From a81c497e8d0d651fa779722f70075b62486ab471 Mon Sep 17 00:00:00 2001 From: Abdessamad Derraz <3028866+Abdess@users.noreply.github.com> Date: Wed, 18 Nov 2026 12:30:02 +0100 Subject: [PATCH] refactor: break the scraper import cycles --- scripts/scraper/batocera_configgen.py | 203 +++++++ scripts/scraper/batocera_launchers.py | 193 +------ scripts/scraper/batocera_scraper.py | 3 +- scripts/scraper/configgen_sites.py | 537 ++++++++++++++++++ scripts/scraper/emuelec_scraper.py | 86 +-- scripts/scraper/emuelec_systems.py | 85 +++ scripts/scraper/knulli_launchers.py | 536 +---------------- scripts/scraper/knulli_scraper.py | 2 +- scripts/scraper/rocknix_packages.py | 37 ++ scripts/scraper/rocknix_scraper.py | 33 +- .../targets/emuelec_targets_scraper.py | 9 +- .../targets/rocknix_targets_scraper.py | 2 +- tests/test_elec_scrapers.py | 18 +- tests/test_launcher_paths.py | 11 +- tests/test_launchers.py | 6 +- tests/test_launchers_knulli.py | 9 +- tests/test_scraper_contract.py | 4 +- tests/test_standalone_links.py | 5 +- tests/test_target_scrapers.py | 2 +- 19 files changed, 921 insertions(+), 860 deletions(-) create mode 100644 scripts/scraper/batocera_configgen.py create mode 100644 scripts/scraper/configgen_sites.py create mode 100644 scripts/scraper/emuelec_systems.py create mode 100644 scripts/scraper/rocknix_packages.py diff --git a/scripts/scraper/batocera_configgen.py b/scripts/scraper/batocera_configgen.py new file mode 100644 index 000000000..4c33417ee --- /dev/null +++ b/scripts/scraper/batocera_configgen.py @@ -0,0 +1,203 @@ +"""Batocera's configgen tree as the launcher readers open it: the generator +modules, the importer that names them, and the paths of batoceraPaths. +KNULLI keeps the same package under its own path.""" + +from __future__ import annotations + +import ast +import posixpath +from collections.abc import Callable +from typing import Any + +from .configgen_launchers import LauncherShapeError, Source, _assigned_name, assigned_value + + +CONFIGGEN = "package/batocera/core/batocera-configgen/configgen/configgen" +GENERATORS = f"{CONFIGGEN}/generators" +PATHS_MODULE = f"{CONFIGGEN}/batoceraPaths.py" +IMPORTER = f"{GENERATORS}/importer.py" + + +def _config_option(node: ast.AST) -> tuple[str, Any] | None: + """(option, default) when `node` is system.config.get*(option, default).""" + if not ( + isinstance(node, ast.Call) + and isinstance(node.func, ast.Attribute) + and node.func.attr.startswith("get") + and ast.unparse(node.func.value) == "system.config" + and node.args + and isinstance(node.args[0], ast.Constant) + ): + return None + second = node.args[1] if len(node.args) > 1 else None + default = second.value if isinstance(second, ast.Constant) else None + return str(node.args[0].value), default + + +def path_constants(source: Source) -> dict[str, str]: + """batoceraPaths' module constants that are plain paths.""" + constants: dict[str, str] = {} + for node in source.tree.body: + assigned = assigned_value(node) + if assigned is None: + continue + name, expr = assigned + value = _path_value(expr, constants) + if value is not None: + constants[name] = value + if "BIOS" not in constants: + source.fail("no BIOS path constant") + return constants + + +def configs_root(cg: Configgen) -> dict[str, str]: + """Where configgen keeps the emulators' configs, relative to the BIOS folder. + + batoceraPaths' CONFIGS (/userdata/system/configs), the folder a generator + starts an emulator from (shadPS4's configs/shadps4), with the lines that + build it and BIOS. + """ + src = cg.source(f"{cg.generators.rsplit('/', 1)[0]}/batoceraPaths.py") + if "CONFIGS" not in cg.paths: + src.fail("no CONFIGS path constant") + wanted: set[str] = {"CONFIGS", "BIOS"} + spans = [] + for node in reversed(src.tree.body): + name = _assigned_name(node) + if name in wanted and isinstance(node, (ast.Assign, ast.AnnAssign)) and node.value: + spans.append((node.lineno, node.end_lineno or node.lineno)) + wanted |= {n.id for n in ast.walk(node.value) if isinstance(n, ast.Name)} + return { + "path": cg.paths["CONFIGS"], + "from_bios": posixpath.relpath(cg.paths["CONFIGS"], cg.bios), + "source_ref": src.ref(spans), + } + + +def _path_value(node: ast.AST | None, constants: dict[str, str]) -> str | None: + if isinstance(node, ast.Name): + return constants.get(node.id) + if ( + isinstance(node, ast.Call) + and isinstance(node.func, ast.Name) + and node.func.id == "Path" + and len(node.args) == 1 + ): + if isinstance(node.args[0], ast.Constant): + return str(node.args[0].value) + return _path_value(node.args[0], constants) + if isinstance(node, ast.BinOp) and isinstance(node.op, ast.Div): + left = _path_value(node.left, constants) + right = node.right.value if isinstance(node.right, ast.Constant) else None + if left is not None and isinstance(right, str): + return f"{left.rstrip('/')}/{right}" + return None + + +def generator_names(source: Source, legacy_map: bool = True) -> dict[str, list[str]]: + """Generator module -> the emulator or core names configgen loads it for. + + legacy_map is false for a configgen written before _LEGACY_GENERATOR_MAP + (KNULLI's), whose importer has the plain map only. + """ + names: dict[str, list[str]] = {} + plain = source.literal(source.assignment("_GENERATOR_MAP").value, "_GENERATOR_MAP") + for emulator, (module, _cls) in plain.items(): + names.setdefault(module, []).append(emulator) + if not legacy_map: + return names + legacy = source.literal( + source.assignment("_LEGACY_GENERATOR_MAP").value, "_LEGACY_GENERATOR_MAP" + ) + for cores in legacy.values(): + for core, (module, _cls) in cores.items(): + names.setdefault(module, []).append(core) + return names + + +class Configgen: + """The configgen tree at one revision, read through `read(path)`. + + root is the configgen package in the repository: Batocera's by default, + KNULLI keeps the same package under its own path. + """ + + def __init__( + self, read: Callable[[str], str], root: str = CONFIGGEN, legacy_map: bool = True + ) -> None: + self._read = read + self._sources: dict[str, Source] = {} + self.generators = f"{root}/generators" + self.importer = f"{self.generators}/importer.py" + self.libretro_options = f"{self.generators}/libretro/libretroOptions.py" + self.paths = path_constants(self.source(f"{root}/batoceraPaths.py")) + self.bios = self.paths["BIOS"] + self._generators = generator_names(self.source(self.importer), legacy_map) + + def source(self, path: str) -> Source: + if path not in self._sources: + self._sources[path] = Source(path, self._read(path)) + return self._sources[path] + + def generator(self, module: str) -> Source: + return self.source(f"{self.generators}/{module.replace('.', '/')}.py") + + def helper(self, module: str, helper: str) -> Source: + """A module the generator imports with `from . import helper`.""" + generator = self.generator(module) + imported = any( + isinstance(node, ast.ImportFrom) + and node.level == 1 + and node.module is None + and any(alias.name == helper for alias in node.names) + for node in ast.walk(generator.tree) + ) + if not imported: + generator.fail(f"does not import {helper}") + return self.source(f"{self.generators}/{module.split('.')[0]}/{helper}.py") + + def emulator(self, module: str) -> str: + """The name configgen loads `module` for (importer.get_generator).""" + if module in self._generators: + return ", ".join(self._generators[module]) + package, _, leaf = module.partition(".") + if leaf == f"{package}Generator": + return package + raise LauncherShapeError(f"{self.importer}: no emulator loads {module}") + + def bios_name(self, node: ast.AST) -> str | None: + """The name under /userdata/bios that an expression spells, if any.""" + if ( + isinstance(node, ast.Call) + and isinstance(node.func, ast.Name) + and node.func.id == "str" + and node.args + ): + return self.bios_name(node.args[0]) + if isinstance(node, ast.Constant) and isinstance(node.value, str): + value = node.value.strip('"') + prefix = self.bios.rstrip("/") + "/" + return value[len(prefix):] if value.startswith(prefix) else None + path = _path_value(node, self.paths) + prefix = self.bios.rstrip("/") + "/" + if path is not None and path.startswith(prefix): + return path[len(prefix):] + return None + + def option_name(self, node: ast.AST) -> tuple[str, str] | None: + """(default name, option) for f"{BIOS}/{system.config.get(option, default)}".""" + if not isinstance(node, ast.JoinedStr) or len(node.values) != 3: + return None + head, sep, tail = node.values + if not ( + isinstance(head, ast.FormattedValue) + and _path_value(head.value, self.paths) == self.bios + and isinstance(sep, ast.Constant) + and sep.value == "/" + and isinstance(tail, ast.FormattedValue) + ): + return None + option = _config_option(tail.value) + if option is None or not isinstance(option[1], str): + return None + return option[1], option[0] diff --git a/scripts/scraper/batocera_launchers.py b/scripts/scraper/batocera_launchers.py index 4216783ba..057cc17fe 100644 --- a/scripts/scraper/batocera_launchers.py +++ b/scripts/scraper/batocera_launchers.py @@ -15,7 +15,6 @@ launcher looks for nothing". from __future__ import annotations import ast -import posixpath import re from collections.abc import Callable, Iterable from typing import Any @@ -35,33 +34,15 @@ from .configgen_launchers import ( _outermost, _run, ) +from .batocera_configgen import Configgen, GENERATORS, _config_option, _path_value +from .configgen_sites import GenericSites, bios_sites -CONFIGGEN = "package/batocera/core/batocera-configgen/configgen/configgen" -GENERATORS = f"{CONFIGGEN}/generators" -PATHS_MODULE = f"{CONFIGGEN}/batoceraPaths.py" -IMPORTER = f"{GENERATORS}/importer.py" LIBRETRO_OPTIONS = f"{GENERATORS}/libretro/libretroOptions.py" # The placeholder a Hatari TOS name carries for its language suffix. LANGUAGE_PLACEHOLDER = "L" -def _config_option(node: ast.AST) -> tuple[str, Any] | None: - """(option, default) when `node` is system.config.get*(option, default).""" - if not ( - isinstance(node, ast.Call) - and isinstance(node.func, ast.Attribute) - and node.func.attr.startswith("get") - and ast.unparse(node.func.value) == "system.config" - and node.args - and isinstance(node.args[0], ast.Constant) - ): - return None - second = node.args[1] if len(node.args) > 1 else None - default = second.value if isinstance(second, ast.Constant) else None - return str(node.args[0].value), default - - def _option_names(node: ast.AST) -> list[str]: """Options a node reads: system.config.get*(o), system.config[o], system.isOptSet(o).""" found: list[str] = [] @@ -85,175 +66,6 @@ def _option_names(node: ast.AST) -> list[str]: return found -def path_constants(source: Source) -> dict[str, str]: - """batoceraPaths' module constants that are plain paths.""" - constants: dict[str, str] = {} - for node in source.tree.body: - assigned = assigned_value(node) - if assigned is None: - continue - name, expr = assigned - value = _path_value(expr, constants) - if value is not None: - constants[name] = value - if "BIOS" not in constants: - source.fail("no BIOS path constant") - return constants - - -def configs_root(cg: Configgen) -> dict[str, str]: - """Where configgen keeps the emulators' configs, relative to the BIOS folder. - - batoceraPaths' CONFIGS (/userdata/system/configs), the folder a generator - starts an emulator from (shadPS4's configs/shadps4), with the lines that - build it and BIOS. - """ - src = cg.source(f"{cg.generators.rsplit('/', 1)[0]}/batoceraPaths.py") - if "CONFIGS" not in cg.paths: - src.fail("no CONFIGS path constant") - wanted: set[str] = {"CONFIGS", "BIOS"} - spans = [] - for node in reversed(src.tree.body): - name = _assigned_name(node) - if name in wanted and isinstance(node, (ast.Assign, ast.AnnAssign)) and node.value: - spans.append((node.lineno, node.end_lineno or node.lineno)) - wanted |= {n.id for n in ast.walk(node.value) if isinstance(n, ast.Name)} - return { - "path": cg.paths["CONFIGS"], - "from_bios": posixpath.relpath(cg.paths["CONFIGS"], cg.bios), - "source_ref": src.ref(spans), - } - - -def _path_value(node: ast.AST | None, constants: dict[str, str]) -> str | None: - if isinstance(node, ast.Name): - return constants.get(node.id) - if ( - isinstance(node, ast.Call) - and isinstance(node.func, ast.Name) - and node.func.id == "Path" - and len(node.args) == 1 - ): - if isinstance(node.args[0], ast.Constant): - return str(node.args[0].value) - return _path_value(node.args[0], constants) - if isinstance(node, ast.BinOp) and isinstance(node.op, ast.Div): - left = _path_value(node.left, constants) - right = node.right.value if isinstance(node.right, ast.Constant) else None - if left is not None and isinstance(right, str): - return f"{left.rstrip('/')}/{right}" - return None - - -def generator_names(source: Source, legacy_map: bool = True) -> dict[str, list[str]]: - """Generator module -> the emulator or core names configgen loads it for. - - legacy_map is false for a configgen written before _LEGACY_GENERATOR_MAP - (KNULLI's), whose importer has the plain map only. - """ - names: dict[str, list[str]] = {} - plain = source.literal(source.assignment("_GENERATOR_MAP").value, "_GENERATOR_MAP") - for emulator, (module, _cls) in plain.items(): - names.setdefault(module, []).append(emulator) - if not legacy_map: - return names - legacy = source.literal( - source.assignment("_LEGACY_GENERATOR_MAP").value, "_LEGACY_GENERATOR_MAP" - ) - for cores in legacy.values(): - for core, (module, _cls) in cores.items(): - names.setdefault(module, []).append(core) - return names - - -class Configgen: - """The configgen tree at one revision, read through `read(path)`. - - root is the configgen package in the repository: Batocera's by default, - KNULLI keeps the same package under its own path. - """ - - def __init__( - self, read: Callable[[str], str], root: str = CONFIGGEN, legacy_map: bool = True - ) -> None: - self._read = read - self._sources: dict[str, Source] = {} - self.generators = f"{root}/generators" - self.importer = f"{self.generators}/importer.py" - self.libretro_options = f"{self.generators}/libretro/libretroOptions.py" - self.paths = path_constants(self.source(f"{root}/batoceraPaths.py")) - self.bios = self.paths["BIOS"] - self._generators = generator_names(self.source(self.importer), legacy_map) - - def source(self, path: str) -> Source: - if path not in self._sources: - self._sources[path] = Source(path, self._read(path)) - return self._sources[path] - - def generator(self, module: str) -> Source: - return self.source(f"{self.generators}/{module.replace('.', '/')}.py") - - def helper(self, module: str, helper: str) -> Source: - """A module the generator imports with `from . import helper`.""" - generator = self.generator(module) - imported = any( - isinstance(node, ast.ImportFrom) - and node.level == 1 - and node.module is None - and any(alias.name == helper for alias in node.names) - for node in ast.walk(generator.tree) - ) - if not imported: - generator.fail(f"does not import {helper}") - return self.source(f"{self.generators}/{module.split('.')[0]}/{helper}.py") - - def emulator(self, module: str) -> str: - """The name configgen loads `module` for (importer.get_generator).""" - if module in self._generators: - return ", ".join(self._generators[module]) - package, _, leaf = module.partition(".") - if leaf == f"{package}Generator": - return package - raise LauncherShapeError(f"{self.importer}: no emulator loads {module}") - - def bios_name(self, node: ast.AST) -> str | None: - """The name under /userdata/bios that an expression spells, if any.""" - if ( - isinstance(node, ast.Call) - and isinstance(node.func, ast.Name) - and node.func.id == "str" - and node.args - ): - return self.bios_name(node.args[0]) - if isinstance(node, ast.Constant) and isinstance(node.value, str): - value = node.value.strip('"') - prefix = self.bios.rstrip("/") + "/" - return value[len(prefix):] if value.startswith(prefix) else None - path = _path_value(node, self.paths) - prefix = self.bios.rstrip("/") + "/" - if path is not None and path.startswith(prefix): - return path[len(prefix):] - return None - - def option_name(self, node: ast.AST) -> tuple[str, str] | None: - """(default name, option) for f"{BIOS}/{system.config.get(option, default)}".""" - if not isinstance(node, ast.JoinedStr) or len(node.values) != 3: - return None - head, sep, tail = node.values - if not ( - isinstance(head, ast.FormattedValue) - and _path_value(head.value, self.paths) == self.bios - and isinstance(sep, ast.Constant) - and sep.value == "/" - and isinstance(tail, ast.FormattedValue) - ): - return None - option = _config_option(tail.value) - if option is None or not isinstance(option[1], str): - return None - return option[1], option[0] - - def _raise_message(source: Source, scope: ast.AST, guard: str | None) -> str: """The message of `if not : raise X("...")` in scope.""" for node in ast.walk(scope): @@ -1190,7 +1002,6 @@ SEARCH_PATH_GENERATORS = ("mame/mameGenerator.py",) def search_paths(cg: Configgen) -> list[Launcher]: """Every /userdata/bios path a generator's command line names, read as KNULLI's generic reader reads its fork of the same generator.""" - from .knulli_launchers import GenericSites, bios_sites # A boot disk image the command line names (the Macintosh's # /userdata/bios/.img) is a file, no search path. return [ diff --git a/scripts/scraper/batocera_scraper.py b/scripts/scraper/batocera_scraper.py index d70c73f31..a0907b939 100644 --- a/scripts/scraper/batocera_scraper.py +++ b/scripts/scraper/batocera_scraper.py @@ -30,7 +30,8 @@ from .base_scraper import ( md5_field, requirement_entry, ) -from .batocera_launchers import Configgen, configs_root, extract_launchers +from .batocera_configgen import Configgen, configs_root +from .batocera_launchers import extract_launchers from .targets.batocera_targets_scraper import BuildSelection from .targets.batocera_targets_scraper import Scraper as BoardTargets diff --git a/scripts/scraper/configgen_sites.py b/scripts/scraper/configgen_sites.py new file mode 100644 index 000000000..48c194910 --- /dev/null +++ b/scripts/scraper/configgen_sites.py @@ -0,0 +1,537 @@ +"""Every /userdata/bios path a configgen generator names, with its context. + +A generator names a BIOS path in a command line, a config key, an +environment variable, a copy or a presence test. bios_sites() reads each of +those uses with ast, and a GenericSites spec says whether the path is a file +or a directory. KNULLI reads most of its generators this way, Batocera its +MAME search paths.""" + +from __future__ import annotations + +import ast +import re +from collections.abc import Iterator +from dataclasses import dataclass, field + +from .batocera_configgen import Configgen, _path_value +from .configgen_launchers import Launcher, Source, _assigned_name, end_line + + +def _bound(node: ast.AST) -> ast.expr | None: + """The value of an assignment statement.""" + value = getattr(node, "value", None) + return value if isinstance(value, ast.expr) else None + + +def _cores_of(test: ast.expr) -> list[str]: + """Core names `system.config['core'] == 'x'`, `in [...]` or an `or` of them tests.""" + if isinstance(test, ast.BoolOp) and isinstance(test.op, ast.Or): + return [core for value in test.values for core in _cores_of(value)] + if ( + isinstance(test, ast.Compare) + and ast.unparse(test.left) == "system.config['core']" + and len(test.ops) == 1 + ): + right = test.comparators[0] + if isinstance(test.ops[0], ast.Eq) and isinstance(right, ast.Constant): + return [str(right.value)] + if isinstance(test.ops[0], ast.In) and isinstance(right, (ast.List, ast.Tuple)): + return [str(e.value) for e in right.elts if isinstance(e, ast.Constant)] + return [] + + +@dataclass(frozen=True) +class GenericSites: + """A generator module whose BIOS path uses bios_sites() reads. + + kind is fixed_name when the path names a file, passes_path when it names + a directory. A copy is recorded as `copies` whatever the kind, its names + read from the folder the code copies from and passes_to the target. caller + names the module and function whose core test selects the cores this + helper module runs for, emulator the name when no core test does. + """ + + path: str + kind: str + build: str = "standalone" + emulator: str | None = None + caller: tuple[str, str] | None = None + + +# The names configgen gives the command it builds. +COMMAND_NAMES = {"commandArray", "commandLine"} + + +@dataclass +class _Site: + """One use of a BIOS path, and the record fields it contributes.""" + + path: str + passes_to: str + kind: str | None + lines: list[tuple[int, int]] + conditions: list[str] + cores: list[str] + expands: dict[str, list[str]] = field(default_factory=dict) + # A copy reads its file from `source` and hands it to `passes_to`. + source: str | None = None + + +class _Reader: + """The BIOS path uses of one generator module.""" + + def __init__(self, cg: Configgen, src: Source) -> None: + self.cg = cg + self.src = src + self.bios = cg.bios.rstrip("/") + self.parents: dict[int, ast.AST] = {} + self.copy_sources: dict[int, str] = {} + for parent in ast.walk(src.tree): + for child in ast.iter_child_nodes(parent): + self.parents[id(child)] = parent + self.constants = dict(cg.paths) + folder = src.path.rsplit("/", 1)[0] + for node in src.tree.body: + if ( + isinstance(node, ast.ImportFrom) + and node.level == 1 + and node.module + and node.module.endswith("Paths") + ): + paths = cg.source(f"{folder}/{node.module}.py") + self._define(paths.tree.body) + self._define(src.tree.body) + + def _define(self, body: list[ast.stmt]) -> None: + for node in body: + name = _assigned_name(node) + value = self.resolve(getattr(node, "value", None)) + if name is not None and value is not None: + self.constants[name] = value + + def under_bios(self, value: str | None) -> bool: + return value is not None and ( + value.rstrip("/") == self.bios or f"{self.bios}/" in value + ) + + def resolve(self, node: ast.AST | None) -> str | None: + """The path an expression spells, unknown parts of an f-string as .""" + if node is None: + return None + value = _path_value(node, self.constants) + if value is not None: + return value + if isinstance(node, ast.Constant) and isinstance(node.value, str): + text = node.value.strip('"') + return text if text.startswith("/") else None + if isinstance(node, ast.Call) and ast.unparse(node.func) == "str" and len(node.args) == 1: + return self.resolve(node.args[0]) + if isinstance(node, ast.JoinedStr): + parts = [] + for part in node.values: + if isinstance(part, ast.Constant): + parts.append(str(part.value)) + else: + # The other parts of an f-string are its {placeholders}. + expr = part.value if isinstance(part, ast.FormattedValue) else part + inner = self.resolve(expr) + parts.append(inner if inner is not None else f"<{ast.unparse(expr)}>") + return "".join(parts).strip('"') + if ( + isinstance(node, ast.BinOp) + and isinstance(node.op, ast.Div) + and isinstance(node.right, (ast.Constant, ast.Name)) + ): + left = self.resolve(node.left) + right = node.right.value if isinstance(node.right, ast.Constant) else None + if isinstance(node.right, ast.Name): + right = self._placeholder(node.right) + if left is not None and isinstance(right, str): + return f"{left.rstrip('/')}/{right}" + return None + + def _placeholder(self, name: ast.Name) -> str | None: + """{var} for a comprehension variable over a literal list.""" + comprehension = self._comprehension(name) + if comprehension is None: + return None + return "{" + name.id + "}" + + def _comprehension(self, name: ast.Name) -> tuple[str, list[str]] | None: + node: ast.AST | None = name + while node is not None: + node = self.parents.get(id(node)) + if isinstance(node, (ast.GeneratorExp, ast.ListComp)): + for generator in node.generators: + if isinstance(generator.target, ast.Name) and generator.target.id == name.id: + values = self._literal_list(generator.iter, node) + return (name.id, values) if values else None + return None + + def _literal_list(self, node: ast.AST | None, scope_of: ast.AST) -> list[str] | None: + if isinstance(node, ast.List): + return [str(e.value) for e in node.elts if isinstance(e, ast.Constant)] + if isinstance(node, ast.Name): + scope = self.function_of(scope_of) + bound = [ + n for n in ast.walk(scope or self.src.tree) + if _assigned_name(n) == node.id and isinstance(_bound(n), ast.List) + ] + if len(bound) == 1: + return self._literal_list(_bound(bound[0]), scope_of) + return None + + def function_of(self, node: ast.AST) -> ast.FunctionDef | None: + current: ast.AST | None = node + while current is not None: + current = self.parents.get(id(current)) + if isinstance(current, ast.FunctionDef): + return current + return None + + def statement_of(self, node: ast.AST) -> ast.stmt: + while not isinstance(node, ast.stmt): + node = self.parents[id(node)] + return node + + def maximal(self) -> Iterator[tuple[ast.AST, str]]: + """Each expression spelling a BIOS path that no larger one contains.""" + for node in ast.walk(self.src.tree): + if not isinstance(node, ast.expr): + continue + value = self.resolve(node) + if value is None and isinstance(node, ast.Constant) and isinstance(node.value, str): + # A line written to a config file: openmsx's settings.tcl. + written = re.search(rf"{re.escape(self.bios)}(?:/[^\s\"';]*)?", node.value) + parent = self.parents.get(id(node)) + if written and isinstance(parent, ast.Call) and ast.unparse(parent.func).endswith(".write"): + yield node, written.group(0) + continue + if value is None or not self.under_bios(value): + continue + parent = self.parents.get(id(node)) + if isinstance(parent, (ast.FormattedValue, ast.JoinedStr)): + continue + if isinstance(parent, ast.expr) and self.under_bios(self.resolve(parent)): + continue + if isinstance(parent, ast.Call) and ast.unparse(parent.func) == "str": + continue + yield node, value + + def conditions( + self, node: ast.AST, guards: bool = False + ) -> tuple[list[str], list[tuple[int, int]]]: + """Tests of the ifs a node sits in, outermost first, and their lines. + + A presence test of a BIOS path is a guard, kept for its lines only, + unless guards is set: a copy made only when its source or its target + is there carries the test as a condition. + """ + tests: list[str] = [] + spans: list[tuple[int, int]] = [] + child, parent = node, self.parents.get(id(node)) + while parent is not None and not isinstance(parent, ast.FunctionDef): + if isinstance(parent, ast.If) and child is not parent.test: + spans.append(self.src.span(parent.test)) + text = ast.unparse(parent.test) + if guards or not self._is_guard(parent.test): + in_else = any(child is stmt for stmt in parent.orelse) + tests.append(f"not ({text})" if in_else else text) + child, parent = parent, self.parents.get(id(parent)) + return list(reversed(tests)), spans + + def _is_guard(self, test: ast.expr) -> bool: + for n in ast.walk(test): + if not ( + isinstance(n, ast.Call) + and isinstance(n.func, ast.Attribute) + and n.func.attr == "exists" + ): + continue + receiver = n.func.value + if self.under_bios(self.resolve(receiver)): + return True + if isinstance(receiver, ast.Name) and self.local_value(receiver) is not None: + return True + return False + + def cores(self, node: ast.AST) -> list[str]: + child, parent = node, self.parents.get(id(node)) + while parent is not None: + if isinstance(parent, ast.If) and child is not parent.test and _cores_of(parent.test): + return _cores_of(parent.test) + child, parent = parent, self.parents.get(id(parent)) + return [] + + def uses(self, node: ast.AST, value: str) -> Iterator[tuple[ast.AST, str | None, str | None]]: + """(node read, passes_to, kind) for each consumer of a BIOS path expression. + + A path bound to a local name is followed to each read of that name. + A use with no consumer (a presence test, a mkdir) yields passes_to None. + """ + parent = self.parents.get(id(node)) + if isinstance(parent, ast.Assign) and len(parent.targets) == 1: + target = parent.targets[0] + if isinstance(target, ast.Name): + scope = self.function_of(parent) + if scope is None: + return + for read in ast.walk(scope): + if ( + isinstance(read, ast.Name) + and read.id == target.id + and isinstance(read.ctx, ast.Load) + and read.lineno > parent.lineno + ): + yield from self.uses(read, value) + return + if isinstance(target, ast.Subscript) and isinstance(target.slice, ast.Constant): + yield node, str(target.slice.value), None + return + yield node, *self.consumer(node, value) + + def _command_line(self, display: ast.List | ast.Tuple) -> bool: + """Whether a list display is (part of) the command configgen runs. + + It is assigned or added to commandArray (or commandLine for the + libretro MAME cmd file), or it starts with an absolute binary path. + """ + first = display.elts[0] if display.elts else None + if isinstance(first, ast.Constant) and str(first.value).startswith("/"): + return True + holder = self.parents.get(id(display)) + targets: list[ast.expr] = [] + if isinstance(holder, ast.Assign): + targets = holder.targets + elif isinstance(holder, ast.AugAssign): + targets = [holder.target] + elif ( + isinstance(holder, ast.Call) + and isinstance(holder.func, ast.Attribute) + and holder.func.attr in ("extend", "append") + ): + targets = [holder.func.value] + names = { + ast.unparse(t.value if isinstance(t, ast.Subscript) else t) for t in targets + } + return bool(names & COMMAND_NAMES) + + def local_value(self, name: ast.Name) -> str | None: + """The BIOS path a local name is bound to once in its function.""" + scope = self.function_of(name) + if scope is None: + return None + bound = [ + self.resolve(_bound(n)) + for n in ast.walk(scope) if _assigned_name(n) == name.id + ] + return bound[0] if len(bound) == 1 and self.under_bios(bound[0]) else None + + def consumer(self, node: ast.AST, value: str) -> tuple[str | None, str | None]: + parent = self.parents.get(id(node)) + if isinstance(parent, (ast.List, ast.Tuple)): + return self._listed_consumer(node, parent, value) + if isinstance(parent, ast.Call): + return self._call_consumer(node, parent, value) + if isinstance(parent, ast.Dict): + return self._dict_consumer(node, parent) + return None, None + + def _listed_consumer( + self, node: ast.AST, parent: ast.List | ast.Tuple, value: str + ) -> tuple[str | None, str | None]: + holder = self.parents.get(id(parent)) + if isinstance(holder, (ast.For, ast.comprehension)): + return None, None + if not self._command_line(parent): + return None, None + index = next(i for i, e in enumerate(parent.elts) if e is node) + if isinstance(node, ast.JoinedStr) and isinstance(node.values[0], ast.Constant): + flag = str(node.values[0].value) + if flag.startswith("-") and flag.endswith("=") and value.startswith(flag): + return f"command line {flag[:-1]}", None + previous = parent.elts[index - 1] if index else None + if isinstance(previous, ast.Constant) and str(previous.value).startswith("-"): + return f"command line {previous.value!s}", None + if index: + return f"command line argument {index}", None + return None, None + + def _call_consumer( + self, node: ast.AST, parent: ast.Call, value: str + ) -> tuple[str | None, str | None]: + func = parent.func + attr = func.attr if isinstance(func, ast.Attribute) else None + consts = [a.value for a in parent.args if isinstance(a, ast.Constant)] + if attr == "save" and len(parent.args) == 2 and parent.args[1] is node and consts: + return str(consts[0]), None + if attr == "set" and len(parent.args) == 3 and parent.args[2] is node and len(consts) >= 2: + return f"[{consts[0]!s}] {consts[1]!s}", None + receiver = func.value if isinstance(func, ast.Attribute) else None + if attr in ("copy", "copyfile", "copy2") and receiver is not None and ast.unparse(receiver) == "shutil": + source, target = parent.args[0], parent.args[1] + self.copy_sources[id(node)] = value if source is node else ( + self.resolve(source) or ast.unparse(source) + ) + return (value if target is node else self.resolve(target) or ast.unparse(target)), "copies" + if ( + attr == "append" + and isinstance(receiver, ast.Name) + and receiver.id in COMMAND_NAMES + and isinstance(node, ast.JoinedStr) + and isinstance(node.values[0], ast.Constant) + ): + flag = str(node.values[0].value) + if flag.startswith("-") and flag.endswith("=") and value.startswith(flag): + return f"command line {flag[:-1]}", None + if attr == "write" and isinstance(node, ast.Constant): + return f"written: {str(node.value).strip()}", None + return None, None + + def _dict_consumer(self, node: ast.AST, parent: ast.Dict) -> tuple[str | None, str | None]: + key = next( + (k for k, v in zip(parent.keys, parent.values) if v is node), None + ) + if not isinstance(key, ast.Constant): + return None, None + holder = self.parents.get(id(parent)) + is_env = ( + isinstance(holder, ast.keyword) and holder.arg == "env" + ) or (holder is not None and _assigned_name(holder) == "env") + return (f"environment {key.value!s}" if is_env else str(key.value)), None + + def sites(self) -> list[_Site]: + found: list[_Site] = [] + guards: list[tuple[ast.AST, str]] = [] + for node, value in self.maximal(): + if isinstance(self.statement_of(node), (ast.Import, ast.ImportFrom)): + continue + if self.function_of(node) is None and isinstance(self.parents.get(id(node)), ast.Assign): + continue + for read, passes_to, kind in self.uses(node, value): + parent = self.parents.get(id(read)) + if ( + passes_to is None + and isinstance(parent, ast.Attribute) + and parent.attr == "exists" + ): + guards.append((read, value)) + if passes_to is None: + continue + found.append(self._site(read, value, passes_to, kind, node)) + for read, value in guards: + if any(site.path == value for site in found): + site = next(s for s in found if s.path == value) + site.lines.append(self.src.span(self.statement_of(read))) + continue + found.append(self._guard_site(read, value)) + return sorted(found, key=lambda site: site.lines[0]) + + def _site( + self, read: ast.AST, value: str, passes_to: str, kind: str | None, defined: ast.AST + ) -> _Site: + tests, spans = self.conditions(read, guards=kind == "copies") + lines = [self.src.span(self.statement_of(read)), *spans] + if defined is not read: + # A path bound in one branch and read after the if: the branch + # that bound it is a condition of the read. + bound_tests, bound_spans = self.conditions(defined) + tests = list(dict.fromkeys([*bound_tests, *tests])) + lines += [self.src.span(self.statement_of(defined)), *bound_spans] + return _Site( + value, passes_to, kind, lines, tests, self.cores(read), self._expands(read), + self.copy_sources.get(id(read)), + ) + + def _guard_site(self, read: ast.AST, value: str) -> _Site: + """A presence test whose if body is the only consumer of the path.""" + test = self.statement_of(read) + if not isinstance(test, ast.If): + self.src.fail(f"line {test.lineno} tests a BIOS path outside an if") + first = test.body[0] + described = ast.unparse(first) + call = first.value if isinstance(first, ast.Expr) else None + if isinstance(call, ast.Call) and isinstance(call.func, ast.Attribute) and call.func.attr == "set": + literal = [a.value for a in call.args if isinstance(a, ast.Constant)] + if len(literal) == 3: + described = f"[{literal[0]!s}] {literal[1]!s} = {literal[2]!s}" + tests, spans = self.conditions(test) + return _Site( + value, f"presence sets {described}", None, + [(test.lineno, end_line(first)), *spans], + tests, self.cores(test), self._expands(read), + ) + + def _expands(self, node: ast.AST) -> dict[str, list[str]]: + found: dict[str, list[str]] = {} + for name in ast.walk(node): + if isinstance(name, ast.Name): + bound = self._comprehension(name) + if bound is not None: + found[bound[0]] = bound[1] + return found + + +def _caller_cores(cg: Configgen, caller: tuple[str, str]) -> list[str]: + path, function = caller + src = cg.source(f"{cg.generators}/{path}") + for node in ast.walk(src.tree): + if not isinstance(node, ast.If) or not _cores_of(node.test): + continue + if any( + isinstance(n, ast.Call) and ast.unparse(n.func).endswith(f".{function}") + for stmt in node.body for n in ast.walk(stmt) + ): + return _cores_of(node.test) + return src.fail(f"no core test calls {function}") + + +def bios_sites(cg: Configgen, spec: GenericSites) -> list[Launcher]: + """One record per BIOS path and consumer of a generator module.""" + src = cg.source(f"{cg.generators}/{spec.path}") + reader = _Reader(cg, src) + sites = reader.sites() + if not sites: + src.fail("hands over no /userdata/bios path") + module = spec.path.removesuffix(".py").replace("/", ".") + caller_cores = _caller_cores(cg, spec.caller) if spec.caller else [] + grouped: dict[tuple[str, str, str, tuple[str, ...]], list[_Site]] = {} + for site in sites: + flag = site.passes_to.removeprefix("command line ") + if site.path.startswith(f"{flag}="): + site.path = site.path[len(flag) + 1:] + emulator = ( + spec.emulator + or ", ".join(site.cores or caller_cores) + or (cg.emulator(module) if spec.build == "standalone" else "") + ) + if not emulator: + src.fail(f"no core runs the {site.passes_to} use at line {site.lines[0][0]}") + key = (emulator, site.path, site.passes_to, tuple(site.conditions)) + grouped.setdefault(key, []).append(site) + prefix = cg.bios.rstrip("/") + "/" + launchers = [] + for (emulator, path, passes_to, _conditions), group in grouped.items(): + kind = group[0].kind or spec.kind + conditions = list(dict.fromkeys(c for site in group for c in site.conditions)) + expands = {k: v for site in group for k, v in site.expands.items()} + names: list[str] = [] + search_dir = path + source = group[0].source + if kind == "copies" and source is not None and not source.startswith(prefix): + # Copied into BIOS: the file is read from the folder it comes from. + search_dir, _, name = source.rpartition("/") + names = [name] + elif kind in ("fixed_name", "copies"): + if not path.startswith(prefix): + src.fail(f"{path} names no file under {cg.bios}") + names, search_dir = [path[len(prefix):]], cg.bios + launchers.append(Launcher( + emulator=emulator, build=spec.build, kind=kind, names=names, + expands=expands or None, + case_insensitive=False if names else None, + search_dir=search_dir, passes_to=passes_to, fails_when_missing=False, + depends_on_option=" and ".join(conditions) or None, + source_ref=src.ref([span for site in group for span in site.lines]), + )) + return launchers diff --git a/scripts/scraper/emuelec_scraper.py b/scripts/scraper/emuelec_scraper.py index 6d87d4ad9..6c848d71b 100644 --- a/scripts/scraper/emuelec_scraper.py +++ b/scripts/scraper/emuelec_scraper.py @@ -27,12 +27,9 @@ Verification (batocera-systems at the release tag): from __future__ import annotations import re -import shlex import urllib.error import urllib.request -from model.safeparse import yaml_load_upstream - from .base_scraper import BaseScraper, BiosRequirement, fetch_github_latest_version from .batocera_scraper import ( SYSTEM_SLUG_MAP as BATOCERA_SLUGS, @@ -45,21 +42,27 @@ from .batocera_scraper import ( ) from .emuelec_launchers import extract_launchers from .es_emulators import ( - SystemEmulators, attach_system_cores, es_cores, json_systems, system_cores, ) from scraper.shell_launchers import RepoTree +from .emuelec_systems import ( + BUILDS_OF, + ES_SYSTEMS_TEMPLATE, + PORTS_TEMPLATE, + RUNNERS, + _RAW, + port_engines, + with_ports, +) +from .targets.emuelec_targets_scraper import Scraper as DeviceTargets PLATFORM_NAME = "emuelec" REPO = "EmuELEC/EmuELEC" -_RAW = "https://raw.githubusercontent.com/EmuELEC/EmuELEC/{ref}/" SOURCE_TEMPLATE = _RAW + "packages/sx05re/emuelec/bin/batocera/batocera-systems" -ES_SYSTEMS_TEMPLATE = _RAW + "packages/sx05re/emuelec-emulationstation/config/es_systems.json" -PORTS_TEMPLATE = _RAW + "packages/sx05re/emuelec-ports/sources/ports.yaml" # Batocera's names, plus the keys EmuELEC writes that Batocera does not: # console keys under the slug the other scrapers give them, and each port @@ -92,35 +95,6 @@ SYSTEM_SLUG_MAP = { "RigelEngine": "duke-nukem-2", } -# es_systems.json names libretro cores under `libretro`, and `retrorun` -# loads the libretro core it lists. emuelecRunEmu.sh:101-116 turns either -# into ${CORE}_libretro. Any other emulator runs the core it names -# (EMU="${CORE}", line 107) through the case at lines 164-353. -RUNNERS: dict[str, str | None] = {"libretro": None, "retrorun": None} - -# A standalone emulator and the libretro core of the same emulator, from the -# packages each one builds (packages/sx05re/emulators//package.mk -# PKG_SITE): hatarisa hatari/hatari, stellasa stella-emu/stella, fbneoSA -# finalburnneo/FBNeo, flycastsa flyinghead/flycast, scummvmsa -# scummvm/scummvm, PPSSPPSDL hrydgard/ppsspp. -BUILDS_OF = { - "HATARISA": "hatari", - "STELLASA": "stella", - "FBNEOSA": "fbneo", - "flycastsa": "flycast", - "SCUMMVMSA": "scummvm", - "PPSSPPSDL": "ppsspp", -} - -# The ES system `ports` (es_systems.json:2570-2590) runs one generated -# script per entry of ports.yaml through emuelecRunApp.sh:22, and its single -# emulator `ports` is that dispatch, not a program. The scripts are rendered -# from port.sh.j2 by port_builder.py (emuelec-ports/package.mk:62-64): each -# runs its `commands`, so the engine is the libretro core a command hands -# emuelecRunEmu.sh with -C (lines 367-369 load _libretro.so), or the -# program `port_exe` names. -PORTS_SYSTEM = "ports" - def launcher_revision(url: str) -> str: """The tag or commit a batocera-systems URL is read at.""" @@ -130,45 +104,6 @@ def launcher_revision(url: str) -> str: return found.group(1) -def port_engines(text: str) -> list[tuple[str, str, str | None, bool]]: - """(port, engine, check_bios key, libretro?) for each entry of ports.yaml. - - The engine is written as the OS writes it: the libretro core a command - hands emuelecRunEmu.sh with -C, else `port_exe`. `check_bios` is the - batocera-systems key the script hands ee_check_bios on a failed start - (port.sh.j2:23-25), the key the port's files are listed under. - """ - data = yaml_load_upstream(text) - if not isinstance(data, dict) or not data: - raise ValueError("ports.yaml names no port") - engines = [] - for port, spec in data.items(): - core = None - for command in map(str, spec.get("commands") or []): - if "emuelecRunEmu.sh" in command: - core = next( - (w[2:] for w in shlex.split(command) if w.startswith("-C")), core - ) - engine = core or spec.get("port_exe") - if not engine: - raise ValueError(f"ports.yaml: {port} names neither a core nor port_exe") - engines.append((str(port), str(engine), spec.get("check_bios"), core is not None)) - return engines - - -def with_ports( - systems: SystemEmulators, engines: list[tuple[str, str, str | None, bool]] -) -> SystemEmulators: - """The ES systems, each port engine filed under `ports` and its own key.""" - def entry(engine: str, libretro: bool) -> tuple[str, list[str]]: - return ("libretro", [engine]) if libretro else (engine, [engine]) - - result = {**systems, PORTS_SYSTEM: [entry(e, lr) for _, e, _, lr in engines]} - for _, engine, key, libretro in engines: - if key: - result[key] = [*result.get(key, []), entry(engine, libretro)] - return result - class Scraper(BaseScraper): """Scraper for EmuELEC's batocera-systems.""" @@ -249,7 +184,6 @@ class Scraper(BaseScraper): engines depend on emuelec-ports, which no package of an image depends on, and flycast-dojo is in no device list (UNBUILT there). """ - from .targets.emuelec_targets_scraper import Scraper as DeviceTargets targets = DeviceTargets().device_targets(self.tag)["targets"] return {name for entry in targets.values() for name in entry["cores"]} diff --git a/scripts/scraper/emuelec_systems.py b/scripts/scraper/emuelec_systems.py new file mode 100644 index 000000000..04222f704 --- /dev/null +++ b/scripts/scraper/emuelec_systems.py @@ -0,0 +1,85 @@ +"""What EmuELEC runs per system, read by its BIOS scraper and its device targets. + +es_systems.json names the emulators of each system, ports.yaml the engine of +each port, and emuelecRunEmu.sh decides which of them are libretro cores.""" + +from __future__ import annotations + +import shlex + +from .es_emulators import SystemEmulators +from model.safeparse import yaml_load_upstream + + +_RAW = "https://raw.githubusercontent.com/EmuELEC/EmuELEC/{ref}/" +ES_SYSTEMS_TEMPLATE = _RAW + "packages/sx05re/emuelec-emulationstation/config/es_systems.json" +PORTS_TEMPLATE = _RAW + "packages/sx05re/emuelec-ports/sources/ports.yaml" + +# es_systems.json names libretro cores under `libretro`, and `retrorun` +# loads the libretro core it lists. emuelecRunEmu.sh:101-116 turns either +# into ${CORE}_libretro. Any other emulator runs the core it names +# (EMU="${CORE}", line 107) through the case at lines 164-353. +RUNNERS: dict[str, str | None] = {"libretro": None, "retrorun": None} + +# A standalone emulator and the libretro core of the same emulator, from the +# packages each one builds (packages/sx05re/emulators//package.mk +# PKG_SITE): hatarisa hatari/hatari, stellasa stella-emu/stella, fbneoSA +# finalburnneo/FBNeo, flycastsa flyinghead/flycast, scummvmsa +# scummvm/scummvm, PPSSPPSDL hrydgard/ppsspp. +BUILDS_OF = { + "HATARISA": "hatari", + "STELLASA": "stella", + "FBNEOSA": "fbneo", + "flycastsa": "flycast", + "SCUMMVMSA": "scummvm", + "PPSSPPSDL": "ppsspp", +} + +# The ES system `ports` (es_systems.json:2570-2590) runs one generated +# script per entry of ports.yaml through emuelecRunApp.sh:22, and its single +# emulator `ports` is that dispatch, not a program. The scripts are rendered +# from port.sh.j2 by port_builder.py (emuelec-ports/package.mk:62-64): each +# runs its `commands`, so the engine is the libretro core a command hands +# emuelecRunEmu.sh with -C (lines 367-369 load _libretro.so), or the +# program `port_exe` names. +PORTS_SYSTEM = "ports" + + +def port_engines(text: str) -> list[tuple[str, str, str | None, bool]]: + """(port, engine, check_bios key, libretro?) for each entry of ports.yaml. + + The engine is written as the OS writes it: the libretro core a command + hands emuelecRunEmu.sh with -C, else `port_exe`. `check_bios` is the + batocera-systems key the script hands ee_check_bios on a failed start + (port.sh.j2:23-25), the key the port's files are listed under. + """ + data = yaml_load_upstream(text) + if not isinstance(data, dict) or not data: + raise ValueError("ports.yaml names no port") + engines = [] + for port, spec in data.items(): + core = None + for command in map(str, spec.get("commands") or []): + if "emuelecRunEmu.sh" in command: + core = next( + (w[2:] for w in shlex.split(command) if w.startswith("-C")), core + ) + engine = core or spec.get("port_exe") + if not engine: + raise ValueError(f"ports.yaml: {port} names neither a core nor port_exe") + engines.append((str(port), str(engine), spec.get("check_bios"), core is not None)) + return engines + + +def with_ports( + systems: SystemEmulators, engines: list[tuple[str, str, str | None, bool]] +) -> SystemEmulators: + """The ES systems, each port engine filed under `ports` and its own key.""" + def entry(engine: str, libretro: bool) -> tuple[str, list[str]]: + return ("libretro", [engine]) if libretro else (engine, [engine]) + + result = {**systems, PORTS_SYSTEM: [entry(e, lr) for _, e, _, lr in engines]} + for _, engine, key, libretro in engines: + if key: + result[key] = [*result.get(key, []), entry(engine, libretro)] + return result diff --git a/scripts/scraper/knulli_launchers.py b/scripts/scraper/knulli_launchers.py index 98039c91c..fadfa0dc7 100644 --- a/scripts/scraper/knulli_launchers.py +++ b/scripts/scraper/knulli_launchers.py @@ -22,17 +22,15 @@ from __future__ import annotations import ast import posixpath import re -from collections.abc import Callable, Iterator -from dataclasses import dataclass, field +from collections.abc import Callable +from dataclasses import dataclass from typing import Any import yaml from .batocera_launchers import ( PATH_PATCHES, - Configgen, config_directories, - _path_value, _render, _system_branches, duckstation, @@ -46,14 +44,23 @@ from .batocera_launchers import ( working_directories, xemu, ) +from .batocera_configgen import Configgen, _path_value from .configgen_launchers import ( Launcher, LauncherShapeError, Source, _assigned_name, - end_line, ) from scraper.shell_launchers import LauncherPatternMissing, Script, source_ref +from .configgen_sites import ( + COMMAND_NAMES, + GenericSites, + _Reader, + _bound, + _caller_cores, + _cores_of, + bios_sites, +) CONFIGGEN = "package/system/knulli-configgen/configgen/configgen" GENERATORS = f"{CONFIGGEN}/generators" @@ -83,12 +90,6 @@ def _lines(node: ast.AST) -> tuple[int, int]: return first, getattr(node, "end_lineno", None) or first -def _bound(node: ast.AST) -> ast.expr | None: - """The value of an assignment statement.""" - value = getattr(node, "value", None) - return value if isinstance(value, ast.expr) else None - - def configgen(read: Callable[[str], str]) -> Configgen: """KNULLI's configgen: Batocera's reader at KNULLI's package, no legacy map.""" return Configgen(read, CONFIGGEN, legacy_map=False) @@ -229,23 +230,6 @@ def _quoted(node: ast.AST) -> str | None: return None -def _cores_of(test: ast.expr) -> list[str]: - """Core names `system.config['core'] == 'x'`, `in [...]` or an `or` of them tests.""" - if isinstance(test, ast.BoolOp) and isinstance(test.op, ast.Or): - return [core for value in test.values for core in _cores_of(value)] - if ( - isinstance(test, ast.Compare) - and ast.unparse(test.left) == "system.config['core']" - and len(test.ops) == 1 - ): - right = test.comparators[0] - if isinstance(test.ops[0], ast.Eq) and isinstance(right, ast.Constant): - return [str(right.value)] - if isinstance(test.ops[0], ast.In) and isinstance(right, (ast.List, ast.Tuple)): - return [str(e.value) for e in right.elts if isinstance(e, ast.Constant)] - return [] - - # libretro core options whose value names the BIOS file the core opens, # the same two batocera_launchers.FILE_OPTIONS reads. FILE_OPTIONS = ("o2em_bios", "neocd_bios") @@ -322,27 +306,6 @@ def _saved(body: list[ast.stmt], setting: str) -> str | None: # Generic reading of the /userdata/bios paths a generator hands over. -@dataclass(frozen=True) -class GenericSites: - """A generator module whose BIOS path uses bios_sites() reads. - - kind is fixed_name when the path names a file, passes_path when it names - a directory. A copy is recorded as `copies` whatever the kind, its names - read from the folder the code copies from and passes_to the target. caller - names the module and function whose core test selects the cores this - helper module runs for, emulator the name when no core test does. - """ - - path: str - kind: str - build: str = "standalone" - emulator: str | None = None - caller: tuple[str, str] | None = None - - -# The names configgen gives the command it builds. -COMMAND_NAMES = {"commandArray", "commandLine"} - GENERIC_SITES = ( GenericSites("dolphin/dolphinGenerator.py", "fixed_name"), GenericSites("yabasanshiro/yabasanshiroGenerator.py", "fixed_name"), @@ -367,481 +330,6 @@ GENERIC_SITES = ( ) -@dataclass -class _Site: - """One use of a BIOS path, and the record fields it contributes.""" - - path: str - passes_to: str - kind: str | None - lines: list[tuple[int, int]] - conditions: list[str] - cores: list[str] - expands: dict[str, list[str]] = field(default_factory=dict) - # A copy reads its file from `source` and hands it to `passes_to`. - source: str | None = None - - -class _Reader: - """The BIOS path uses of one generator module.""" - - def __init__(self, cg: Configgen, src: Source) -> None: - self.cg = cg - self.src = src - self.bios = cg.bios.rstrip("/") - self.parents: dict[int, ast.AST] = {} - self.copy_sources: dict[int, str] = {} - for parent in ast.walk(src.tree): - for child in ast.iter_child_nodes(parent): - self.parents[id(child)] = parent - self.constants = dict(cg.paths) - folder = src.path.rsplit("/", 1)[0] - for node in src.tree.body: - if ( - isinstance(node, ast.ImportFrom) - and node.level == 1 - and node.module - and node.module.endswith("Paths") - ): - paths = cg.source(f"{folder}/{node.module}.py") - self._define(paths.tree.body) - self._define(src.tree.body) - - def _define(self, body: list[ast.stmt]) -> None: - for node in body: - name = _assigned_name(node) - value = self.resolve(getattr(node, "value", None)) - if name is not None and value is not None: - self.constants[name] = value - - def under_bios(self, value: str | None) -> bool: - return value is not None and ( - value.rstrip("/") == self.bios or f"{self.bios}/" in value - ) - - def resolve(self, node: ast.AST | None) -> str | None: - """The path an expression spells, unknown parts of an f-string as .""" - if node is None: - return None - value = _path_value(node, self.constants) - if value is not None: - return value - if isinstance(node, ast.Constant) and isinstance(node.value, str): - text = node.value.strip('"') - return text if text.startswith("/") else None - if isinstance(node, ast.Call) and ast.unparse(node.func) == "str" and len(node.args) == 1: - return self.resolve(node.args[0]) - if isinstance(node, ast.JoinedStr): - parts = [] - for part in node.values: - if isinstance(part, ast.Constant): - parts.append(str(part.value)) - else: - # The other parts of an f-string are its {placeholders}. - expr = part.value if isinstance(part, ast.FormattedValue) else part - inner = self.resolve(expr) - parts.append(inner if inner is not None else f"<{ast.unparse(expr)}>") - return "".join(parts).strip('"') - if ( - isinstance(node, ast.BinOp) - and isinstance(node.op, ast.Div) - and isinstance(node.right, (ast.Constant, ast.Name)) - ): - left = self.resolve(node.left) - right = node.right.value if isinstance(node.right, ast.Constant) else None - if isinstance(node.right, ast.Name): - right = self._placeholder(node.right) - if left is not None and isinstance(right, str): - return f"{left.rstrip('/')}/{right}" - return None - - def _placeholder(self, name: ast.Name) -> str | None: - """{var} for a comprehension variable over a literal list.""" - comprehension = self._comprehension(name) - if comprehension is None: - return None - return "{" + name.id + "}" - - def _comprehension(self, name: ast.Name) -> tuple[str, list[str]] | None: - node: ast.AST | None = name - while node is not None: - node = self.parents.get(id(node)) - if isinstance(node, (ast.GeneratorExp, ast.ListComp)): - for generator in node.generators: - if isinstance(generator.target, ast.Name) and generator.target.id == name.id: - values = self._literal_list(generator.iter, node) - return (name.id, values) if values else None - return None - - def _literal_list(self, node: ast.AST | None, scope_of: ast.AST) -> list[str] | None: - if isinstance(node, ast.List): - return [str(e.value) for e in node.elts if isinstance(e, ast.Constant)] - if isinstance(node, ast.Name): - scope = self.function_of(scope_of) - bound = [ - n for n in ast.walk(scope or self.src.tree) - if _assigned_name(n) == node.id and isinstance(_bound(n), ast.List) - ] - if len(bound) == 1: - return self._literal_list(_bound(bound[0]), scope_of) - return None - - def function_of(self, node: ast.AST) -> ast.FunctionDef | None: - current: ast.AST | None = node - while current is not None: - current = self.parents.get(id(current)) - if isinstance(current, ast.FunctionDef): - return current - return None - - def statement_of(self, node: ast.AST) -> ast.stmt: - while not isinstance(node, ast.stmt): - node = self.parents[id(node)] - return node - - def maximal(self) -> Iterator[tuple[ast.AST, str]]: - """Each expression spelling a BIOS path that no larger one contains.""" - for node in ast.walk(self.src.tree): - if not isinstance(node, ast.expr): - continue - value = self.resolve(node) - if value is None and isinstance(node, ast.Constant) and isinstance(node.value, str): - # A line written to a config file: openmsx's settings.tcl. - written = re.search(rf"{re.escape(self.bios)}(?:/[^\s\"';]*)?", node.value) - parent = self.parents.get(id(node)) - if written and isinstance(parent, ast.Call) and ast.unparse(parent.func).endswith(".write"): - yield node, written.group(0) - continue - if value is None or not self.under_bios(value): - continue - parent = self.parents.get(id(node)) - if isinstance(parent, (ast.FormattedValue, ast.JoinedStr)): - continue - if isinstance(parent, ast.expr) and self.under_bios(self.resolve(parent)): - continue - if isinstance(parent, ast.Call) and ast.unparse(parent.func) == "str": - continue - yield node, value - - def conditions( - self, node: ast.AST, guards: bool = False - ) -> tuple[list[str], list[tuple[int, int]]]: - """Tests of the ifs a node sits in, outermost first, and their lines. - - A presence test of a BIOS path is a guard, kept for its lines only, - unless guards is set: a copy made only when its source or its target - is there carries the test as a condition. - """ - tests: list[str] = [] - spans: list[tuple[int, int]] = [] - child, parent = node, self.parents.get(id(node)) - while parent is not None and not isinstance(parent, ast.FunctionDef): - if isinstance(parent, ast.If) and child is not parent.test: - spans.append(self.src.span(parent.test)) - text = ast.unparse(parent.test) - if guards or not self._is_guard(parent.test): - in_else = any(child is stmt for stmt in parent.orelse) - tests.append(f"not ({text})" if in_else else text) - child, parent = parent, self.parents.get(id(parent)) - return list(reversed(tests)), spans - - def _is_guard(self, test: ast.expr) -> bool: - for n in ast.walk(test): - if not ( - isinstance(n, ast.Call) - and isinstance(n.func, ast.Attribute) - and n.func.attr == "exists" - ): - continue - receiver = n.func.value - if self.under_bios(self.resolve(receiver)): - return True - if isinstance(receiver, ast.Name) and self.local_value(receiver) is not None: - return True - return False - - def cores(self, node: ast.AST) -> list[str]: - child, parent = node, self.parents.get(id(node)) - while parent is not None: - if isinstance(parent, ast.If) and child is not parent.test and _cores_of(parent.test): - return _cores_of(parent.test) - child, parent = parent, self.parents.get(id(parent)) - return [] - - def uses(self, node: ast.AST, value: str) -> Iterator[tuple[ast.AST, str | None, str | None]]: - """(node read, passes_to, kind) for each consumer of a BIOS path expression. - - A path bound to a local name is followed to each read of that name. - A use with no consumer (a presence test, a mkdir) yields passes_to None. - """ - parent = self.parents.get(id(node)) - if isinstance(parent, ast.Assign) and len(parent.targets) == 1: - target = parent.targets[0] - if isinstance(target, ast.Name): - scope = self.function_of(parent) - if scope is None: - return - for read in ast.walk(scope): - if ( - isinstance(read, ast.Name) - and read.id == target.id - and isinstance(read.ctx, ast.Load) - and read.lineno > parent.lineno - ): - yield from self.uses(read, value) - return - if isinstance(target, ast.Subscript) and isinstance(target.slice, ast.Constant): - yield node, str(target.slice.value), None - return - yield node, *self.consumer(node, value) - - def _command_line(self, display: ast.List | ast.Tuple) -> bool: - """Whether a list display is (part of) the command configgen runs. - - It is assigned or added to commandArray (or commandLine for the - libretro MAME cmd file), or it starts with an absolute binary path. - """ - first = display.elts[0] if display.elts else None - if isinstance(first, ast.Constant) and str(first.value).startswith("/"): - return True - holder = self.parents.get(id(display)) - targets: list[ast.expr] = [] - if isinstance(holder, ast.Assign): - targets = holder.targets - elif isinstance(holder, ast.AugAssign): - targets = [holder.target] - elif ( - isinstance(holder, ast.Call) - and isinstance(holder.func, ast.Attribute) - and holder.func.attr in ("extend", "append") - ): - targets = [holder.func.value] - names = { - ast.unparse(t.value if isinstance(t, ast.Subscript) else t) for t in targets - } - return bool(names & COMMAND_NAMES) - - def local_value(self, name: ast.Name) -> str | None: - """The BIOS path a local name is bound to once in its function.""" - scope = self.function_of(name) - if scope is None: - return None - bound = [ - self.resolve(_bound(n)) - for n in ast.walk(scope) if _assigned_name(n) == name.id - ] - return bound[0] if len(bound) == 1 and self.under_bios(bound[0]) else None - - def consumer(self, node: ast.AST, value: str) -> tuple[str | None, str | None]: - parent = self.parents.get(id(node)) - if isinstance(parent, (ast.List, ast.Tuple)): - return self._listed_consumer(node, parent, value) - if isinstance(parent, ast.Call): - return self._call_consumer(node, parent, value) - if isinstance(parent, ast.Dict): - return self._dict_consumer(node, parent) - return None, None - - def _listed_consumer( - self, node: ast.AST, parent: ast.List | ast.Tuple, value: str - ) -> tuple[str | None, str | None]: - holder = self.parents.get(id(parent)) - if isinstance(holder, (ast.For, ast.comprehension)): - return None, None - if not self._command_line(parent): - return None, None - index = next(i for i, e in enumerate(parent.elts) if e is node) - if isinstance(node, ast.JoinedStr) and isinstance(node.values[0], ast.Constant): - flag = str(node.values[0].value) - if flag.startswith("-") and flag.endswith("=") and value.startswith(flag): - return f"command line {flag[:-1]}", None - previous = parent.elts[index - 1] if index else None - if isinstance(previous, ast.Constant) and str(previous.value).startswith("-"): - return f"command line {previous.value!s}", None - if index: - return f"command line argument {index}", None - return None, None - - def _call_consumer( - self, node: ast.AST, parent: ast.Call, value: str - ) -> tuple[str | None, str | None]: - func = parent.func - attr = func.attr if isinstance(func, ast.Attribute) else None - consts = [a.value for a in parent.args if isinstance(a, ast.Constant)] - if attr == "save" and len(parent.args) == 2 and parent.args[1] is node and consts: - return str(consts[0]), None - if attr == "set" and len(parent.args) == 3 and parent.args[2] is node and len(consts) >= 2: - return f"[{consts[0]!s}] {consts[1]!s}", None - receiver = func.value if isinstance(func, ast.Attribute) else None - if attr in ("copy", "copyfile", "copy2") and receiver is not None and ast.unparse(receiver) == "shutil": - source, target = parent.args[0], parent.args[1] - self.copy_sources[id(node)] = value if source is node else ( - self.resolve(source) or ast.unparse(source) - ) - return (value if target is node else self.resolve(target) or ast.unparse(target)), "copies" - if ( - attr == "append" - and isinstance(receiver, ast.Name) - and receiver.id in COMMAND_NAMES - and isinstance(node, ast.JoinedStr) - and isinstance(node.values[0], ast.Constant) - ): - flag = str(node.values[0].value) - if flag.startswith("-") and flag.endswith("=") and value.startswith(flag): - return f"command line {flag[:-1]}", None - if attr == "write" and isinstance(node, ast.Constant): - return f"written: {str(node.value).strip()}", None - return None, None - - def _dict_consumer(self, node: ast.AST, parent: ast.Dict) -> tuple[str | None, str | None]: - key = next( - (k for k, v in zip(parent.keys, parent.values) if v is node), None - ) - if not isinstance(key, ast.Constant): - return None, None - holder = self.parents.get(id(parent)) - is_env = ( - isinstance(holder, ast.keyword) and holder.arg == "env" - ) or (holder is not None and _assigned_name(holder) == "env") - return (f"environment {key.value!s}" if is_env else str(key.value)), None - - def sites(self) -> list[_Site]: - found: list[_Site] = [] - guards: list[tuple[ast.AST, str]] = [] - for node, value in self.maximal(): - if isinstance(self.statement_of(node), (ast.Import, ast.ImportFrom)): - continue - if self.function_of(node) is None and isinstance(self.parents.get(id(node)), ast.Assign): - continue - for read, passes_to, kind in self.uses(node, value): - parent = self.parents.get(id(read)) - if ( - passes_to is None - and isinstance(parent, ast.Attribute) - and parent.attr == "exists" - ): - guards.append((read, value)) - if passes_to is None: - continue - found.append(self._site(read, value, passes_to, kind, node)) - for read, value in guards: - if any(site.path == value for site in found): - site = next(s for s in found if s.path == value) - site.lines.append(self.src.span(self.statement_of(read))) - continue - found.append(self._guard_site(read, value)) - return sorted(found, key=lambda site: site.lines[0]) - - def _site( - self, read: ast.AST, value: str, passes_to: str, kind: str | None, defined: ast.AST - ) -> _Site: - tests, spans = self.conditions(read, guards=kind == "copies") - lines = [self.src.span(self.statement_of(read)), *spans] - if defined is not read: - # A path bound in one branch and read after the if: the branch - # that bound it is a condition of the read. - bound_tests, bound_spans = self.conditions(defined) - tests = list(dict.fromkeys([*bound_tests, *tests])) - lines += [self.src.span(self.statement_of(defined)), *bound_spans] - return _Site( - value, passes_to, kind, lines, tests, self.cores(read), self._expands(read), - self.copy_sources.get(id(read)), - ) - - def _guard_site(self, read: ast.AST, value: str) -> _Site: - """A presence test whose if body is the only consumer of the path.""" - test = self.statement_of(read) - if not isinstance(test, ast.If): - self.src.fail(f"line {test.lineno} tests a BIOS path outside an if") - first = test.body[0] - described = ast.unparse(first) - call = first.value if isinstance(first, ast.Expr) else None - if isinstance(call, ast.Call) and isinstance(call.func, ast.Attribute) and call.func.attr == "set": - literal = [a.value for a in call.args if isinstance(a, ast.Constant)] - if len(literal) == 3: - described = f"[{literal[0]!s}] {literal[1]!s} = {literal[2]!s}" - tests, spans = self.conditions(test) - return _Site( - value, f"presence sets {described}", None, - [(test.lineno, end_line(first)), *spans], - tests, self.cores(test), self._expands(read), - ) - - def _expands(self, node: ast.AST) -> dict[str, list[str]]: - found: dict[str, list[str]] = {} - for name in ast.walk(node): - if isinstance(name, ast.Name): - bound = self._comprehension(name) - if bound is not None: - found[bound[0]] = bound[1] - return found - - -def _caller_cores(cg: Configgen, caller: tuple[str, str]) -> list[str]: - path, function = caller - src = cg.source(f"{cg.generators}/{path}") - for node in ast.walk(src.tree): - if not isinstance(node, ast.If) or not _cores_of(node.test): - continue - if any( - isinstance(n, ast.Call) and ast.unparse(n.func).endswith(f".{function}") - for stmt in node.body for n in ast.walk(stmt) - ): - return _cores_of(node.test) - return src.fail(f"no core test calls {function}") - - -def bios_sites(cg: Configgen, spec: GenericSites) -> list[Launcher]: - """One record per BIOS path and consumer of a generator module.""" - src = cg.source(f"{cg.generators}/{spec.path}") - reader = _Reader(cg, src) - sites = reader.sites() - if not sites: - src.fail("hands over no /userdata/bios path") - module = spec.path.removesuffix(".py").replace("/", ".") - caller_cores = _caller_cores(cg, spec.caller) if spec.caller else [] - grouped: dict[tuple[str, str, str, tuple[str, ...]], list[_Site]] = {} - for site in sites: - flag = site.passes_to.removeprefix("command line ") - if site.path.startswith(f"{flag}="): - site.path = site.path[len(flag) + 1:] - emulator = ( - spec.emulator - or ", ".join(site.cores or caller_cores) - or (cg.emulator(module) if spec.build == "standalone" else "") - ) - if not emulator: - src.fail(f"no core runs the {site.passes_to} use at line {site.lines[0][0]}") - key = (emulator, site.path, site.passes_to, tuple(site.conditions)) - grouped.setdefault(key, []).append(site) - prefix = cg.bios.rstrip("/") + "/" - launchers = [] - for (emulator, path, passes_to, _conditions), group in grouped.items(): - kind = group[0].kind or spec.kind - conditions = list(dict.fromkeys(c for site in group for c in site.conditions)) - expands = {k: v for site in group for k, v in site.expands.items()} - names: list[str] = [] - search_dir = path - source = group[0].source - if kind == "copies" and source is not None and not source.startswith(prefix): - # Copied into BIOS: the file is read from the folder it comes from. - search_dir, _, name = source.rpartition("/") - names = [name] - elif kind in ("fixed_name", "copies"): - if not path.startswith(prefix): - src.fail(f"{path} names no file under {cg.bios}") - names, search_dir = [path[len(prefix):]], cg.bios - launchers.append(Launcher( - emulator=emulator, build=spec.build, kind=kind, names=names, - expands=expands or None, - case_insensitive=False if names else None, - search_dir=search_dir, passes_to=passes_to, fails_when_missing=False, - depends_on_option=" and ".join(conditions) or None, - source_ref=src.ref([span for site in group for span in site.lines]), - )) - return launchers - - # Generators that write a [Folders] path relative to the config folder they # are given. PCSX2 and AetherSX2 resolve those paths against their data root, # the folder holding inis/, which configureINI receives as config_directory. diff --git a/scripts/scraper/knulli_scraper.py b/scripts/scraper/knulli_scraper.py index afdd18e4b..1c4695d7c 100644 --- a/scripts/scraper/knulli_scraper.py +++ b/scripts/scraper/knulli_scraper.py @@ -49,7 +49,7 @@ from .batocera_scraper import ( ) from .es_emulators import attach_system_cores from .targets.knulli_targets_scraper import Scraper as BoardTargets -from .batocera_launchers import configs_root +from .batocera_configgen import configs_root from .knulli_launchers import BATOCERA_SUBMODULE, extract_launchers from .knulli_launchers import configgen as knulli_configgen diff --git a/scripts/scraper/rocknix_packages.py b/scripts/scraper/rocknix_packages.py new file mode 100644 index 000000000..1e3dd1e5c --- /dev/null +++ b/scripts/scraper/rocknix_packages.py @@ -0,0 +1,37 @@ +"""The emulators ROCKNIX packages, by the names the profiles use, read by its +BIOS scraper and its device targets.""" + +from __future__ import annotations + +import re + + +def standalone_emulators(package_names: list[str]) -> list[str]: + """The standalone emulators ROCKNIX packages, by the names profiles use. + + A package is named after its emulator with an ``-sa`` suffix + (``duckstation-sa``), once without its hyphen (``hatarisa``), and both + spellings are kept so a profile listing either is found. + """ + names: set[str] = set() + for package in package_names: + names.add(package) + stripped = _emulator_of(package) + if stripped != package: + names.add(stripped) + return sorted(names) + + +def _emulator_of(package: str) -> str: + return re.sub(r"-?sa$", "", package) or package + + +def dual_mode_emulators(standalone: list[str], package_mk: str) -> list[str]: + """The standalone emulators RetroArch also runs as a core. + + package.mk adds each launch option with `add_emu_core + `. Only an emulator also added as `retroarch ` is + launched both ways: ARMSX2 is added as armsx2-sa alone. + """ + retroarch = set(re.findall(r"^\s*add_emu_core\s+\S+\s+retroarch\s+(\S+)", package_mk, re.M)) + return sorted(name for name in standalone if _emulator_of(name) in retroarch) diff --git a/scripts/scraper/rocknix_scraper.py b/scripts/scraper/rocknix_scraper.py index ce9f7d09a..2c7387a7b 100644 --- a/scripts/scraper/rocknix_scraper.py +++ b/scripts/scraper/rocknix_scraper.py @@ -26,6 +26,8 @@ from .base_scraper import ( ) from .rocknix_launchers import extract_launchers from scraper.shell_launchers import RepoTree +from .rocknix_packages import dual_mode_emulators, standalone_emulators +from .targets.rocknix_targets_scraper import Scraper as DeviceTargets PLATFORM_NAME = "rocknix" @@ -56,36 +58,6 @@ def launcher_revision(url: str) -> str: return found.group(1) -def standalone_emulators(package_names: list[str]) -> list[str]: - """The standalone emulators ROCKNIX packages, by the names profiles use. - - A package is named after its emulator with an ``-sa`` suffix - (``duckstation-sa``), once without its hyphen (``hatarisa``), and both - spellings are kept so a profile listing either is found. - """ - names: set[str] = set() - for package in package_names: - names.add(package) - stripped = _emulator_of(package) - if stripped != package: - names.add(stripped) - return sorted(names) - -def _emulator_of(package: str) -> str: - return re.sub(r"-?sa$", "", package) or package - - -def dual_mode_emulators(standalone: list[str], package_mk: str) -> list[str]: - """The standalone emulators RetroArch also runs as a core. - - package.mk adds each launch option with `add_emu_core - `. Only an emulator also added as `retroarch ` is - launched both ways: ARMSX2 is added as armsx2-sa alone. - """ - retroarch = set(re.findall(r"^\s*add_emu_core\s+\S+\s+retroarch\s+(\S+)", package_mk, re.M)) - return sorted(name for name in standalone if _emulator_of(name) in retroarch) - - # ROCKNIX system key -> retrobios system ID SYSTEM_SLUG_MAP = { "xbox": "microsoft-xbox", @@ -188,7 +160,6 @@ class Scraper(BaseScraper): the targets scraper, where every libretro profile counted before. A standalone package no device carries is not run either. """ - from .targets.rocknix_targets_scraper import Scraper as DeviceTargets builds = DeviceTargets().device_builds(self.tag or launcher_revision(self.url)) 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}))) diff --git a/scripts/scraper/targets/emuelec_targets_scraper.py b/scripts/scraper/targets/emuelec_targets_scraper.py index 5153aadcd..1bb975520 100644 --- a/scripts/scraper/targets/emuelec_targets_scraper.py +++ b/scripts/scraper/targets/emuelec_targets_scraper.py @@ -37,8 +37,13 @@ import yaml from . import BaseTargetScraper from ..base_scraper import fetch_bytes, github_headers from ..batocera_scraper import _not_cores -from ..emuelec_scraper import ( - BUILDS_OF, ES_SYSTEMS_TEMPLATE, PORTS_TEMPLATE, RUNNERS, port_engines, with_ports, +from ..emuelec_systems import ( + BUILDS_OF, + ES_SYSTEMS_TEMPLATE, + PORTS_TEMPLATE, + RUNNERS, + port_engines, + with_ports, ) from ..es_emulators import SystemEmulators, es_cores diff --git a/scripts/scraper/targets/rocknix_targets_scraper.py b/scripts/scraper/targets/rocknix_targets_scraper.py index b106c66aa..f7e808576 100644 --- a/scripts/scraper/targets/rocknix_targets_scraper.py +++ b/scripts/scraper/targets/rocknix_targets_scraper.py @@ -24,7 +24,7 @@ import yaml from . import BaseTargetScraper from ..base_scraper import fetch_bytes, github_headers -from ..rocknix_scraper import standalone_emulators +from ..rocknix_packages import standalone_emulators PLATFORM_NAME = "rocknix" diff --git a/tests/test_elec_scrapers.py b/tests/test_elec_scrapers.py index ca7f5aff5..74272f96a 100644 --- a/tests/test_elec_scrapers.py +++ b/tests/test_elec_scrapers.py @@ -14,7 +14,7 @@ import tests import unittest from pathlib import Path -from scraper import amberelec_scraper, emuelec_scraper, knulli_scraper +from scraper import amberelec_scraper, emuelec_scraper, emuelec_systems, knulli_scraper from scraper.es_emulators import ( attach_system_cores, es_cores, @@ -152,7 +152,7 @@ class TheCoresComeFromTheOsList(unittest.TestCase): def test_emuelec_runners_and_standalone_names(self): cores, standalone, dual = es_cores( - json_systems(EMUELEC_ES), emuelec_scraper.RUNNERS, emuelec_scraper.BUILDS_OF + json_systems(EMUELEC_ES), emuelec_systems.RUNNERS, emuelec_systems.BUILDS_OF ) self.assertEqual(standalone, ["STELLASA", "yabasanshiro"]) self.assertNotIn("yabasanshiroSA", cores) @@ -160,7 +160,7 @@ class TheCoresComeFromTheOsList(unittest.TestCase): def test_a_name_that_emulates_nothing_is_dropped(self): cores, standalone, _ = es_cores( - json_systems(EMUELEC_ES), emuelec_scraper.RUNNERS, not_cores={"STELLASA"} + json_systems(EMUELEC_ES), emuelec_systems.RUNNERS, not_cores={"STELLASA"} ) self.assertNotIn("STELLASA", cores + standalone) @@ -211,27 +211,27 @@ class EmuelecPortsRunTheirEngine(unittest.TestCase): port's script: what runs is the core or program the script names.""" def test_each_port_names_its_engine(self): - self.assertEqual(emuelec_scraper.port_engines(PORTS), [ + self.assertEqual(emuelec_systems.port_engines(PORTS), [ ("2048", "2048", None, True), ("Diablo", "devilutionx", "Diablo", False), ("Flashback", "reminiscence", "REminiscence", True), ]) def test_engines_replace_the_dispatch(self): - systems = emuelec_scraper.with_ports( - {"ports": [("ports", ["ports"])]}, emuelec_scraper.port_engines(PORTS) + systems = emuelec_systems.with_ports( + {"ports": [("ports", ["ports"])]}, emuelec_systems.port_engines(PORTS) ) - cores, standalone, _ = es_cores(systems, emuelec_scraper.RUNNERS) + cores, standalone, _ = es_cores(systems, emuelec_systems.RUNNERS) self.assertNotIn("ports", cores) self.assertEqual(standalone, ["devilutionx"]) self.assertTrue({"2048", "reminiscence"} <= set(cores)) - by_system = system_cores(systems, emuelec_scraper.RUNNERS) + by_system = system_cores(systems, emuelec_systems.RUNNERS) self.assertEqual(by_system["Diablo"], ["devilutionx"]) self.assertEqual(by_system["REminiscence"], ["reminiscence"]) def test_a_port_without_an_engine_is_refused(self): with self.assertRaises(ValueError): - emuelec_scraper.port_engines("Broken:\n commands:\n - true\n") + emuelec_systems.port_engines("Broken:\n commands:\n - true\n") class CoreFilesGoUnderTheStatedFolder(unittest.TestCase): diff --git a/tests/test_launcher_paths.py b/tests/test_launcher_paths.py index b83132fd3..826de62f2 100644 --- a/tests/test_launcher_paths.py +++ b/tests/test_launcher_paths.py @@ -18,15 +18,8 @@ from pathlib import Path from resolve.launchers import handed_directories, standalone_bindings from scraper import retrobat_launchers as rl -from scraper.batocera_launchers import ( - GENERATORS, - IMPORTER, - PATHS_MODULE, - Configgen, - LauncherShapeError, - patched_paths, - working_directories, -) +from scraper.batocera_configgen import GENERATORS, IMPORTER, PATHS_MODULE, Configgen +from scraper.batocera_launchers import LauncherShapeError, patched_paths, working_directories REPO_ROOT = Path(__file__).resolve().parent.parent diff --git a/tests/test_launchers.py b/tests/test_launchers.py index 4350948c5..3a4c65b4a 100644 --- a/tests/test_launchers.py +++ b/tests/test_launchers.py @@ -17,12 +17,8 @@ from pathlib import Path import yaml +from scraper.batocera_configgen import CONFIGGEN, GENERATORS, IMPORTER, PATHS_MODULE, Configgen from scraper.batocera_launchers import ( - CONFIGGEN, - GENERATORS, - IMPORTER, - PATHS_MODULE, - Configgen, Launcher, LauncherShapeError, config_directories, diff --git a/tests/test_launchers_knulli.py b/tests/test_launchers_knulli.py index 83f3b7ca4..c10d49bc0 100644 --- a/tests/test_launchers_knulli.py +++ b/tests/test_launchers_knulli.py @@ -17,6 +17,7 @@ from pathlib import Path import yaml from scraper import knulli_launchers as kl +from scraper.configgen_sites import bios_sites, GenericSites from scraper.batocera_launchers import hatari, melonds from scraper.configgen_launchers import LauncherShapeError @@ -391,8 +392,8 @@ def configgen(**overrides: str) -> kl.Configgen: def sites(path: str, kind: str, **fields: object) -> list[dict]: - spec = kl.GenericSites(path, kind, **fields) - return [launcher.entry() for launcher in kl.bios_sites(configgen(), spec)] + spec = GenericSites(path, kind, **fields) + return [launcher.entry() for launcher in bios_sites(configgen(), spec)] class SharedExtractors(unittest.TestCase): @@ -551,9 +552,9 @@ class BiosSites(unittest.TestCase): def test_a_generator_without_a_bios_path_raises(self): files = tree(**{f"{G}/openmsx/openmsxGenerator.py": "def generate():\n return 1\n"}) - spec = kl.GenericSites("openmsx/openmsxGenerator.py", "passes_path") + spec = GenericSites("openmsx/openmsxGenerator.py", "passes_path") with self.assertRaises(LauncherShapeError): - kl.bios_sites(kl.configgen(files.__getitem__), spec) + bios_sites(kl.configgen(files.__getitem__), spec) class CopiesAndFolders(unittest.TestCase): diff --git a/tests/test_scraper_contract.py b/tests/test_scraper_contract.py index f9e724357..480267a00 100644 --- a/tests/test_scraper_contract.py +++ b/tests/test_scraper_contract.py @@ -445,7 +445,7 @@ class RocknixRunsItsStandaloneEmulators(unittest.TestCase): the next branch under the release's version.""" def test_package_names_reach_the_profiles(self): - from scraper.rocknix_scraper import standalone_emulators + from scraper.rocknix_packages import standalone_emulators self.assertEqual( standalone_emulators(["duckstation-sa", "hatarisa", "openbor"]), @@ -456,7 +456,7 @@ class RocknixRunsItsStandaloneEmulators(unittest.TestCase): """Every standalone package was declared launched both ways, so ARMSX2's libretro layout reached ROCKNIX, whose package.mk adds it as armsx2-sa only (add_emu_core ps2 armsx2 armsx2-sa true).""" - from scraper.rocknix_scraper import dual_mode_emulators + from scraper.rocknix_packages import dual_mode_emulators package_mk = ( " add_emu_core psx retroarch duckstation false\n" diff --git a/tests/test_standalone_links.py b/tests/test_standalone_links.py index d49cade55..cc91c65ca 100644 --- a/tests/test_standalone_links.py +++ b/tests/test_standalone_links.py @@ -515,9 +515,8 @@ class Scrapers(unittest.TestCase): rl.patched_directories(RepoTree.from_files({path: patch.replace("return", "x =")})) def test_batocera_environment_directory(self) -> None: - from scraper.batocera_launchers import ( - GENERATORS, IMPORTER, PATHS_MODULE, Configgen, environment_directories, - ) + from scraper.batocera_configgen import GENERATORS, IMPORTER, PATHS_MODULE, Configgen + from scraper.batocera_launchers import environment_directories from scraper.configgen_launchers import LauncherShapeError paths = "from pathlib import Path\nBIOS = Path('/userdata/bios')\nCONFIGS = Path('/userdata/system/configs')\n" diff --git a/tests/test_target_scrapers.py b/tests/test_target_scrapers.py index 93b7a9486..750bd8f5e 100644 --- a/tests/test_target_scrapers.py +++ b/tests/test_target_scrapers.py @@ -571,7 +571,7 @@ class RocknixPerDevice(unittest.TestCase): """vice-standalone answers to vice-sa only, as scummvm-standalone to scummvm-sa: stripped to vice, every targeted pack left them out while the untargeted one, read from the platform scraper, kept them.""" - from scraper.rocknix_scraper import standalone_emulators + from scraper.rocknix_packages import standalone_emulators from scraper.targets.rocknix_targets_scraper import parse_device_cores _, standalone = parse_device_cores(self.PACKAGE_MK, "SM8550", "aarch64", False)