mirror of
https://github.com/Abdess/retroarch_system.git
synced 2026-12-03 14:58:51 -06:00
refactor: group scraper modules by subject
scraper/ held the platform scrapers next to three other subjects. The launcher readers move to scraper/launchers/ (their _launchers suffix dropped), the MAME and FBNeo hash scrapers and romset importers to scraper/arcade/, the DAT readers and dump catalog importers to scraper/dats/. The buildbot check is a freshness check and moves to freshness/buildbot.py. Every -m command, workflow job, schema description and page follows. The scraper discovery in scraper/__init__.py had no caller: the registry's scraper: field names the module, and the pages now say so.
This commit is contained in:
1 parent
4e01cff854
commit
e1bad01b82
130 files changed
+445
-414
No files matched your search
@@ -0,0 +1,9 @@
|
||||
"""The launcher layer of each platform: what its launch code looks for, under
|
||||
which name and in which folder, and what it hands to the core or emulator,
|
||||
read from that code at the revision the platform file pins.
|
||||
|
||||
One module per platform reads its launchers (batocera.py, retrobat.py...).
|
||||
configgen.py holds the record every reader returns and the errors a reader
|
||||
raises when the code no longer has the shape it reads. shell.py and
|
||||
csharp_source.py read the shell and C# sources several platforms share.
|
||||
"""
|
||||
@@ -0,0 +1,439 @@
|
||||
"""AmberELEC's launcher layer, read from runemu.py and its emulator scripts.
|
||||
|
||||
EmulationStation hands every launch to runemu.py. A libretro core runs in
|
||||
RetroArch or retrorun with the system directory their configs name, MAME
|
||||
machines get a .cmd file with a `-rp` search path, and every other emulator
|
||||
runs the script its standalone_emulators table names (/usr/bin/<name>.sh,
|
||||
installed from the package). Those scripts, and the configs their packages
|
||||
install, say which file under /storage/roms/bios is opened: yabasanshiro.sh
|
||||
tests saturn_bios.bin and passes it with -b, Hatari's default config names
|
||||
tos.img.
|
||||
|
||||
runemu.py is read with ast, the scripts with shell.py's readers. An
|
||||
extractor whose construct is gone raises instead of returning nothing.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import ast
|
||||
import posixpath
|
||||
import re
|
||||
from collections.abc import Callable
|
||||
from typing import Any
|
||||
|
||||
from .configgen import Launcher, Source
|
||||
from scraper.launchers.shell import (
|
||||
LauncherPatternMissing,
|
||||
Script,
|
||||
config_placement,
|
||||
describe_keys,
|
||||
apply_evidence,
|
||||
first_boot_placement,
|
||||
settings,
|
||||
source_ref,
|
||||
)
|
||||
|
||||
BIOS = "/storage/roms/bios"
|
||||
RUNEMU = "packages/amberelec/sources/scripts/runemu.py"
|
||||
RETROARCH_CFG = "packages/games/tools/retroarch/sources/retroarch.cfg"
|
||||
RETRORUN = "packages/games/tools/retrorun/retrorun.sh"
|
||||
HATARI_CONFIG = "packages/games/emulators/hatarisa/config/conf/Atari-ST-default.cfg"
|
||||
# The first-boot copy of every package's /usr/config into /storage/.config.
|
||||
USERCONFIG = "packages/sysutils/systemd/scripts/userconfig-setup"
|
||||
AMIBERRY_PACKAGE = "packages/games/emulators/amiberry/package.mk"
|
||||
AMIBERRY_CONFIGS = "packages/games/emulators/amiberry/config/conf"
|
||||
FREEJ2ME = (
|
||||
("freej2me", "packages/games/libretro/freej2me/freej2me.sh"),
|
||||
("freej2me-plus", "packages/games/libretro/freej2me-plus/freej2me-plus.sh"),
|
||||
)
|
||||
EASYRPG = "packages/games/libretro/easyrpg/easyrpg.sh"
|
||||
|
||||
# The script each standalone_emulators entry runs, as the package installs it
|
||||
# to /usr/bin. scripts() checks each against runemu's table.
|
||||
SCRIPTS = {
|
||||
"AMIBERRY": "packages/games/emulators/amiberry/scripts/amiberry.sh",
|
||||
"HATARISA": "packages/games/emulators/hatarisa/scripts/hatari.sh",
|
||||
"SCUMMVMSA": "packages/games/emulators/scummvmsa/scummvm.sh",
|
||||
"pico8": "packages/amberelec/sources/pico-8.sh",
|
||||
"piemu": "packages/games/emulators/piemu/bin/piemu.sh",
|
||||
"yabasanshiroSA": "packages/games/emulators/yabasanshiroSA/yabasanshiro.sh",
|
||||
}
|
||||
|
||||
Read = Callable[[str], str]
|
||||
|
||||
|
||||
class Runemu:
|
||||
"""runemu.py, parsed: the standalone table and the RetroArch command."""
|
||||
|
||||
def __init__(self, read: Read) -> None:
|
||||
self.src = Source(RUNEMU, read(RUNEMU))
|
||||
node = self.src.assignment("standalone_emulators")
|
||||
if not isinstance(node.value, ast.Dict):
|
||||
self.src.fail("standalone_emulators is not a dict display")
|
||||
self.table: dict[str, tuple[str, int]] = {}
|
||||
for key, value in zip(node.value.keys, node.value.values):
|
||||
if not (
|
||||
isinstance(key, ast.Constant)
|
||||
and isinstance(value, ast.Call)
|
||||
and len(value.args) >= 2
|
||||
and isinstance(value.args[1], ast.List)
|
||||
):
|
||||
self.src.fail(f"entry at line {getattr(key, 'lineno', '?')} is not StandaloneEmulator(name, [args])")
|
||||
args = [a.value for a in value.args[1].elts if isinstance(a, ast.Constant)]
|
||||
script = next((a for a in args if str(a).endswith(".sh")), None)
|
||||
if script is None:
|
||||
self.src.fail(f"{ast.unparse(key)} runs no .sh script")
|
||||
self.table[str(key.value)] = (str(script), value.lineno)
|
||||
|
||||
def script(self, emulator: str) -> tuple[str, int]:
|
||||
"""The repository script runemu runs for emulator, and the table line."""
|
||||
if emulator not in self.table:
|
||||
self.src.fail(f"standalone_emulators has no {emulator}")
|
||||
installed, line = self.table[emulator]
|
||||
path = SCRIPTS[emulator]
|
||||
if posixpath.basename(installed) != posixpath.basename(path):
|
||||
self.src.fail(f"{emulator} runs {installed}, not {posixpath.basename(path)}")
|
||||
return path, line
|
||||
|
||||
|
||||
def _evidence(
|
||||
read: Read, record: Launcher, target: str, keys: list[str],
|
||||
start: Script | None = None, source_name: str = "",
|
||||
) -> Launcher:
|
||||
"""A config record with the steps that put its file at ``target``: the
|
||||
first-boot copy of /usr/config, then the start script's own copy."""
|
||||
placements = [first_boot_placement(Script(USERCONFIG, read(USERCONFIG)), target)]
|
||||
if start is not None:
|
||||
placements.append(
|
||||
config_placement(start, target, keys, source_name=source_name, required=False)
|
||||
)
|
||||
return apply_evidence(record, placements)
|
||||
|
||||
|
||||
def retroarch(read: Read) -> list[Launcher]:
|
||||
"""system_directory of the retroarch.cfg the retroarch package installs."""
|
||||
found = [s for s in settings(read(RETROARCH_CFG)) if s.key == "system_directory"]
|
||||
if len(found) != 1:
|
||||
raise LauncherPatternMissing(RETROARCH_CFG, "one system_directory")
|
||||
return [_evidence(read, Launcher(
|
||||
emulator="retroarch", build="libretro", kind="passes_path", names=[],
|
||||
search_dir=found[0].value, passes_to="retroarch.cfg system_directory",
|
||||
fails_when_missing=False, source_ref=source_ref([(RETROARCH_CFG, [found[0].line])]),
|
||||
), "/storage/.config/retroarch/retroarch.cfg", ["system_directory"])]
|
||||
|
||||
|
||||
def retrorun(read: Read) -> list[Launcher]:
|
||||
"""The -d directory retrorun.sh passes to retrorun."""
|
||||
script = Script(RETRORUN, read(RETRORUN))
|
||||
line, found = script.find(r"^\s*/usr/bin/retrorun\s.*\s-d\s+(\S+)", "retrorun -d")
|
||||
return [Launcher(
|
||||
emulator="retrorun", build="libretro", kind="passes_path", names=[],
|
||||
search_dir=found.group(1).strip('"'), passes_to="command line -d",
|
||||
fails_when_missing=False, source_ref=source_ref([(RETRORUN, [line])]),
|
||||
)]
|
||||
|
||||
|
||||
def mame(runemu: Runemu) -> list[Launcher]:
|
||||
"""The `-rp` search path of the .cmd file runemu writes for a MAME machine."""
|
||||
src = runemu.src
|
||||
commands = [
|
||||
node for node in ast.walk(src.function("get_retroarch_command"))
|
||||
if isinstance(node, ast.JoinedStr)
|
||||
and any(isinstance(p, ast.Constant) and " -rp " in str(p.value) for p in node.values)
|
||||
]
|
||||
if not commands:
|
||||
src.fail("get_retroarch_command writes no -rp search path")
|
||||
paths = []
|
||||
for node in commands:
|
||||
text = "".join(str(p.value) for p in node.values if isinstance(p, ast.Constant))
|
||||
paths.append(text.split(" -rp ", 1)[1].split()[0])
|
||||
if len(set(paths)) != 1:
|
||||
src.fail(f"the MAME commands differ in their search path: {sorted(set(paths))}")
|
||||
guard = next(
|
||||
node for node in ast.walk(src.function("get_retroarch_command"))
|
||||
if isinstance(node, ast.If) and ast.unparse(node.test) == "self.emulator == 'mame'"
|
||||
)
|
||||
return [Launcher(
|
||||
emulator="mame", build="libretro", kind="passes_path", names=[],
|
||||
search_dir=paths[0], passes_to=".cmd -rp", fails_when_missing=False,
|
||||
depends_on_option=ast.unparse(guard.test),
|
||||
source_ref=src.ref([
|
||||
src.span(guard.test), *((n.lineno, n.end_lineno or n.lineno) for n in commands),
|
||||
]),
|
||||
)]
|
||||
|
||||
|
||||
def _bios_files(path: str, text: str) -> tuple[list[tuple[tuple[str, str], str]], set[int]]:
|
||||
"""((section, key), name under BIOS) for each config key whose value is a BIOS file."""
|
||||
prefix = BIOS + "/"
|
||||
found = [s for s in settings(text) if s.value.startswith(prefix)]
|
||||
if not found:
|
||||
raise LauncherPatternMissing(path, f"key naming a file under {BIOS}")
|
||||
return [((s.section, s.key), s.value[len(prefix):]) for s in found], {s.line for s in found}
|
||||
|
||||
|
||||
def hatari(read: Read, runemu: Runemu) -> list[Launcher]:
|
||||
"""szTosImageFileName of the default config hatari.sh copies and passes."""
|
||||
path, table_line = runemu.script("HATARISA")
|
||||
script = Script(path, read(path))
|
||||
name = posixpath.basename(HATARI_CONFIG)
|
||||
copied, copy = script.find(
|
||||
rf"^\s*cp\s+\S*/{re.escape(name)}\s+\"?(\$\{{?\w+\}}?)", f"cp of {name}"
|
||||
)
|
||||
passed, _ = script.find(r"\shatari\s+--configfile\s", "hatari --configfile")
|
||||
files, lines = _bios_files(HATARI_CONFIG, read(HATARI_CONFIG))
|
||||
return [_evidence(read, Launcher(
|
||||
emulator="HATARISA", build="standalone", kind="fixed_name",
|
||||
names=[n for _k, n in files], case_insensitive=False, search_dir=BIOS,
|
||||
passes_to=describe_keys(name, tuple(k for k, _n in files)),
|
||||
fails_when_missing=False,
|
||||
source_ref=source_ref([
|
||||
(RUNEMU, [table_line]), (path, [copied, passed]), (HATARI_CONFIG, lines),
|
||||
]),
|
||||
), script.expand(copy.group(1), copied, set()),
|
||||
[f"[{s}] {k}" if s else k for (s, k), _n in files], script, name)]
|
||||
|
||||
|
||||
def yabasanshiro(read: Read, runemu: Runemu) -> list[Launcher]:
|
||||
"""`if [ -e <bios> ]; then BIOS="-b <bios>"`, skipped when HLE is chosen."""
|
||||
path, table_line = runemu.script("yabasanshiroSA")
|
||||
script = Script(path, read(path))
|
||||
tested, test = script.find(rf'if \[ -e "({re.escape(BIOS)}/[^"]+)" \]', "BIOS presence test")
|
||||
flag_line, flag = script.find(
|
||||
rf'BIOS="(-\w+) {re.escape(test.group(1))}"', "BIOS flag", tested
|
||||
)
|
||||
hle_line, hle = script.find(r'get_setting "(\w*hle\w*)"', "HLE setting")
|
||||
guard_line, _ = script.find(r'if \[ "\$\{HLEBIOS\}" != 1 \]', "HLE test")
|
||||
used_line, _ = script.find(r"\$\{BIOS\}", "BIOS on the command line", flag_line + 1)
|
||||
return [Launcher(
|
||||
emulator="yabasanshiroSA", build="standalone", kind="fixed_name",
|
||||
names=[test.group(1)[len(BIOS) + 1:]], case_insensitive=False, search_dir=BIOS,
|
||||
passes_to=f"command line {flag.group(1)}", fails_when_missing=False,
|
||||
depends_on_option=hle.group(1),
|
||||
source_ref=source_ref([
|
||||
(RUNEMU, [table_line]),
|
||||
(path, [hle_line, guard_line, tested, flag_line, used_line]),
|
||||
]),
|
||||
)]
|
||||
|
||||
|
||||
def pico8(read: Read, runemu: Runemu) -> list[Launcher]:
|
||||
"""`if [ ! -f A ] || [ ! -f B ]; then text_viewer ...; else A ...`."""
|
||||
path, table_line = runemu.script("pico8")
|
||||
script = Script(path, read(path))
|
||||
line, test = script.find(r'if \[ ! -f "([^"]+)" \] \|\| \[ ! -f "([^"]+)" \]', "binary test")
|
||||
message_line, message = script.find(r'text_viewer .*-t "([^"]+)"', "missing message", line)
|
||||
binary = test.group(1)
|
||||
run_line, _ = script.find(rf"^\s*{re.escape(binary)}\s", f"{binary} run", message_line)
|
||||
folders = {posixpath.dirname(test.group(1)), posixpath.dirname(test.group(2))}
|
||||
if len(folders) != 1:
|
||||
raise script.missing("both binaries in one folder")
|
||||
return [Launcher(
|
||||
emulator="pico8", build="standalone", kind="fixed_name",
|
||||
names=[posixpath.basename(test.group(1)), posixpath.basename(test.group(2))],
|
||||
case_insensitive=False, search_dir=folders.pop(), passes_to="exec",
|
||||
fails_when_missing=message.group(1),
|
||||
source_ref=source_ref([(RUNEMU, [table_line]), (path, [line, message_line, run_line])]),
|
||||
)]
|
||||
|
||||
|
||||
def piemu(read: Read, runemu: Runemu) -> list[Launcher]:
|
||||
"""The BIOS file piemu.sh hands to mkpfi to build the flash image."""
|
||||
path, table_line = runemu.script("piemu")
|
||||
script = Script(path, read(path))
|
||||
names: list[str] = []
|
||||
lines: set[int] = set()
|
||||
for number, line in script.code():
|
||||
found = re.search(r'/usr/bin/mkpfi\s+"([^"]+)"', line)
|
||||
if found is None:
|
||||
continue
|
||||
used: set[int] = {number}
|
||||
value = script.expand(found.group(1), number, used)
|
||||
if value.startswith(BIOS + "/") and value[len(BIOS) + 1:] not in names:
|
||||
names.append(value[len(BIOS) + 1:])
|
||||
lines |= used
|
||||
if not names:
|
||||
raise script.missing(f"mkpfi of a file under {BIOS}")
|
||||
return [Launcher(
|
||||
emulator="piemu", build="standalone", kind="fixed_name", names=names,
|
||||
case_insensitive=False, search_dir=BIOS, passes_to="mkpfi argument",
|
||||
fails_when_missing=False,
|
||||
source_ref=source_ref([(RUNEMU, [table_line]), (path, lines)]),
|
||||
)]
|
||||
|
||||
|
||||
def amiberry(read: Read, runemu: Runemu) -> list[Launcher]:
|
||||
"""The kickstarts link of the package, and the ROM each default config names."""
|
||||
package = Script(AMIBERRY_PACKAGE, read(AMIBERRY_PACKAGE))
|
||||
links = [link for link in package.links(BIOS) if link.bios_is_target]
|
||||
if len(links) != 1 or links[0].bios_side.rstrip("/") != BIOS:
|
||||
raise package.missing(f"ln -s {BIOS} to the kickstarts folder")
|
||||
link = links[0]
|
||||
installed = re.sub(r"^\$\{INSTALL\}", "", link.link)
|
||||
path, table_line = runemu.script("AMIBERRY")
|
||||
script = Script(path, read(path))
|
||||
# A WHDLoad archive is booted by --autoload, which builds its own setup
|
||||
# over the config: the kickstart records hold for the other content.
|
||||
autoload = [n for n, text in script.code() if re.search(r"amiberry .*--autoload", text)]
|
||||
if not autoload:
|
||||
raise script.missing("WHDLoad boot with --autoload")
|
||||
content = (
|
||||
"content not booted with --autoload, a WHDLoad .lha or .zip "
|
||||
f"({posixpath.basename(path)}:{', '.join(map(str, autoload))})"
|
||||
)
|
||||
launchers = [Launcher(
|
||||
emulator="AMIBERRY", build="standalone", kind="links", names=[],
|
||||
case_insensitive=False, search_dir=BIOS,
|
||||
passes_to=f"{installed} is a symlink to it", fails_when_missing=False,
|
||||
source_ref=source_ref([(AMIBERRY_PACKAGE, link.lines)]),
|
||||
)]
|
||||
for number, line in script.code():
|
||||
copied = re.search(r"cp\s+\$AMIBERRY_CONFIG_DIR/(\S+\.uae)\s", line)
|
||||
if copied is None:
|
||||
continue
|
||||
config = f"{AMIBERRY_CONFIGS}/{copied.group(1)}"
|
||||
found = [
|
||||
s for s in settings(read(config))
|
||||
if s.key == "kickstart_rom_file" and s.value.startswith("$(FILE_PATH)/")
|
||||
]
|
||||
rom_path = [s for s in settings(read(config)) if s.key == "amiberry.rom_path"]
|
||||
if len(found) != 1 or len(rom_path) != 1:
|
||||
raise LauncherPatternMissing(config, "kickstart_rom_file under $(FILE_PATH)")
|
||||
if rom_path[0].value.rstrip("/").rsplit("/", 1)[-1] != installed.rstrip("/").rsplit("/", 1)[-1]:
|
||||
raise LauncherPatternMissing(config, f"amiberry.rom_path naming {installed}")
|
||||
condition_line = max(
|
||||
n for n, text in script.code()
|
||||
if n < number and re.match(r"\s*(if|else)\b", text)
|
||||
)
|
||||
branch = script.lines[condition_line - 1].strip()
|
||||
if branch == "else":
|
||||
opened = max(
|
||||
n for n, text in script.code()
|
||||
if n < condition_line and re.match(r"\s*if\b", text)
|
||||
)
|
||||
test = _shell_test(script, opened)
|
||||
condition = f"not ({test})"
|
||||
else:
|
||||
test = _shell_test(script, condition_line)
|
||||
condition = test
|
||||
target = re.search(r'"?(\$\{?\w+\}?)"?\s*$', line)
|
||||
if target is None:
|
||||
raise script.missing(f"destination of the copy at line {number}")
|
||||
launchers.append(_evidence(read, Launcher(
|
||||
emulator="AMIBERRY", build="standalone", kind="fixed_name",
|
||||
slot=copied.group(1).removesuffix("-default.uae").removeprefix("Amiga"),
|
||||
names=[found[0].value.removeprefix("$(FILE_PATH)/")], case_insensitive=False,
|
||||
search_dir=BIOS,
|
||||
passes_to=f"{copied.group(1)} kickstart_rom_file, $(FILE_PATH) = {rom_path[0].value}",
|
||||
fails_when_missing=False,
|
||||
depends_on_option=f"{condition}, {content}",
|
||||
source_ref=source_ref([
|
||||
(RUNEMU, [table_line]), (path, [condition_line, number]),
|
||||
(config, [rom_path[0].line, found[0].line]),
|
||||
]),
|
||||
), script.expand(target.group(1), number, set()), ["kickstart_rom_file"],
|
||||
script, copied.group(1)))
|
||||
if len(launchers) == 1:
|
||||
raise script.missing("cp of a default .uae config")
|
||||
return launchers
|
||||
|
||||
|
||||
def _shell_test(script: Script, line: int) -> str:
|
||||
"""The test of `if <test>; then` at a line."""
|
||||
found = re.match(r"\s*if\s+(.*?);\s*then\s*$", script.lines[line - 1])
|
||||
if found is None:
|
||||
raise script.missing(f"if ...; then at line {line}")
|
||||
return found.group(1)
|
||||
|
||||
|
||||
def scummvm(read: Read) -> list[Launcher]:
|
||||
"""The paths scummvm.sh writes into the libretro core's scummvm.ini."""
|
||||
path = SCRIPTS["SCUMMVMSA"]
|
||||
script = Script(path, read(path))
|
||||
branch, _ = script.find(r'^\s*"libretro"\)', "libretro branch")
|
||||
launchers = []
|
||||
for number, line in script.code():
|
||||
if number < branch:
|
||||
continue
|
||||
written = re.search(r"s/\^/(\w*path)=((?:\\/[^\\/n]+)+)\\n/", line)
|
||||
if written is None:
|
||||
continue
|
||||
folder = written.group(2).replace("\\/", "/")
|
||||
if "/roms/bios/" not in folder + "/" or written.group(1) == "browser_lastpath":
|
||||
continue
|
||||
launchers.append(Launcher(
|
||||
emulator="scummvm", build="libretro", kind="passes_path", names=[],
|
||||
search_dir=folder, passes_to=f"scummvm.ini {written.group(1)}",
|
||||
fails_when_missing=False, depends_on_option="scummvm.sh libretro",
|
||||
source_ref=source_ref([(path, [branch, number])]),
|
||||
))
|
||||
if not launchers:
|
||||
raise script.missing("a scummvm.ini path written under /roms/bios")
|
||||
return launchers
|
||||
|
||||
|
||||
def freej2me(read: Read) -> list[Launcher]:
|
||||
"""`if [ ! -f <bios>/<jar> ]; then cp <shipped jar> <bios>`."""
|
||||
launchers = []
|
||||
for core, path in FREEJ2ME:
|
||||
script = Script(path, read(path))
|
||||
tested, test = script.find(
|
||||
rf'if \[ ! -f "{re.escape(BIOS)}/([^"]+)" \]', "jar presence test"
|
||||
)
|
||||
jar = test.group(1)
|
||||
lines = [tested]
|
||||
source = None
|
||||
for number, line in script.code():
|
||||
copied = re.match(rf"\s*cp\s+(?:-\S+\s+)*(\S+/{re.escape(jar)})\s+{re.escape(BIOS)}/?\s*$", line)
|
||||
if copied:
|
||||
lines.append(number)
|
||||
source = copied.group(1)
|
||||
if source is None:
|
||||
raise script.missing(f"cp of {jar} into {BIOS}")
|
||||
launchers.append(Launcher(
|
||||
emulator=core, build="libretro", kind="copies", names=[jar],
|
||||
case_insensitive=False, search_dir=posixpath.dirname(source), passes_to=BIOS,
|
||||
fails_when_missing=False, source_ref=source_ref([(path, lines)]),
|
||||
))
|
||||
return launchers
|
||||
|
||||
|
||||
def easyrpg(read: Read) -> list[Launcher]:
|
||||
"""Each install_bios call: a runtime package downloaded and unpacked under BIOS."""
|
||||
script = Script(EASYRPG, read(EASYRPG))
|
||||
url_line, url = script.find(r'curl -Lo "\$\{BIOS\}" "([^"]+)"', "curl of the package")
|
||||
launchers = []
|
||||
for number, line in script.code():
|
||||
call = re.match(r"\s*install_bios\s+(\S+)\s+(\S+)\s*$", line)
|
||||
if call is None:
|
||||
continue
|
||||
used: set[int] = {number, url_line}
|
||||
source = script.expand(url.group(1), number, used, {"BIOS": call.group(1)})
|
||||
install = script.value("INSTALLPATH", number)
|
||||
if install is None or install.value.rstrip("/") != BIOS:
|
||||
raise script.missing(f"INSTALLPATH {BIOS}")
|
||||
used.add(install.line)
|
||||
launchers.append(Launcher(
|
||||
emulator="easyrpg", build="libretro", kind="copies", names=[],
|
||||
search_dir=source, passes_to=f"{BIOS}/{call.group(2)}",
|
||||
fails_when_missing=False, source_ref=source_ref([(EASYRPG, used)]),
|
||||
))
|
||||
if not launchers:
|
||||
raise script.missing("install_bios call")
|
||||
return launchers
|
||||
|
||||
|
||||
def extract_launchers(read: Read) -> list[dict[str, Any]]:
|
||||
"""Every launcher record, read through `read(repo-relative path)`."""
|
||||
runemu = Runemu(read)
|
||||
# The atari800.cfg AmberELEC ships names the OS ROMs, but the core opens
|
||||
# it only under its atari800_cfg option, off by default, and finds the
|
||||
# ROMs by a scan of the content folder (libretro-atari800 atari.c:512-516,
|
||||
# 537, libretro_core_options.h:1203): no record reads it.
|
||||
launchers = [
|
||||
*retroarch(read), *retrorun(read), *mame(runemu),
|
||||
*scummvm(read), *freej2me(read), *easyrpg(read),
|
||||
*amiberry(read, runemu), *hatari(read, runemu), *pico8(read, runemu),
|
||||
*piemu(read, runemu), *yabasanshiro(read, runemu),
|
||||
]
|
||||
return [launcher.entry() for launcher in launchers]
|
||||
@@ -0,0 +1,332 @@
|
||||
"""Batocera's launcher layer, read from the configgen generators.
|
||||
|
||||
Between the file a user drops in /userdata/bios and the emulator, configgen
|
||||
decides which name is looked for and where it is handed over: the DuckStation
|
||||
generator walks a list of 22 names per region, Hatari's tries each TOS
|
||||
version in each language, xemu writes one fixed path into its config. That is
|
||||
the platform's behaviour, not the emulator's, so it is recorded here with the
|
||||
lines of the pinned revision that say it.
|
||||
|
||||
Every extractor reads a known shape with ast. A generator that no longer has
|
||||
that shape raises LauncherShapeError: an empty list would read as "this
|
||||
launcher looks for nothing".
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import ast
|
||||
import re
|
||||
from collections.abc import Callable, Iterable
|
||||
from dataclasses import dataclass
|
||||
from typing import Any
|
||||
|
||||
from model.launcherrecords import emulator_names, join_emulators
|
||||
from .configgen import (
|
||||
Launcher,
|
||||
LauncherShapeError,
|
||||
end_line,
|
||||
_assigned_name,
|
||||
_calls,
|
||||
_innermost_function,
|
||||
_outermost,
|
||||
)
|
||||
from .batocera_configgen import Configgen, GENERATORS, _path_value
|
||||
from .configgen_sites import GenericSites, bios_sites
|
||||
from .batocera_config_writes import gsplus, lexaloffle, melonds, mupen64plus, x16emu, xemu
|
||||
from .batocera_searches import duckstation, duckstation_legacy, hatari
|
||||
|
||||
LIBRETRO_OPTIONS = f"{GENERATORS}/libretro/libretroOptions.py"
|
||||
|
||||
|
||||
# Generators that hand a directory of /userdata/bios to the emulator through
|
||||
# its environment, with the module holding their path constants.
|
||||
ENVIRONMENT_GENERATORS = (("flycast.flycastGenerator", "flycast/flycastPaths.py"),)
|
||||
|
||||
|
||||
def environment_directories(cg: Configgen) -> list[Launcher]:
|
||||
"""Command(..., env={KEY: <path under BIOS>}) in the generator."""
|
||||
launchers: list[Launcher] = []
|
||||
for module, paths_module in ENVIRONMENT_GENERATORS:
|
||||
src = cg.generator(module)
|
||||
constants = dict(cg.paths)
|
||||
for node in cg.source(f"{cg.generators}/{paths_module}").tree.body:
|
||||
name = _assigned_name(node)
|
||||
value = _path_value(getattr(node, "value", None), constants)
|
||||
if name is not None and value is not None:
|
||||
constants[name] = value
|
||||
prefix = cg.bios.rstrip("/")
|
||||
found = [
|
||||
(str(key.value), value, key)
|
||||
for call in _calls(src.tree, attr="Command")
|
||||
for keyword in call.keywords
|
||||
if keyword.arg == "env" and isinstance(keyword.value, ast.Dict)
|
||||
for key, item in zip(keyword.value.keys, keyword.value.values)
|
||||
if isinstance(key, ast.Constant)
|
||||
and (value := _path_value(item, constants)) is not None
|
||||
and (value == prefix or value.startswith(prefix + "/"))
|
||||
]
|
||||
if not found:
|
||||
src.fail("the command environment names no /userdata/bios directory")
|
||||
launchers.extend(
|
||||
Launcher(
|
||||
emulator=cg.emulator(module), build="standalone", kind="passes_path",
|
||||
names=[], search_dir=value, passes_to=f"environment {key}",
|
||||
source_ref=src.ref([(node.lineno, end_line(node))]),
|
||||
)
|
||||
for key, value, node in found
|
||||
)
|
||||
return launchers
|
||||
|
||||
|
||||
# Generators that hand the emulator a /userdata/bios directory through its
|
||||
# configuration: a line written to the file it reads (openMSX's script.tcl
|
||||
# filepool entries, xroar.conf rompath) or a key saved to it (amiberry.conf
|
||||
# rom_path).
|
||||
CONFIG_DIRECTORY_GENERATORS = (
|
||||
"openmsx.openmsxGenerator",
|
||||
"xroar.xroarGenerator",
|
||||
"amiberry.amiberryGenerator",
|
||||
)
|
||||
|
||||
|
||||
def config_directories(
|
||||
cg: Configgen, modules: Iterable[str] = CONFIG_DIRECTORY_GENERATORS
|
||||
) -> list[Launcher]:
|
||||
"""file.write("<line naming a BIOS directory>") and settings.save(key, <BIOS directory>)."""
|
||||
prefix = cg.bios.rstrip("/")
|
||||
inside = re.compile(rf"{re.escape(prefix)}(?:/[^\s\"';]*)?")
|
||||
launchers: list[Launcher] = []
|
||||
for module in modules:
|
||||
src = cg.generator(module)
|
||||
constants = dict(cg.paths)
|
||||
for node in src.tree.body:
|
||||
name = _assigned_name(node)
|
||||
value = _path_value(getattr(node, "value", None), constants)
|
||||
if name is not None and value is not None:
|
||||
constants[name] = value
|
||||
found: list[tuple[str, str, ast.Call]] = []
|
||||
for call in _calls(src.tree, attr="write"):
|
||||
text = call.args[0] if len(call.args) == 1 else None
|
||||
if isinstance(text, ast.Constant) and isinstance(text.value, str):
|
||||
line = text.value.strip()
|
||||
named = inside.search(line)
|
||||
if named:
|
||||
found.append((named.group(0), f"written: {line}", call))
|
||||
for call in _calls(src.tree, attr="save"):
|
||||
if len(call.args) != 2 or not isinstance(call.args[0], ast.Constant):
|
||||
continue
|
||||
value = _path_value(call.args[1], constants)
|
||||
if value is None and isinstance(call.args[1], ast.Constant):
|
||||
value = str(call.args[1].value)
|
||||
if value is not None and (value.rstrip("/") == prefix or value.startswith(prefix + "/")):
|
||||
found.append((value, str(call.args[0].value), call))
|
||||
if not found:
|
||||
src.fail("hands no /userdata/bios directory through its config")
|
||||
launchers.extend(
|
||||
Launcher(
|
||||
emulator=cg.emulator(module), build="standalone", kind="passes_path",
|
||||
names=[], search_dir=directory, passes_to=passes_to,
|
||||
source_ref=src.ref([src.span(call)]),
|
||||
)
|
||||
for directory, passes_to, call in found
|
||||
)
|
||||
return launchers
|
||||
|
||||
|
||||
# Generators that start the emulator from a folder they enter with os.chdir.
|
||||
WORKING_DIRECTORY_GENERATORS = ("shadps4.shadps4Generator",)
|
||||
|
||||
|
||||
def working_directories(cg: Configgen) -> list[Launcher]:
|
||||
"""os.chdir(<folder>) in the generators above, before the command runs.
|
||||
|
||||
shadPS4 reads its user folder below the working directory first
|
||||
(std::filesystem::current_path() / "user"): Batocera enters
|
||||
/userdata/system/configs/shadps4.
|
||||
"""
|
||||
launchers = []
|
||||
for module in WORKING_DIRECTORY_GENERATORS:
|
||||
src = cg.generator(module)
|
||||
calls = _calls(src.tree, attr="chdir")
|
||||
if len(calls) != 1 or len(calls[0].args) != 1:
|
||||
src.fail("one os.chdir(folder) call")
|
||||
call = calls[0]
|
||||
argument = call.args[0]
|
||||
constants = dict(cg.paths)
|
||||
spans = [(call.lineno, call.end_lineno or call.lineno)]
|
||||
if isinstance(argument, ast.Name):
|
||||
scope = _innermost_function(src, call)
|
||||
assigned = src.assignment(argument.id, scope)
|
||||
spans.append((assigned.lineno, assigned.end_lineno or assigned.lineno))
|
||||
folder = _path_value(assigned.value, constants)
|
||||
else:
|
||||
folder = _path_value(argument, constants)
|
||||
if folder is None:
|
||||
src.fail("os.chdir names no folder")
|
||||
launchers.append(Launcher(
|
||||
emulator=cg.emulator(module), build="standalone", kind="passes_path", names=[],
|
||||
search_dir=folder, passes_to=f"working directory of {src.path.rsplit('/', 1)[-1]}",
|
||||
source_ref=src.ref(spans),
|
||||
))
|
||||
return launchers
|
||||
|
||||
|
||||
# libretro core options whose value names the BIOS file the core opens.
|
||||
FILE_OPTIONS = (("_o2em_options", "o2em_bios"), ("_neocd_options", "neocd_bios"))
|
||||
|
||||
|
||||
def core_file_options(cg: Configgen) -> list[Launcher]:
|
||||
"""_set_from_system(settings, option, system, [name], default=...)."""
|
||||
src = cg.source(cg.libretro_options)
|
||||
table = src.assignment("_option_functions").value
|
||||
if not isinstance(table, ast.Dict):
|
||||
src.fail("_option_functions is not a dict display")
|
||||
cores: dict[str, list[str]] = {}
|
||||
for key, value in zip(table.keys, table.values):
|
||||
if isinstance(key, ast.Constant) and isinstance(value, ast.Name):
|
||||
cores.setdefault(value.id, []).append(str(key.value))
|
||||
launchers = []
|
||||
for function_name, setting in FILE_OPTIONS:
|
||||
function = src.function(function_name)
|
||||
if function_name not in cores:
|
||||
src.fail(f"no core is configured by {function_name}")
|
||||
calls = [
|
||||
call for call in _calls(function, name="_set_from_system")
|
||||
if len(call.args) >= 2
|
||||
and isinstance(call.args[1], ast.Constant)
|
||||
and call.args[1].value == setting
|
||||
]
|
||||
if len(calls) != 1:
|
||||
src.fail(f"{function_name} no longer sets {setting} once")
|
||||
call = calls[0]
|
||||
named = call.args[3] if len(call.args) > 3 else None
|
||||
option = str(named.value) if isinstance(named, ast.Constant) else setting
|
||||
default = next((k.value for k in call.keywords if k.arg == "default"), None)
|
||||
if isinstance(default, ast.Constant):
|
||||
names = [str(default.value)]
|
||||
condition = None
|
||||
elif (
|
||||
isinstance(default, ast.IfExp)
|
||||
and isinstance(default.body, ast.Constant)
|
||||
and isinstance(default.orelse, ast.Constant)
|
||||
):
|
||||
names = [str(default.body.value), str(default.orelse.value)]
|
||||
condition = ast.unparse(default.test)
|
||||
else:
|
||||
src.fail(f"{setting} has no literal default")
|
||||
depends = option if condition is None else f"{option} (default by {condition})"
|
||||
launchers.append(Launcher(
|
||||
emulator=join_emulators(cores[function_name]), build="libretro", kind="core_option",
|
||||
names=names, passes_to=f"core option {setting}", depends_on_option=depends,
|
||||
source_ref=src.ref([src.span(_outermost(function, call))]),
|
||||
))
|
||||
return launchers
|
||||
|
||||
|
||||
# Batocera's patches to an emulator's own path code. Each rewrites one of
|
||||
# the folders the emulator derives (yuzu's family generates every user
|
||||
# folder through Generate<Name>Path) to a fixed folder of /userdata.
|
||||
PATH_PATCHES = ("package/batocera/emulators/citron/002-adjust-paths.patch",)
|
||||
_PATH_REMOVED = re.compile(r"^-\s*Generate\w+Path\((\w+Path::\w+),\s*(.+?)\);\s*$")
|
||||
_PATH_ADDED = re.compile(r'^\+\s*Generate\w+Path\((\w+Path::\w+),\s*"(/userdata/bios[^"]*)"\);\s*$')
|
||||
|
||||
|
||||
def patched_paths(read: Callable[[str], str], patches: tuple[str, ...] = PATH_PATCHES) -> list[Launcher]:
|
||||
"""The emulator folders a path patch points at the BIOS tree.
|
||||
|
||||
A patch line replacing `GenerateCitronPath(CitronPath::KeysDir,
|
||||
citron_path / KEYS_DIR)` with a literal /userdata/bios folder hands
|
||||
that folder to the emulator under the handle the code names it by.
|
||||
The emulator is the package the patch belongs to.
|
||||
"""
|
||||
launchers: list[Launcher] = []
|
||||
for path in patches:
|
||||
lines = read(path).splitlines()
|
||||
target = ""
|
||||
removed: dict[str, tuple[int, str]] = {}
|
||||
found = 0
|
||||
for number, line in enumerate(lines, 1):
|
||||
if line.startswith("+++ b/"):
|
||||
target = line[len("+++ b/"):]
|
||||
continue
|
||||
if (old := _PATH_REMOVED.match(line)):
|
||||
removed[old.group(1)] = (number, old.group(2))
|
||||
continue
|
||||
if not (new := _PATH_ADDED.match(line)):
|
||||
continue
|
||||
handle, folder = new.groups()
|
||||
if handle not in removed or not target:
|
||||
raise LauncherShapeError(f"{path}:{number}: {handle} added with no line it replaces")
|
||||
first, original = removed[handle]
|
||||
found += 1
|
||||
launchers.append(Launcher(
|
||||
emulator=path.split("/")[-2], build="standalone", kind="passes_path", names=[],
|
||||
search_dir=folder,
|
||||
passes_to=f"{handle} in {target} returns it, in place of {original}",
|
||||
fails_when_missing=False,
|
||||
source_ref=f"{path}:{first}-{number}",
|
||||
))
|
||||
if not found:
|
||||
raise LauncherShapeError(f"{path}: no path rewritten to /userdata/bios")
|
||||
return launchers
|
||||
|
||||
|
||||
# Generators whose command line hands the emulator /userdata/bios folders as
|
||||
# search paths: MAME's `-rompath` and `-samplepath` (mame/mameGenerator.py).
|
||||
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."""
|
||||
# A boot disk image the command line names (the Macintosh's
|
||||
# /userdata/bios/<boot_disk>.img) is a file, no search path.
|
||||
return [
|
||||
launcher
|
||||
for path in SEARCH_PATH_GENERATORS
|
||||
for launcher in bios_sites(cg, GenericSites(path, "passes_path"))
|
||||
if re.match(r"command line -\w", launcher.passes_to or "")
|
||||
]
|
||||
|
||||
|
||||
EXTRACTORS: tuple[Callable[[Configgen], list[Launcher]], ...] = (
|
||||
duckstation, duckstation_legacy, hatari, xemu, melonds, mupen64plus,
|
||||
x16emu, gsplus, lexaloffle, environment_directories, config_directories,
|
||||
core_file_options, working_directories, search_paths,
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Extraction:
|
||||
"""A configgen's launcher records, and the emulators it runs from the BIOS folder."""
|
||||
|
||||
records: list[dict[str, Any]]
|
||||
# The emulators whose program the launcher runs from the BIOS folder
|
||||
# (lexaloffle, /userdata/bios/pico-8/pico8): the user supplies it, no
|
||||
# package builds it.
|
||||
bios_programs: frozenset[str]
|
||||
|
||||
|
||||
def extraction(launchers: list[Launcher], bios: str) -> Extraction:
|
||||
"""The records of `launchers`, and those that run a program from `bios`."""
|
||||
root = bios.rstrip("/")
|
||||
return Extraction(
|
||||
records=[launcher.entry() for launcher in launchers],
|
||||
bios_programs=frozenset(
|
||||
name
|
||||
for launcher in launchers
|
||||
if launcher.passes_to == "exec"
|
||||
and launcher.search_dir is not None
|
||||
and (launcher.search_dir.rstrip("/") == root
|
||||
or launcher.search_dir.startswith(f"{root}/"))
|
||||
for name in emulator_names(launcher.emulator)
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def extract_launchers(read: Callable[[str], str]) -> Extraction:
|
||||
"""Every launcher record, read through `read(repo-relative path)`."""
|
||||
cg = Configgen(read)
|
||||
launchers = [launcher for extractor in EXTRACTORS for launcher in extractor(cg)]
|
||||
launchers += patched_paths(read)
|
||||
return extraction(launchers, cg.bios)
|
||||
@@ -0,0 +1,333 @@
|
||||
"""Batocera generators that write a BIOS path into a configuration or onto the command line."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import ast
|
||||
from collections.abc import Callable
|
||||
|
||||
from .batocera_configgen import Configgen, _path_value
|
||||
from .batocera_searches import option_names
|
||||
from .configgen import (
|
||||
Launcher,
|
||||
Source,
|
||||
_assigned_name,
|
||||
_calls,
|
||||
_enclosing_test,
|
||||
_innermost_function,
|
||||
_mentions,
|
||||
_outermost,
|
||||
assigned_value,
|
||||
end_line,
|
||||
)
|
||||
|
||||
|
||||
def _config_writes(cg: Configgen, src: Source, emulator: str) -> Launcher:
|
||||
"""parser.set(section, key, <path under BIOS>) calls of one module."""
|
||||
writes = []
|
||||
for call in _calls(src.tree, attr="set"):
|
||||
if len(call.args) != 3:
|
||||
continue
|
||||
section_node, key_node, path = call.args
|
||||
if not (isinstance(section_node, ast.Constant) and isinstance(key_node, ast.Constant)):
|
||||
continue
|
||||
name = cg.bios_name(path)
|
||||
if name is not None:
|
||||
writes.append((call, str(section_node.value), str(key_node.value), name))
|
||||
if not writes:
|
||||
src.fail("writes no /userdata/bios path into its config")
|
||||
spans = []
|
||||
conditions = []
|
||||
for call, _section, _key, _name in writes:
|
||||
scope = _innermost_function(src, call)
|
||||
spans.append(src.span(_outermost(scope, call)))
|
||||
test = _enclosing_test(scope, call)
|
||||
if test is not None and test not in conditions:
|
||||
conditions.append(test)
|
||||
keys = []
|
||||
for _call, section, key, _name in writes:
|
||||
label = f"[{section}] {key}"
|
||||
if label not in keys:
|
||||
keys.append(label)
|
||||
return Launcher(
|
||||
emulator=emulator, build="standalone", kind="fixed_name",
|
||||
names=list(dict.fromkeys(name for *_rest, name in writes)),
|
||||
case_insensitive=False, search_dir=cg.bios, passes_to=", ".join(keys),
|
||||
depends_on_option=", ".join(conditions) or None, source_ref=src.ref(spans),
|
||||
)
|
||||
|
||||
|
||||
def xemu(cg: Configgen) -> list[Launcher]:
|
||||
module = "xemu.xemuGenerator"
|
||||
return [_config_writes(cg, cg.helper(module, "xemuConfig"), cg.emulator(module))]
|
||||
|
||||
|
||||
def mupen64plus(cg: Configgen) -> list[Launcher]:
|
||||
module = "mupen.mupenGenerator"
|
||||
return [_config_writes(cg, cg.helper(module, "mupenConfig"), cg.emulator(module))]
|
||||
|
||||
|
||||
def melonds(cg: Configgen) -> list[Launcher]:
|
||||
"""One record per base_config section whose values are BIOS paths."""
|
||||
module = "melonds.melondsGenerator"
|
||||
src = cg.generator(module)
|
||||
generate = src.function("generate")
|
||||
base = src.assignment("base_config", generate)
|
||||
if not isinstance(base.value, ast.Dict):
|
||||
src.fail("base_config is not a dict display")
|
||||
console = [
|
||||
node for node in ast.walk(generate)
|
||||
if isinstance(node, ast.Assign)
|
||||
and ast.unparse(node.targets[0]).startswith("base_config['Emu']['ConsoleType']")
|
||||
and option_names(node.value)
|
||||
]
|
||||
enabled = [
|
||||
(key, value) for key, value in zip(base.value.keys, base.value.values)
|
||||
if isinstance(value, ast.Dict)
|
||||
and any(
|
||||
isinstance(k, ast.Constant) and k.value == "ExternalBIOSEnable" for k in value.keys
|
||||
)
|
||||
]
|
||||
if len(console) != 1 or len(enabled) != 1:
|
||||
src.fail("generate no longer sets Emu.ConsoleType from an option with external BIOS on")
|
||||
option = option_names(console[0].value)[0]
|
||||
enabled_key, enabled_value = enabled[0]
|
||||
if enabled_key is None:
|
||||
src.fail("base_config unpacks the section that enables the external BIOS")
|
||||
launchers = []
|
||||
for key, value in zip(base.value.keys, base.value.values):
|
||||
if not isinstance(value, ast.Dict) or not isinstance(key, ast.Constant):
|
||||
continue
|
||||
read = [
|
||||
(str(k.value), cg.bios_name(v)) for k, v in zip(value.keys, value.values)
|
||||
if isinstance(k, ast.Constant)
|
||||
]
|
||||
entries = [(k, name) for k, name in read if name is not None]
|
||||
if not entries:
|
||||
continue
|
||||
section = str(key.value)
|
||||
launchers.append(Launcher(
|
||||
emulator=cg.emulator(module), build="standalone", kind="fixed_name",
|
||||
names=[name for _k, name in entries], case_insensitive=False,
|
||||
search_dir=cg.bios,
|
||||
passes_to=", ".join(f"{section}.{k}" for k, _n in entries),
|
||||
depends_on_option=option,
|
||||
source_ref=src.ref([
|
||||
(key.lineno, end_line(value)),
|
||||
(enabled_key.lineno, end_line(enabled_value)),
|
||||
src.span(console[0]),
|
||||
]),
|
||||
))
|
||||
if not launchers:
|
||||
src.fail("base_config names no BIOS path")
|
||||
return launchers
|
||||
|
||||
|
||||
def x16emu(cg: Configgen) -> list[Launcher]:
|
||||
"""A command-line flag followed by a path under BIOS."""
|
||||
module = "x16emu.x16emuGenerator"
|
||||
src = cg.generator(module)
|
||||
found = []
|
||||
for node in ast.walk(src.function("generate")):
|
||||
if isinstance(node, ast.List):
|
||||
for flag, value in zip(node.elts, node.elts[1:]):
|
||||
name = cg.bios_name(value)
|
||||
if (
|
||||
isinstance(flag, ast.Constant)
|
||||
and str(flag.value).startswith("-")
|
||||
and name is not None
|
||||
):
|
||||
found.append((flag, str(flag.value), value, name))
|
||||
if not found:
|
||||
src.fail("the command line passes no /userdata/bios path")
|
||||
return [Launcher(
|
||||
emulator=cg.emulator(module), build="standalone", kind="fixed_name",
|
||||
names=[name for _f, _t, _v, name in found], case_insensitive=False,
|
||||
search_dir=cg.bios,
|
||||
passes_to=", ".join(f"command line {text}" for _f, text, _v, _n in found),
|
||||
source_ref=src.ref([(f.lineno, end_line(v)) for f, _t, v, _n in found]),
|
||||
)]
|
||||
|
||||
|
||||
def gsplus(cg: Configgen) -> list[Launcher]:
|
||||
"""config.save(key, f"{BIOS}/{system.config.get(option, default)}")."""
|
||||
module = "gsplus.gsplusGenerator"
|
||||
src = cg.generator(module)
|
||||
found = []
|
||||
for call in _calls(src.tree, attr="save"):
|
||||
if len(call.args) == 2 and isinstance(call.args[0], ast.Constant):
|
||||
named = cg.option_name(call.args[1])
|
||||
if named is not None:
|
||||
found.append((call, str(call.args[0].value), *named))
|
||||
if len(found) != 1:
|
||||
src.fail(f"expected one ROM path built from an option, found {len(found)}")
|
||||
call, key, name, option = found[0]
|
||||
return [Launcher(
|
||||
emulator=cg.emulator(module), build="standalone", kind="fixed_name",
|
||||
names=[name], case_insensitive=False, search_dir=cg.bios,
|
||||
passes_to=key, depends_on_option=option,
|
||||
source_ref=src.ref([src.span(_outermost(src.function("generate"), call))]),
|
||||
)]
|
||||
|
||||
|
||||
def system_branches(scope: ast.FunctionDef) -> list[tuple[str, ast.If]]:
|
||||
"""(system, branch) for each `if system.name == "<name>":` of an if/elif chain."""
|
||||
branches: list[tuple[str, ast.If]] = []
|
||||
for node in ast.walk(scope):
|
||||
if not isinstance(node, ast.If):
|
||||
continue
|
||||
test = node.test
|
||||
if (
|
||||
isinstance(test, ast.Compare)
|
||||
and ast.unparse(test.left) == "system.name"
|
||||
and len(test.ops) == 1
|
||||
and isinstance(test.ops[0], ast.Eq)
|
||||
and isinstance(test.comparators[0], ast.Constant)
|
||||
):
|
||||
branches.append((str(test.comparators[0].value), node))
|
||||
return sorted(branches, key=lambda item: item[1].lineno)
|
||||
|
||||
|
||||
def _guard_message(
|
||||
src: Source, scope: ast.FunctionDef, test: Callable[[ast.expr], bool], what: str
|
||||
) -> tuple[ast.If, ast.JoinedStr]:
|
||||
"""The `if not <test>: raise X(f"...")` statement and its message."""
|
||||
found = [
|
||||
(node, message) for node in ast.walk(scope)
|
||||
if isinstance(node, ast.If)
|
||||
and isinstance(node.test, ast.UnaryOp)
|
||||
and isinstance(node.test.op, ast.Not)
|
||||
and test(node.test.operand)
|
||||
and (message := _raised_fstring(node)) is not None
|
||||
]
|
||||
if len(found) != 1:
|
||||
src.fail(f"expected one `if not {what}: raise` with a message, found {len(found)}")
|
||||
return found[0]
|
||||
|
||||
|
||||
def _raised_fstring(node: ast.If) -> ast.JoinedStr | None:
|
||||
"""The f-string message of `raise X(f"...")` opening the if body."""
|
||||
first = node.body[0]
|
||||
if (
|
||||
isinstance(first, ast.Raise)
|
||||
and isinstance(first.exc, ast.Call)
|
||||
and first.exc.args
|
||||
and isinstance(first.exc.args[0], ast.JoinedStr)
|
||||
):
|
||||
return first.exc.args[0]
|
||||
return None
|
||||
|
||||
|
||||
def render(message: ast.JoinedStr, var: str, value: str) -> str:
|
||||
parts = []
|
||||
for part in message.values:
|
||||
if isinstance(part, ast.Constant):
|
||||
parts.append(str(part.value))
|
||||
continue
|
||||
# The other parts of an f-string are its {placeholders}.
|
||||
expr = part.value if isinstance(part, ast.FormattedValue) else part
|
||||
if isinstance(expr, ast.Name) and expr.id == var:
|
||||
parts.append(value)
|
||||
else:
|
||||
parts.append(f"{{{ast.unparse(expr)}}}")
|
||||
return "".join(parts)
|
||||
|
||||
|
||||
def lexaloffle(cg: Configgen) -> list[Launcher]:
|
||||
"""Per system, a binary under BIOS run as the command, its folder on LD_LIBRARY_PATH."""
|
||||
module = "lexaloffle.lexaloffleGenerator"
|
||||
src = cg.generator(module)
|
||||
constants = dict(cg.paths)
|
||||
defined: dict[str, ast.stmt] = {}
|
||||
for node in src.tree.body:
|
||||
name = _assigned_name(node)
|
||||
value = _path_value(getattr(node, "value", None), constants)
|
||||
if name is not None and value is not None:
|
||||
constants[name] = value
|
||||
defined[name] = node
|
||||
generate = src.function("generate")
|
||||
|
||||
command = [
|
||||
(node, head.id) for node in ast.walk(generate)
|
||||
if isinstance(node, (ast.Assign, ast.AnnAssign))
|
||||
and (assigned := assigned_value(node)) is not None
|
||||
and assigned[0] == "commandArray"
|
||||
and isinstance(assigned[1], ast.List)
|
||||
and assigned[1].elts
|
||||
and isinstance((head := assigned[1].elts[0]), ast.Name)
|
||||
]
|
||||
if len(command) != 1:
|
||||
src.fail("generate no longer starts commandArray with the binary it runs")
|
||||
command_stmt, binary = command[0]
|
||||
|
||||
exists, missing = _guard_message(src, generate, lambda test: (
|
||||
isinstance(test, ast.Call)
|
||||
and isinstance(test.func, ast.Attribute)
|
||||
and test.func.attr == "exists"
|
||||
and ast.unparse(test.func.value) == binary
|
||||
), f"{binary}.exists()")
|
||||
access, not_executable = _guard_message(src, generate, lambda test: (
|
||||
isinstance(test, ast.Call)
|
||||
and ast.unparse(test.func) == "os.access"
|
||||
and [ast.unparse(a) for a in test.args] == [binary, "os.X_OK"]
|
||||
), f"os.access({binary}, os.X_OK)")
|
||||
|
||||
env = [
|
||||
(key, value)
|
||||
for call in _calls(generate, attr="Command")
|
||||
for keyword in call.keywords
|
||||
if keyword.arg == "env" and isinstance(keyword.value, ast.Dict)
|
||||
for key, value in zip(keyword.value.keys, keyword.value.values)
|
||||
if isinstance(key, ast.Constant) and key.value == "LD_LIBRARY_PATH"
|
||||
]
|
||||
if len(env) != 1:
|
||||
src.fail("the command environment no longer sets LD_LIBRARY_PATH once")
|
||||
env_key, env_value = env[0]
|
||||
|
||||
prefix = cg.bios.rstrip("/") + "/"
|
||||
launchers = []
|
||||
for system, branch in system_branches(generate):
|
||||
bound = {
|
||||
assigned[0]: (stmt, assigned[1], _path_value(assigned[1], constants))
|
||||
for stmt in branch.body if (assigned := assigned_value(stmt)) is not None
|
||||
}
|
||||
if binary not in bound or not (bound[binary][2] or "").startswith(prefix):
|
||||
src.fail(f"the {system} branch binds {binary} to no path under {cg.bios}")
|
||||
library = [
|
||||
name for name in bound
|
||||
if name != binary and _mentions(env_value, set(), {name})
|
||||
]
|
||||
if len(library) != 1 or not (bound[library[0]][2] or "").startswith(prefix):
|
||||
src.fail(f"the {system} branch puts no /userdata/bios folder on LD_LIBRARY_PATH")
|
||||
binary_stmt, binary_value, path = bound[binary]
|
||||
library_stmt, _library_value, folder = bound[library[0]]
|
||||
if path is None:
|
||||
src.fail(f"the {system} branch binds {binary} to no path under {cg.bios}")
|
||||
test_line = src.span(branch.test)
|
||||
constant = next(
|
||||
(defined[n.id] for n in ast.walk(binary_value)
|
||||
if isinstance(n, ast.Name) and n.id in defined),
|
||||
None,
|
||||
)
|
||||
spans = [test_line, src.span(binary_stmt), src.span(exists), src.span(access),
|
||||
src.span(command_stmt)]
|
||||
if constant is not None:
|
||||
spans.append(src.span(constant))
|
||||
launchers.append(Launcher(
|
||||
emulator=cg.emulator(module), build="standalone", kind="fixed_name",
|
||||
slot=system, names=[path[len(prefix):]],
|
||||
case_insensitive=False, search_dir=cg.bios, passes_to="exec",
|
||||
fails_when_missing=", ".join(
|
||||
render(message, binary, path) for message in (missing, not_executable)
|
||||
),
|
||||
source_ref=src.ref(spans),
|
||||
))
|
||||
launchers.append(Launcher(
|
||||
emulator=cg.emulator(module), build="standalone", kind="passes_path",
|
||||
slot=system, names=[], search_dir=folder,
|
||||
passes_to="environment LD_LIBRARY_PATH",
|
||||
source_ref=src.ref([test_line, src.span(library_stmt),
|
||||
(src.span(env_key)[0], src.span(env_value)[1])]),
|
||||
))
|
||||
if not launchers:
|
||||
src.fail("generate no longer branches on system.name")
|
||||
return launchers
|
||||
@@ -0,0 +1,204 @@
|
||||
"""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 model.launcherrecords import join_emulators
|
||||
from .configgen 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_emulators(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]
|
||||
@@ -0,0 +1,427 @@
|
||||
"""Batocera generators that search BIOS names: DuckStation's region lists and Hatari's TOS."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import ast
|
||||
|
||||
from .batocera_configgen import Configgen, _config_option, _path_value
|
||||
from .configgen import (
|
||||
Launcher,
|
||||
Source,
|
||||
_assigned_name,
|
||||
_calls,
|
||||
_locate,
|
||||
_mentions,
|
||||
_run,
|
||||
end_line,
|
||||
)
|
||||
|
||||
|
||||
# The placeholder a Hatari TOS name carries for its language suffix.
|
||||
LANGUAGE_PLACEHOLDER = "L"
|
||||
|
||||
|
||||
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] = []
|
||||
for child in ast.walk(node):
|
||||
option = _config_option(child)
|
||||
if option is None and (
|
||||
isinstance(child, ast.Subscript)
|
||||
and ast.unparse(child.value) == "system.config"
|
||||
and isinstance(child.slice, ast.Constant)
|
||||
):
|
||||
option = (str(child.slice.value), None)
|
||||
if option is None and (
|
||||
isinstance(child, ast.Call)
|
||||
and ast.unparse(child.func) == "system.isOptSet"
|
||||
and child.args
|
||||
and isinstance(child.args[0], ast.Constant)
|
||||
):
|
||||
option = (str(child.args[0].value), None)
|
||||
if option is not None and option[0] not in found:
|
||||
found.append(option[0])
|
||||
return found
|
||||
|
||||
|
||||
def _raise_message(source: Source, scope: ast.AST, guard: str | None) -> str:
|
||||
"""The message of `if not <guard>: raise X("...")` in scope."""
|
||||
for node in ast.walk(scope):
|
||||
if (
|
||||
isinstance(node, ast.If)
|
||||
and isinstance(node.test, ast.UnaryOp)
|
||||
and isinstance(node.test.op, ast.Not)
|
||||
and isinstance(node.test.operand, ast.Name)
|
||||
and node.test.operand.id == guard
|
||||
and isinstance(node.body[0], ast.Raise)
|
||||
):
|
||||
exc = node.body[0].exc
|
||||
if isinstance(exc, ast.Call) and exc.args and isinstance(exc.args[0], ast.Constant):
|
||||
return str(exc.args[0].value)
|
||||
return source.fail(f"no `if not {guard}: raise` with a message")
|
||||
|
||||
|
||||
def _string_lists(source: Source, node: ast.AST, what: str) -> dict[str, list[str]]:
|
||||
value = source.literal(node, what)
|
||||
if not (
|
||||
isinstance(value, dict)
|
||||
and value
|
||||
and all(
|
||||
isinstance(v, list) and v and all(isinstance(n, str) for n in v)
|
||||
for v in value.values()
|
||||
)
|
||||
):
|
||||
source.fail(f"{what} is not a mapping of name lists")
|
||||
return value
|
||||
|
||||
|
||||
def duckstation(cg: Configgen) -> list[Launcher]:
|
||||
"""bios_lists searched case-insensitively, first hit per region."""
|
||||
module = "duckstation.duckstationGenerator"
|
||||
src = cg.generator(module)
|
||||
lists_node = src.assignment("bios_lists")
|
||||
lists = _string_lists(src, lists_node.value, "bios_lists")
|
||||
finder = src.function("find_bios")
|
||||
listed = [
|
||||
call.func.value.id for call in _calls(finder, attr="iterdir")
|
||||
if isinstance(call.func, ast.Attribute) and isinstance(call.func.value, ast.Name)
|
||||
]
|
||||
lowered = _calls(finder, attr="lower")
|
||||
if len(listed) != 1 or not lowered:
|
||||
src.fail("find_bios no longer lists the BIOS directory and compares lowercased names")
|
||||
search_dir = cg.paths.get(listed[0])
|
||||
if search_dir is None:
|
||||
src.fail("find_bios lists a directory that is not a batoceraPaths constant")
|
||||
|
||||
generate = src.function("generate")
|
||||
located = _locate(generate, lambda stmt: (
|
||||
isinstance(stmt, ast.Assign)
|
||||
and isinstance(stmt.value, ast.Call)
|
||||
and isinstance(stmt.value.func, ast.Name)
|
||||
and stmt.value.func.id == "find_bios"
|
||||
))
|
||||
if located is None:
|
||||
src.fail("generate no longer calls find_bios")
|
||||
body, index = located
|
||||
found_var = _assigned_name(body[index])
|
||||
if found_var is None:
|
||||
src.fail("find_bios result is not bound to a name")
|
||||
message = _raise_message(src, generate, found_var)
|
||||
|
||||
region_mapping = src.literal(
|
||||
src.assignment("region_mapping", generate).value, "region_mapping"
|
||||
)
|
||||
branches = [
|
||||
(node, node.test.left.value) for node in ast.walk(generate)
|
||||
if isinstance(node, ast.If)
|
||||
and isinstance(node.test, ast.Compare)
|
||||
and isinstance(node.test.left, ast.Constant)
|
||||
and isinstance(node.test.ops[0], ast.In)
|
||||
and ast.unparse(node.test.comparators[0]) == found_var
|
||||
]
|
||||
if len(branches) != 1:
|
||||
src.fail(f"generate no longer branches once on a slot found in {found_var}")
|
||||
branch, branch_slot = branches[0]
|
||||
writes = _calls(branch, attr="set")
|
||||
sections = {
|
||||
str(call.args[0].value) for call in writes if isinstance(call.args[0], ast.Constant)
|
||||
}
|
||||
if len(sections) != 1 or not any(
|
||||
isinstance(call.args[1], ast.Subscript)
|
||||
and ast.unparse(call.args[1].value) == "region_mapping"
|
||||
for call in writes
|
||||
):
|
||||
src.fail("the region paths are not written to one config section through region_mapping")
|
||||
section = sections.pop()
|
||||
shared = {
|
||||
branch_slot: [
|
||||
str(call.args[1].value) for stmt in branch.body for call in _calls(stmt, attr="set")
|
||||
if isinstance(call.args[1], ast.Constant)
|
||||
]
|
||||
}
|
||||
|
||||
first, last = _run(body, index, lambda stmt: _mentions(stmt, {section}, {found_var}))
|
||||
ref = src.ref([
|
||||
(src.span(first)[0], end_line(last)),
|
||||
(finder.lineno, end_line(finder)),
|
||||
src.span(lists_node),
|
||||
])
|
||||
launchers = []
|
||||
for slot, names in lists.items():
|
||||
keys = shared.get(slot) or ([region_mapping[slot]] if slot in region_mapping else None)
|
||||
if not keys:
|
||||
src.fail(f"bios_lists slot {slot} is written nowhere")
|
||||
launchers.append(Launcher(
|
||||
emulator=cg.emulator(module), build="standalone", kind="names_searched",
|
||||
slot=slot, names=names, case_insensitive=True, search_dir=search_dir,
|
||||
passes_to=f"[{section}] {', '.join(keys)}",
|
||||
fails_when_missing=message, fails_scope="emulator", source_ref=ref,
|
||||
))
|
||||
return launchers
|
||||
|
||||
|
||||
def duckstation_legacy(cg: Configgen) -> list[Launcher]:
|
||||
"""One name list per region, tried with Path.exists, first hit kept."""
|
||||
module = "duckstation_legacy.duckstationLegacyGenerator"
|
||||
src = cg.generator(module)
|
||||
generate = src.function("generate")
|
||||
loops = []
|
||||
for node in ast.walk(generate):
|
||||
if not (
|
||||
isinstance(node, ast.For)
|
||||
and isinstance(node.iter, ast.Name)
|
||||
and isinstance(node.target, ast.Name)
|
||||
):
|
||||
continue
|
||||
guard = node.body[0]
|
||||
if not isinstance(guard, ast.If):
|
||||
continue
|
||||
test = guard.test
|
||||
if not (
|
||||
isinstance(test, ast.Call)
|
||||
and isinstance(test.func, ast.Attribute)
|
||||
and test.func.attr == "exists"
|
||||
and isinstance(test.func.value, ast.BinOp)
|
||||
and isinstance(test.func.value.left, ast.Name)
|
||||
and ast.unparse(test.func.value.right) == node.target.id
|
||||
):
|
||||
continue
|
||||
bound = {
|
||||
_assigned_name(stmt): stmt for stmt in guard.body
|
||||
if isinstance(stmt, ast.Assign) and ast.unparse(stmt.value) == node.target.id
|
||||
}
|
||||
flags = {
|
||||
_assigned_name(stmt) for stmt in guard.body
|
||||
if isinstance(stmt, ast.Assign)
|
||||
and isinstance(stmt.value, ast.Constant)
|
||||
and stmt.value.value is True
|
||||
}
|
||||
if len(bound) != 1 or len(flags) != 1:
|
||||
src.fail(f"the loop over {node.iter.id} no longer keeps one file and one flag")
|
||||
loops.append((node.iter.id, next(iter(bound)), flags.pop(), test.func.value.left.id))
|
||||
if not loops:
|
||||
src.fail("generate no longer tries BIOS names with Path.exists")
|
||||
flags = {flag for _l, _v, flag, _d in loops}
|
||||
dirs = {directory for _l, _v, _f, directory in loops}
|
||||
if len(flags) != 1 or len(dirs) != 1 or next(iter(dirs)) not in cg.paths:
|
||||
src.fail("the region loops no longer share one flag and one BIOS directory")
|
||||
flag = flags.pop()
|
||||
search_dir = cg.paths[dirs.pop()]
|
||||
message = _raise_message(src, generate, flag)
|
||||
|
||||
writes: dict[str, tuple[str, str]] = {}
|
||||
for call in _calls(generate, attr="set"):
|
||||
if len(call.args) != 3:
|
||||
continue
|
||||
section_node, key_node, var_node = call.args
|
||||
if (
|
||||
isinstance(section_node, ast.Constant)
|
||||
and isinstance(key_node, ast.Constant)
|
||||
and isinstance(var_node, ast.Name)
|
||||
):
|
||||
writes[var_node.id] = (str(section_node.value), str(key_node.value))
|
||||
|
||||
list_nodes = {name: src.assignment(name, generate) for name, _v, _f, _d in loops}
|
||||
# A name never bound (None) is mentioned by no statement.
|
||||
tracked = {
|
||||
name for name in (*list_nodes, *(v for _l, v, _f, _d in loops), flag)
|
||||
if name is not None
|
||||
}
|
||||
first_list = min(list_nodes.values(), key=lambda node: node.lineno).node
|
||||
located = _locate(generate, lambda stmt: stmt is first_list)
|
||||
if located is None:
|
||||
src.fail(f"line {first_list.lineno} is outside generate")
|
||||
body, index = located
|
||||
sections = {section for section, _key in writes.values()}
|
||||
first, last = _run(body, index, lambda stmt: _mentions(stmt, sections, tracked))
|
||||
ref = src.ref([(src.span(first)[0], end_line(last))])
|
||||
|
||||
launchers = []
|
||||
for list_name, var, _flag, _dir in loops:
|
||||
if var not in writes:
|
||||
src.fail(f"{var} is written to no config key")
|
||||
section, key = writes[var]
|
||||
names = src.literal(list_nodes[list_name].value, list_name)
|
||||
if not (isinstance(names, list) and names and all(isinstance(n, str) for n in names)):
|
||||
src.fail(f"{list_name} is not a list of names")
|
||||
launchers.append(Launcher(
|
||||
emulator=cg.emulator(module), build="standalone", kind="names_searched",
|
||||
slot=key.removeprefix("Path"), names=names, case_insensitive=False,
|
||||
search_dir=search_dir, passes_to=f"[{section}] {key}",
|
||||
fails_when_missing=message, fails_scope="emulator", source_ref=ref,
|
||||
))
|
||||
return launchers
|
||||
|
||||
|
||||
def _loaded(stmt: ast.stmt) -> set[str]:
|
||||
"""Names an assignment reads on its right-hand side."""
|
||||
value = getattr(stmt, "value", None)
|
||||
return {n.id for n in ast.walk(value) if isinstance(n, ast.Name)} if value else set()
|
||||
|
||||
|
||||
def _branch_assigns(stmt: ast.stmt, needed: set[str]) -> bool:
|
||||
"""Whether an if statement assigns one of the names in any branch."""
|
||||
return isinstance(stmt, ast.If) and any(
|
||||
_assigned_name(node) in needed for node in ast.walk(stmt)
|
||||
)
|
||||
|
||||
|
||||
def _trace(body: list[ast.stmt], index: int) -> list[ast.stmt]:
|
||||
"""body[index], the assignments before it that bind what it reads, and
|
||||
the command-line additions that read any of those names.
|
||||
|
||||
An if statement that assigns a name read is kept with what its test
|
||||
reads (KNULLI's `if system.isOptSet("model") ...: machine = ...`)."""
|
||||
kept = [body[index]]
|
||||
needed = _loaded(body[index])
|
||||
for stmt in reversed(body[:index]):
|
||||
if _assigned_name(stmt) in needed:
|
||||
kept.append(stmt)
|
||||
needed |= _loaded(stmt)
|
||||
elif _branch_assigns(stmt, needed):
|
||||
kept.append(stmt)
|
||||
needed |= {n.id for n in ast.walk(stmt) if isinstance(n, ast.Name)}
|
||||
produced = {name for stmt in kept if (name := _assigned_name(stmt)) is not None}
|
||||
kept += [
|
||||
stmt for stmt in body
|
||||
if isinstance(stmt, ast.AugAssign) and _mentions(stmt.value, set(), produced)
|
||||
]
|
||||
return sorted(kept, key=lambda stmt: stmt.lineno)
|
||||
|
||||
|
||||
def _tos_name_parts(src: Source, finder: ast.FunctionDef) -> tuple[str, str, str]:
|
||||
"""(marker, prefix, suffix) of the names findBestTos builds."""
|
||||
marker = prefix = suffix = None
|
||||
for node in ast.walk(finder):
|
||||
if (
|
||||
isinstance(node, ast.If)
|
||||
and isinstance(node.test, ast.Compare)
|
||||
and isinstance(node.test.left, ast.Constant)
|
||||
and isinstance(node.test.ops[0], ast.In)
|
||||
and len(node.orelse) == 1
|
||||
and isinstance(node.orelse[0], ast.Assign)
|
||||
and isinstance(node.orelse[0].value, ast.JoinedStr)
|
||||
):
|
||||
parts = node.orelse[0].value.values
|
||||
if (
|
||||
len(parts) == 2
|
||||
and isinstance(parts[0], ast.Constant)
|
||||
and isinstance(parts[1], ast.FormattedValue)
|
||||
):
|
||||
marker, prefix = str(node.test.left.value), str(parts[0].value)
|
||||
# Batocera: tos_path = biosdir / f"{biosversion}{v_language}.img".
|
||||
# KNULLI: filename = f"{biosversion}{v_language}.img".
|
||||
names_built = []
|
||||
for node in ast.walk(finder):
|
||||
value = node.value if isinstance(node, ast.Assign) else None
|
||||
if isinstance(value, ast.BinOp) and isinstance(value.op, ast.Div):
|
||||
value = value.right
|
||||
if isinstance(value, ast.JoinedStr):
|
||||
parts = value.values
|
||||
if (
|
||||
len(parts) == 3
|
||||
and all(isinstance(p, ast.FormattedValue) for p in parts[:2])
|
||||
and isinstance(parts[2], ast.Constant)
|
||||
):
|
||||
names_built.append(str(parts[2].value))
|
||||
if len(names_built) == 1:
|
||||
suffix = names_built[0]
|
||||
if marker is None or prefix is None or suffix is None:
|
||||
src.fail("findBestTos no longer builds <tos{version} or etos*><language>.img")
|
||||
return marker, prefix, suffix
|
||||
|
||||
|
||||
def _tos_command_args(
|
||||
kept: list[ast.stmt], *, machine_var: str | None, tos_var: str | None,
|
||||
search_dir: str, paths: dict[str, str],
|
||||
) -> list[str]:
|
||||
"""The command-line additions of the traced statements, the TOS as <file>."""
|
||||
args: list[str] = []
|
||||
for stmt in kept:
|
||||
if isinstance(stmt, ast.AugAssign) and isinstance(stmt.value, ast.List):
|
||||
for element in stmt.value.elts:
|
||||
if isinstance(element, ast.Constant):
|
||||
args.append(str(element.value))
|
||||
elif isinstance(element, ast.Name) and element.id == machine_var:
|
||||
args.append("{machine}")
|
||||
elif isinstance(element, ast.Name) and element.id == tos_var:
|
||||
args.append("<file>")
|
||||
elif (
|
||||
isinstance(element, ast.BinOp)
|
||||
and isinstance(element.right, ast.Name)
|
||||
and element.right.id == tos_var
|
||||
and _path_value(element.left, paths) == search_dir
|
||||
):
|
||||
# KNULLI returns the bare name and joins it: BIOS / tos.
|
||||
args.append("<file>")
|
||||
return args
|
||||
|
||||
|
||||
def hatari(cg: Configgen) -> list[Launcher]:
|
||||
"""findBestTos: per machine, each TOS version in each language."""
|
||||
module = "hatari.hatariGenerator"
|
||||
src = cg.generator(module)
|
||||
finder = src.function("findBestTos")
|
||||
languages = src.literal(src.assignment("all_languages", finder).value, "all_languages")
|
||||
machines = _string_lists(
|
||||
src, src.assignment("all_machines_bios", finder).value, "all_machines_bios"
|
||||
)
|
||||
if not (
|
||||
isinstance(languages, list) and languages and all(isinstance(x, str) for x in languages)
|
||||
):
|
||||
src.fail("all_languages is not a list of strings")
|
||||
|
||||
marker, prefix, suffix = _tos_name_parts(src, finder)
|
||||
raised = [node for node in ast.walk(finder) if isinstance(node, ast.Raise)]
|
||||
exc = raised[0].exc if len(raised) == 1 else None
|
||||
if not (isinstance(exc, ast.Call) and exc.args and isinstance(exc.args[0], ast.JoinedStr)):
|
||||
src.fail("findBestTos no longer raises one formatted message")
|
||||
template = exc.args[0]
|
||||
|
||||
generate = src.function("generate")
|
||||
located = _locate(generate, lambda stmt: (
|
||||
isinstance(stmt, ast.Assign)
|
||||
and isinstance(stmt.value, ast.Call)
|
||||
and ast.unparse(stmt.value.func).endswith(".findBestTos")
|
||||
))
|
||||
if located is None:
|
||||
src.fail("generate no longer calls findBestTos")
|
||||
body, index = located
|
||||
found = body[index]
|
||||
if not (isinstance(found, ast.Assign) and isinstance(found.value, ast.Call)):
|
||||
src.fail("generate no longer calls findBestTos")
|
||||
call = found.value
|
||||
if not call.args or not isinstance(call.args[0], ast.Name) or call.args[0].id not in cg.paths:
|
||||
src.fail("findBestTos is not given a batoceraPaths directory")
|
||||
search_dir = cg.paths[call.args[0].id]
|
||||
kept = _trace(body, index)
|
||||
options = list(dict.fromkeys(name for stmt in kept for name in option_names(stmt)))
|
||||
spans = [src.span(stmt) for stmt in kept] + [(finder.lineno, end_line(finder))]
|
||||
second = call.args[1] if len(call.args) > 1 else None
|
||||
args = _tos_command_args(
|
||||
kept, machine_var=second.id if isinstance(second, ast.Name) else None,
|
||||
tos_var=_assigned_name(found), search_dir=search_dir, paths=cg.paths,
|
||||
)
|
||||
if "<file>" not in args:
|
||||
src.fail("the TOS findBestTos returns is not put on the command line")
|
||||
|
||||
ref = src.ref(spans)
|
||||
launchers = []
|
||||
for machine, versions in machines.items():
|
||||
message = "".join(
|
||||
str(part.value) if isinstance(part, ast.Constant) else machine
|
||||
for part in template.values
|
||||
)
|
||||
names = [
|
||||
f"{v if marker in v else prefix + v}{{{LANGUAGE_PLACEHOLDER}}}{suffix}"
|
||||
for v in versions
|
||||
]
|
||||
launchers.append(Launcher(
|
||||
emulator=cg.emulator(module), build="standalone", kind="names_searched",
|
||||
slot=machine, names=names, expands={LANGUAGE_PLACEHOLDER: languages},
|
||||
case_insensitive=False, search_dir=search_dir,
|
||||
passes_to=" ".join(args).replace("{machine}", machine),
|
||||
fails_when_missing=message, depends_on_option=", ".join(options),
|
||||
source_ref=ref,
|
||||
))
|
||||
return launchers
|
||||
@@ -0,0 +1,262 @@
|
||||
"""What the configgen launchers of Batocera and Recalbox have in common.
|
||||
|
||||
Both platforms start their emulators from a Python configgen, so their
|
||||
launcher layers are read the same way: parse each generator with ast,
|
||||
locate one known shape, and cite the lines it spans at the pinned revision.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import ast
|
||||
from collections.abc import Callable, Iterator
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, ClassVar, NoReturn, Protocol
|
||||
|
||||
|
||||
class LauncherShapeError(ValueError):
|
||||
"""A generator no longer has the shape its extractor reads."""
|
||||
|
||||
|
||||
class LauncherPatternMissing(LauncherShapeError):
|
||||
"""A construct an extractor reads is absent from the launcher source."""
|
||||
|
||||
def __init__(self, path: str, what: str) -> None:
|
||||
super().__init__(f"{path}: {what} not found")
|
||||
|
||||
|
||||
class Located(Protocol):
|
||||
"""A node that carries source lines: a statement, an expression, an argument."""
|
||||
|
||||
@property
|
||||
def lineno(self) -> int: ...
|
||||
|
||||
@property
|
||||
def end_lineno(self) -> int | None: ...
|
||||
|
||||
|
||||
def end_line(node: Located) -> int:
|
||||
"""The last line of a parsed node, which ast.parse always sets."""
|
||||
if node.end_lineno is None:
|
||||
raise LauncherShapeError(f"node at line {node.lineno} has no end line")
|
||||
return node.end_lineno
|
||||
|
||||
|
||||
@dataclass
|
||||
class Launcher:
|
||||
"""One thing a launcher looks for or hands over, as its code says it."""
|
||||
|
||||
emulator: str
|
||||
build: str
|
||||
kind: str
|
||||
names: list[str]
|
||||
source_ref: str
|
||||
slot: str | None = None
|
||||
expands: dict[str, list[str]] | None = None
|
||||
case_insensitive: bool | None = None
|
||||
search_dir: str | None = None
|
||||
passes_to: str | None = None
|
||||
fails_when_missing: bool | str | None = False
|
||||
fails_scope: str | None = None
|
||||
depends_on_option: str | None = None
|
||||
device: str | None = None
|
||||
# The machines the platform offers under the record's systems.
|
||||
machines: list[str] | None = None
|
||||
# The platform systems the record is written for, none for every one.
|
||||
systems: list[str] | None = None
|
||||
# For a record citing a config: where the platform's code puts it
|
||||
# ({path, source_ref}), whether that leaves a file already there, and
|
||||
# the launch code rewriting its keys ([] when none does).
|
||||
installs: dict[str, str] | None = None
|
||||
kept_if_present: bool | None = None
|
||||
overrides: list[str] | None = None
|
||||
# The feature or option file listing the values the option written takes.
|
||||
choices_from: str | None = None
|
||||
|
||||
# The platform YAML key order. A platform whose records carry other
|
||||
# fields (RetroPie's package and repo) declares its own.
|
||||
ENTRY_ORDER: ClassVar[tuple[str, ...]] = (
|
||||
"emulator", "systems", "build", "kind", "slot", "names", "expands",
|
||||
"case_insensitive", "search_dir", "passes_to",
|
||||
"fails_when_missing", "fails_scope", "depends_on_option",
|
||||
"device", "machines", "installs", "kept_if_present", "overrides",
|
||||
"choices_from", "source_ref",
|
||||
)
|
||||
|
||||
def entry(self) -> dict[str, Any]:
|
||||
"""The platform YAML form, in a fixed key order, unset keys left out."""
|
||||
return {key: getattr(self, key) for key in self.ENTRY_ORDER if getattr(self, key) is not None}
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Assignment:
|
||||
"""A single-name assignment statement and the value it binds."""
|
||||
|
||||
node: ast.Assign | ast.AnnAssign
|
||||
value: ast.expr
|
||||
|
||||
@property
|
||||
def lineno(self) -> int:
|
||||
return self.node.lineno
|
||||
|
||||
@property
|
||||
def end_lineno(self) -> int | None:
|
||||
return self.node.end_lineno
|
||||
|
||||
|
||||
class Source:
|
||||
"""One configgen file, parsed, with the lines its nodes span."""
|
||||
|
||||
def __init__(self, path: str, text: str) -> None:
|
||||
self.path = path
|
||||
self.lines = text.splitlines()
|
||||
try:
|
||||
self.tree = ast.parse(text)
|
||||
except SyntaxError as e:
|
||||
raise LauncherShapeError(f"{path}: {e}") from e
|
||||
|
||||
def fail(self, what: str) -> NoReturn:
|
||||
raise LauncherShapeError(f"{self.path}: {what}")
|
||||
|
||||
def function(self, name: str) -> ast.FunctionDef:
|
||||
found = [
|
||||
node for node in ast.walk(self.tree)
|
||||
if isinstance(node, ast.FunctionDef) and node.name == name
|
||||
]
|
||||
if len(found) != 1:
|
||||
self.fail(f"expected one function {name}, found {len(found)}")
|
||||
return found[0]
|
||||
|
||||
def assignment(self, name: str, scope: ast.AST | None = None) -> Assignment:
|
||||
found = [
|
||||
Assignment(node, assigned[1]) for node in ast.walk(scope or self.tree)
|
||||
if isinstance(node, (ast.Assign, ast.AnnAssign))
|
||||
and (assigned := assigned_value(node)) is not None and assigned[0] == name
|
||||
]
|
||||
if len(found) != 1:
|
||||
self.fail(f"expected one assignment to {name}, found {len(found)}")
|
||||
return found[0]
|
||||
|
||||
def literal(self, node: ast.AST, what: str) -> Any:
|
||||
try:
|
||||
return ast.literal_eval(node)
|
||||
except (ValueError, TypeError, SyntaxError) as e:
|
||||
self.fail(f"{what} is not a literal: {e}")
|
||||
|
||||
def span(self, node: Located) -> tuple[int, int]:
|
||||
"""Lines of a node, with the comment lines written right above it."""
|
||||
start = node.lineno
|
||||
while start > 1 and self.lines[start - 2].strip().startswith("#"):
|
||||
start -= 1
|
||||
return start, end_line(node)
|
||||
|
||||
def ref(self, spans: list[tuple[int, int]]) -> str:
|
||||
"""`path:a-b, c-d`, ranges joined across blank and comment lines."""
|
||||
merged: list[list[int]] = []
|
||||
for start, end in sorted(spans):
|
||||
if merged and self._only_filler(merged[-1][1] + 1, start - 1):
|
||||
merged[-1][1] = max(merged[-1][1], end)
|
||||
else:
|
||||
merged.append([start, end])
|
||||
parts = [f"{a}" if a == b else f"{a}-{b}" for a, b in merged]
|
||||
return f"{self.path}:{', '.join(parts)}"
|
||||
|
||||
def _only_filler(self, first: int, last: int) -> bool:
|
||||
return all(
|
||||
not line.strip() or line.strip().startswith("#")
|
||||
for line in self.lines[max(first - 1, 0):max(last, 0)]
|
||||
)
|
||||
|
||||
|
||||
def assigned_value(node: ast.AST) -> tuple[str, ast.expr] | None:
|
||||
"""The name a single-name assignment binds, and the value it binds."""
|
||||
if isinstance(node, ast.Assign) and len(node.targets) == 1:
|
||||
target, value = node.targets[0], node.value
|
||||
elif isinstance(node, ast.AnnAssign) and node.value is not None:
|
||||
target, value = node.target, node.value
|
||||
else:
|
||||
return None
|
||||
return (target.id, value) if isinstance(target, ast.Name) else None
|
||||
|
||||
|
||||
def _assigned_name(node: ast.AST) -> str | None:
|
||||
assigned = assigned_value(node)
|
||||
return assigned[0] if assigned is not None else None
|
||||
|
||||
|
||||
def _statement_lists(node: ast.AST) -> Iterator[list[ast.stmt]]:
|
||||
for child in ast.walk(node):
|
||||
for attr in ("body", "orelse", "finalbody"):
|
||||
value = getattr(child, attr, None)
|
||||
if isinstance(value, list) and value and isinstance(value[0], ast.stmt):
|
||||
yield value
|
||||
|
||||
|
||||
def _locate(
|
||||
scope: ast.AST, wanted: Callable[[ast.stmt], bool]
|
||||
) -> tuple[list[ast.stmt], int] | None:
|
||||
"""The innermost statement list holding a statement that satisfies `wanted`."""
|
||||
for body in _statement_lists(scope):
|
||||
for index, stmt in enumerate(body):
|
||||
if wanted(stmt):
|
||||
return body, index
|
||||
return None
|
||||
|
||||
|
||||
def _outermost(scope: ast.FunctionDef, node: ast.AST) -> ast.stmt:
|
||||
"""The statement of the function body that contains `node`."""
|
||||
for stmt in scope.body:
|
||||
if any(child is node for child in ast.walk(stmt)):
|
||||
return stmt
|
||||
line = getattr(node, "lineno", "?")
|
||||
raise LauncherShapeError(f"node at line {line} is outside {scope.name}")
|
||||
|
||||
|
||||
def _mentions(stmt: ast.AST, constants: set[str], names: set[str]) -> bool:
|
||||
for node in ast.walk(stmt):
|
||||
if isinstance(node, ast.Constant) and node.value in constants:
|
||||
return True
|
||||
if isinstance(node, ast.Name) and node.id in names:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _run(
|
||||
body: list[ast.stmt], index: int, keep: Callable[[ast.stmt], bool]
|
||||
) -> tuple[ast.stmt, ast.stmt]:
|
||||
"""The contiguous statements around body[index] that `keep` accepts."""
|
||||
first = last = index
|
||||
while first > 0 and keep(body[first - 1]):
|
||||
first -= 1
|
||||
while last + 1 < len(body) and keep(body[last + 1]):
|
||||
last += 1
|
||||
return body[first], body[last]
|
||||
|
||||
|
||||
def _calls(scope: ast.AST, attr: str | None = None, name: str | None = None) -> list[ast.Call]:
|
||||
found = []
|
||||
for node in ast.walk(scope):
|
||||
if not isinstance(node, ast.Call):
|
||||
continue
|
||||
func = node.func
|
||||
if attr is not None and isinstance(func, ast.Attribute) and func.attr == attr or name is not None and isinstance(func, ast.Name) and func.id == name:
|
||||
found.append(node)
|
||||
return sorted(found, key=lambda call: (call.lineno, call.col_offset))
|
||||
|
||||
|
||||
def _enclosing_test(scope: ast.AST, node: ast.AST) -> str | None:
|
||||
for parent in ast.walk(scope):
|
||||
if isinstance(parent, ast.If) and any(
|
||||
child is node for stmt in parent.body for child in ast.walk(stmt)
|
||||
):
|
||||
return ast.unparse(parent.test)
|
||||
return None
|
||||
|
||||
|
||||
def _innermost_function(src: Source, node: ast.stmt | ast.expr) -> ast.FunctionDef:
|
||||
holders = [
|
||||
f for f in ast.walk(src.tree)
|
||||
if isinstance(f, ast.FunctionDef) and any(child is node for child in ast.walk(f))
|
||||
]
|
||||
if not holders:
|
||||
src.fail(f"line {node.lineno} is outside any function")
|
||||
return max(holders, key=lambda f: f.lineno)
|
||||
@@ -0,0 +1,538 @@
|
||||
"""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 model.launcherrecords import join_emulators
|
||||
from .batocera_configgen import Configgen, _path_value
|
||||
from .configgen 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 <expr>."""
|
||||
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_emulators(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
|
||||
@@ -0,0 +1,313 @@
|
||||
"""C# source read as text, never compiled: comments and strings told apart from
|
||||
code, string literals, call arguments, statements, and the lines a construct
|
||||
spans. A construct that is gone raises LauncherPatternMissing."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import bisect
|
||||
import re
|
||||
from collections.abc import Iterator
|
||||
|
||||
from core.lines import LineIndex
|
||||
from model.sourceref import span
|
||||
|
||||
from .configgen import LauncherPatternMissing
|
||||
from .shell import merge_lines
|
||||
|
||||
|
||||
STRING = r'"((?:[^"\\\n]|\\.)*)"'
|
||||
|
||||
Record = dict[str, object]
|
||||
|
||||
|
||||
class Source:
|
||||
"""One source file with line lookup and C#-aware brace matching."""
|
||||
|
||||
def __init__(self, path: str, text: str) -> None:
|
||||
self.path = path
|
||||
self.text = text
|
||||
self._lines = LineIndex(text)
|
||||
self._blocks: list[tuple[int, int]] | None = None
|
||||
self._ends: list[int] | None = None
|
||||
self.code: str | None = None
|
||||
self.bare: str | None = None
|
||||
|
||||
def line(self, offset: int) -> int:
|
||||
return self._lines.line(offset)
|
||||
|
||||
def lines(self, start: int, end: int) -> tuple[int, int]:
|
||||
return self.line(start), self.line(max(start, end - 1))
|
||||
|
||||
def find(
|
||||
self, pattern: str, what: str, start: int = 0, end: int | None = None, flags: int = 0
|
||||
) -> re.Match[str]:
|
||||
found = re.compile(pattern, flags).search(
|
||||
self.text, start, len(self.text) if end is None else end
|
||||
)
|
||||
if found is None:
|
||||
raise LauncherPatternMissing(self.path, what)
|
||||
return found
|
||||
|
||||
def find_all(
|
||||
self, pattern: str, what: str, start: int = 0, end: int | None = None
|
||||
) -> list[re.Match[str]]:
|
||||
found = list(
|
||||
re.compile(pattern).finditer(self.text, start, len(self.text) if end is None else end)
|
||||
)
|
||||
if not found:
|
||||
raise LauncherPatternMissing(self.path, what)
|
||||
return found
|
||||
|
||||
def blocks(self) -> list[tuple[int, int]]:
|
||||
"""Every brace pair, as (offset of "{", offset after "}")."""
|
||||
if self._blocks is None:
|
||||
self._blocks = []
|
||||
stack: list[int] = []
|
||||
for offset, char in _code_chars(self.text):
|
||||
if char == "{":
|
||||
stack.append(offset)
|
||||
elif char == "}" and stack:
|
||||
self._blocks.append((stack.pop(), offset + 1))
|
||||
return self._blocks
|
||||
|
||||
def block_at(self, open_offset: int) -> tuple[int, int]:
|
||||
"""The block opened by the first "{" at or after open_offset."""
|
||||
candidates = [b for b in self.blocks() if b[0] >= open_offset]
|
||||
if not candidates:
|
||||
raise LauncherPatternMissing(self.path, f"block after line {self.line(open_offset)}")
|
||||
return min(candidates)
|
||||
|
||||
def enclosing(self, offset: int) -> tuple[int, int]:
|
||||
"""The innermost block holding offset."""
|
||||
holding = [b for b in self.blocks() if b[0] < offset < b[1]]
|
||||
if not holding:
|
||||
raise LauncherPatternMissing(self.path, f"block around line {self.line(offset)}")
|
||||
return max(holding)
|
||||
|
||||
def header(self, block: tuple[int, int]) -> str:
|
||||
"""The statement that owns a block's opening brace, comments and
|
||||
preprocessor lines (#region, #if) removed."""
|
||||
if self._ends is None:
|
||||
self._ends = [o for o, c in _code_chars(self.text) if c in ";{}"]
|
||||
previous = bisect.bisect_left(self._ends, block[0]) - 1
|
||||
start = self._ends[previous] + 1 if previous >= 0 else 0
|
||||
text = re.sub(r"^[ \t]*#[^\n]*", "", _code(self)[start : block[0]], flags=re.M)
|
||||
return " ".join(text.split())
|
||||
|
||||
def statement_span(self, block: tuple[int, int]) -> tuple[int, int]:
|
||||
"""Lines of a block, from the statement that owns its opening brace."""
|
||||
first, last = self.lines(*block)
|
||||
line_text = self.text[self._lines.start(first) : block[0]].strip()
|
||||
return (first - 1 if not line_text and first > 1 else first), last
|
||||
|
||||
|
||||
def _scan(text: str) -> Iterator[tuple[str, int, int]]:
|
||||
"""C# text as (kind, start, end) runs: "comment", "literal" (string or
|
||||
char) and "code", one code character per run."""
|
||||
i, n = 0, len(text)
|
||||
while i < n:
|
||||
start = i
|
||||
if text.startswith("//", i):
|
||||
i = text.find("\n", i)
|
||||
i = n if i < 0 else i
|
||||
yield "comment", start, i
|
||||
elif text.startswith("/*", i):
|
||||
close = text.find("*/", i + 2)
|
||||
i = n if close < 0 else close + 2
|
||||
yield "comment", start, i
|
||||
elif text.startswith('@"', i):
|
||||
i += 2
|
||||
while i < n and not (text[i] == '"' and not text.startswith('""', i)):
|
||||
i += 2 if text.startswith('""', i) else 1
|
||||
i += 1
|
||||
yield "literal", start, min(i, n)
|
||||
elif text[i] in "\"'":
|
||||
quote = text[i]
|
||||
i += 1
|
||||
while i < n and text[i] != quote and text[i] != "\n":
|
||||
i += 2 if text[i] == "\\" else 1
|
||||
i += 1
|
||||
yield "literal", start, min(i, n)
|
||||
else:
|
||||
i += 1
|
||||
yield "code", start, i
|
||||
|
||||
|
||||
def _code_chars(text: str) -> Iterator[tuple[int, str]]:
|
||||
"""Characters of C# code outside string, char literals and comments."""
|
||||
return ((start, text[start]) for kind, start, _ in _scan(text) if kind == "code")
|
||||
|
||||
|
||||
def blank_comments(text: str) -> str:
|
||||
"""C# text with every comment blanked, offsets and lines unchanged;
|
||||
a // or /* inside a string literal is text, not a comment."""
|
||||
chars = list(text)
|
||||
for kind, start, end in _scan(text):
|
||||
if kind == "comment":
|
||||
for i in range(start, end):
|
||||
if chars[i] != "\n":
|
||||
chars[i] = " "
|
||||
return "".join(chars)
|
||||
|
||||
|
||||
def _unescape(literal: str) -> str:
|
||||
return re.sub(r"\\(.)", lambda m: {"n": "\n", "t": "\t"}.get(m.group(1), m.group(1)), literal)
|
||||
|
||||
|
||||
def _strings(text: str) -> list[str]:
|
||||
return [_unescape(m.group(1)) for m in re.finditer(STRING, text)]
|
||||
|
||||
|
||||
def _unique(names: list[str]) -> list[str]:
|
||||
return list(dict.fromkeys(names))
|
||||
|
||||
|
||||
def source_ref(*parts: tuple[str, list[tuple[int, int]]]) -> str:
|
||||
"""path:a-b, c-d for each file, spans one line apart joined."""
|
||||
refs = []
|
||||
for path, spans in parts:
|
||||
lines = merge_lines(n for first, last in spans for n in range(first, last + 1))
|
||||
refs.append(f"{path}:{', '.join(span(*s) for s in lines)}")
|
||||
return ", ".join(refs)
|
||||
|
||||
|
||||
def _array_at(src: Source, offset: int) -> tuple[list[str], tuple[int, int]]:
|
||||
"""String literals of the array initializer opened at offset."""
|
||||
block = src.block_at(offset)
|
||||
return _strings(src.text[block[0] : block[1]]), src.lines(*block)
|
||||
|
||||
|
||||
def _call_args(src: Source, open_paren: int) -> str:
|
||||
depth = 0
|
||||
for offset, char in _code_chars(src.text[open_paren:]):
|
||||
if char == "(":
|
||||
depth += 1
|
||||
elif char == ")":
|
||||
depth -= 1
|
||||
if depth == 0:
|
||||
return src.text[open_paren + 1 : open_paren + offset]
|
||||
raise LauncherPatternMissing(src.path, f"closing parenthesis after line {src.line(open_paren)}")
|
||||
|
||||
|
||||
def render_concat(expression: str) -> str:
|
||||
"""A C# string concatenation as text, each non-literal operand as <operand>."""
|
||||
parts, depth, current, in_string = [], 0, "", False
|
||||
i = 0
|
||||
while i < len(expression):
|
||||
char = expression[i]
|
||||
if in_string:
|
||||
current += char
|
||||
if char == "\\":
|
||||
current += expression[i + 1]
|
||||
i += 1
|
||||
elif char == '"':
|
||||
in_string = False
|
||||
elif char == '"':
|
||||
in_string = True
|
||||
current += char
|
||||
elif char in "([":
|
||||
depth += 1
|
||||
current += char
|
||||
elif char in ")]":
|
||||
depth -= 1
|
||||
current += char
|
||||
elif char == "+" and depth == 0:
|
||||
parts.append(current.strip())
|
||||
current = ""
|
||||
else:
|
||||
current += char
|
||||
i += 1
|
||||
parts.append(current.strip())
|
||||
rendered = []
|
||||
for part in parts:
|
||||
literal = re.fullmatch(STRING, part)
|
||||
rendered.append(_unescape(literal.group(1)) if literal else f"<{part}>")
|
||||
return "".join(rendered)
|
||||
|
||||
|
||||
def _throw_message(src: Source, start: int, end: int) -> tuple[str, int]:
|
||||
found = src.find(r"throw new ApplicationException\(", "ApplicationException", start, end)
|
||||
message = render_concat(_call_args(src, found.end() - 1))
|
||||
return f"ApplicationException '{message}'", src.line(found.start())
|
||||
|
||||
|
||||
_METHOD = re.compile(
|
||||
r"(?:(?:public|private|protected|internal|static|override|virtual)\s+)+[\w<>\[\],. ]+\s\w+\s*\("
|
||||
)
|
||||
|
||||
|
||||
def _code(src: Source) -> str:
|
||||
"""The text with comments blanked, offsets and lines unchanged."""
|
||||
if src.code is None:
|
||||
src.code = blank_comments(src.text)
|
||||
return src.code
|
||||
|
||||
|
||||
def _split_top(text: str, separator: str) -> list[str]:
|
||||
"""text split on separator outside strings, parentheses and braces."""
|
||||
code = {offset for offset, _ in _code_chars(text)}
|
||||
parts, depth, start = [], 0, 0
|
||||
for i, char in enumerate(text):
|
||||
if i not in code:
|
||||
continue
|
||||
if char in "([{":
|
||||
depth += 1
|
||||
elif char in ")]}":
|
||||
depth -= 1
|
||||
elif depth == 0 and text.startswith(separator, i):
|
||||
parts.append(text[start:i].strip())
|
||||
start = i + len(separator)
|
||||
parts.append(text[start:].strip())
|
||||
return parts
|
||||
|
||||
|
||||
def _wrapped(expr: str, opener: str) -> str | None:
|
||||
"""The inside of opener(...) when the parentheses span the whole expression."""
|
||||
if not expr.startswith(opener + "(") or not expr.endswith(")"):
|
||||
return None
|
||||
inner = expr[len(opener) + 1 : -1]
|
||||
depth = 0
|
||||
for _offset, char in _code_chars(inner):
|
||||
depth += {"(": 1, ")": -1}.get(char, 0)
|
||||
if depth < 0:
|
||||
return None
|
||||
return inner
|
||||
|
||||
|
||||
def _method_of(src: Source, offset: int) -> tuple[int, int]:
|
||||
for block in sorted((b for b in src.blocks() if b[0] < offset < b[1]), reverse=True):
|
||||
if _METHOD.match(src.header(block)):
|
||||
return block
|
||||
raise LauncherPatternMissing(src.path, f"method around line {src.line(offset)}")
|
||||
|
||||
|
||||
def _bare(src: Source) -> str:
|
||||
"""The code with comments and the inside of literals blanked."""
|
||||
if src.bare is None:
|
||||
chars = [" " if c != "\n" else c for c in src.text]
|
||||
for offset, char in _code_chars(src.text):
|
||||
chars[offset] = char
|
||||
src.bare = "".join(chars)
|
||||
return src.bare
|
||||
|
||||
|
||||
def _statement_start(src: Source, offset: int) -> int:
|
||||
code = _bare(src)
|
||||
found = max(code.rfind(";", 0, offset), code.rfind("{", 0, offset), code.rfind("}", 0, offset))
|
||||
start = found + 1
|
||||
while start < offset and code[start].isspace():
|
||||
start += 1
|
||||
return start
|
||||
|
||||
|
||||
def _statement_end(src: Source, offset: int) -> int:
|
||||
"""Offset of the semicolon that ends the statement running at offset."""
|
||||
depth = 0
|
||||
for position, char in _code_chars(src.text[offset:]):
|
||||
if char in "([{":
|
||||
depth += 1
|
||||
elif char in ")]}":
|
||||
depth -= 1
|
||||
elif char == ";" and depth == 0:
|
||||
return offset + position
|
||||
raise LauncherPatternMissing(src.path, f"end of the statement at line {src.line(offset)}")
|
||||
@@ -0,0 +1,414 @@
|
||||
"""EmuDeck's launcher layer, read from its EmuScripts at the pinned commit.
|
||||
|
||||
Each functions/EmuScripts/emuDeck<Name>.sh sets an emulator up once, at
|
||||
install or update: it writes BIOS paths into the emulator's config with
|
||||
changeLine, iniFieldUpdate or RetroArch_setConfigOverride, rewrites the
|
||||
paths of a config it ships with sed, or links a directory of bios/ to the
|
||||
emulator's own. Nothing runs between that setup and a launch, so these are
|
||||
the names and directories the emulator is left with.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import posixpath
|
||||
import re
|
||||
from collections.abc import Callable
|
||||
|
||||
from .configgen import Launcher
|
||||
from scraper.launchers.shell import (
|
||||
describe_keys,
|
||||
LauncherPatternMissing,
|
||||
link_record,
|
||||
RepoTree,
|
||||
Script,
|
||||
settings,
|
||||
source_ref,
|
||||
words,
|
||||
)
|
||||
|
||||
EMUSCRIPTS = "functions/EmuScripts"
|
||||
CONFIGS = "configs"
|
||||
BIOS = "${biosPath}"
|
||||
# EmuDeck's settings put the BIOS directory under the Emulation folder.
|
||||
EMULATION_BIOS = "${emulationPath}/bios"
|
||||
STORAGE = "${storagePath}"
|
||||
FLATPAK_DATA = "${HOME}/.var/app/"
|
||||
# The function every EmuScript installs its Flatpak config with.
|
||||
CONFIG_EMU_FP = "functions/configEmuFP.sh"
|
||||
|
||||
# EmuScripts file names that differ from the emulator profile they set up.
|
||||
# The platform and target scrapers both read them here.
|
||||
SCRIPT_EMULATORS = {
|
||||
"pcsx2qt": "pcsx2",
|
||||
"rpcs3legacy": "rpcs3",
|
||||
"cemuproton": "cemu",
|
||||
"rmg": "mupen64plus_next",
|
||||
}
|
||||
# The main RetroArch config script installs no emulator, and emudeck-we's
|
||||
# emuDeckTemplate.ps1 is the skeleton new installers are copied from.
|
||||
NOT_EMULATORS = {"retroarch_maincfg", "template"}
|
||||
# EmuDeck's SteamOS installers are shell scripts, emudeck-we's PowerShell.
|
||||
SCRIPT_SUFFIXES = (".sh", ".ps1")
|
||||
|
||||
# What the emulator does with a directory written into each key.
|
||||
DIRECTORY_KINDS = {
|
||||
"SearchDirectory": "scans_dir",
|
||||
"Bios": "scans_dir",
|
||||
"rompath": "scans_dir",
|
||||
"system_directory": "passes_path",
|
||||
}
|
||||
|
||||
|
||||
def emulator_of_script(file_name: str) -> str | None:
|
||||
"""The emulator an EmuScripts file sets up, None for a helper script."""
|
||||
stem, dot, suffix = file_name.rpartition(".")
|
||||
if not dot or f".{suffix}" not in SCRIPT_SUFFIXES:
|
||||
return None
|
||||
key = re.sub(r"^emuDeck", "", stem, flags=re.IGNORECASE).lower()
|
||||
if not key or key in NOT_EMULATORS:
|
||||
return None
|
||||
return SCRIPT_EMULATORS.get(key, key)
|
||||
|
||||
|
||||
def _script(tree: RepoTree, name: str) -> Script:
|
||||
path = f"{EMUSCRIPTS}/{name}"
|
||||
return Script(path, tree.read(path))
|
||||
|
||||
|
||||
def _emulator(name: str) -> str:
|
||||
emulator = emulator_of_script(name)
|
||||
if emulator is None:
|
||||
raise LauncherPatternMissing(f"{EMUSCRIPTS}/{name}", "emulator script")
|
||||
return emulator
|
||||
|
||||
|
||||
def _is_bios(value: str) -> bool:
|
||||
return any(value == root or value.startswith(root + "/") for root in (BIOS, EMULATION_BIOS))
|
||||
|
||||
|
||||
def with_evidence(tree: RepoTree, script: Script, record: Launcher, config: str) -> Launcher:
|
||||
"""A record citing a shipped config, with the steps that install it.
|
||||
|
||||
configEmuFP rsyncs the repository's configs/<app> over the Flatpak's:
|
||||
the _init call overwrites (keeping a .bak), every other call passes
|
||||
--ignore-existing and leaves the user's file in place.
|
||||
"""
|
||||
fp = Script(CONFIG_EMU_FP, tree.read(CONFIG_EMU_FP))
|
||||
rsync_line, _ = fp.find(r"^\s*rsync .*\$emudeckBackend/configs/", "rsync of the configs")
|
||||
keep_line, _ = fp.find(r'overwrite="--ignore-existing"', "--ignore-existing")
|
||||
calls = {n for n, line in script.code() if re.match(r"\s*configEmuFP\s", line)}
|
||||
if not calls:
|
||||
raise script.missing("configEmuFP call")
|
||||
variable = script.assignment_ending("/" + config)
|
||||
if variable is None:
|
||||
raise script.missing(f"config variable for {config}")
|
||||
record.installs = {
|
||||
"path": script.expand(variable.value, variable.line, set()),
|
||||
"source_ref": source_ref([(script.path, calls), (fp.path, {keep_line, rsync_line})]),
|
||||
}
|
||||
record.kept_if_present = True
|
||||
record.overrides = []
|
||||
return record
|
||||
|
||||
|
||||
def _repo_config(script: Script, path: str) -> str:
|
||||
"""The repository copy of a Flatpak config EmuDeck installs."""
|
||||
if not path.startswith(FLATPAK_DATA):
|
||||
raise script.missing(f"repository copy of {path}")
|
||||
return f"{CONFIGS}/{path[len(FLATPAK_DATA):]}"
|
||||
|
||||
|
||||
def setters(script: Script) -> list[tuple[str, str, str, str, set[int]]]:
|
||||
"""(config file, section, key, value, lines) for each path setter call.
|
||||
|
||||
Reads changeLine "$KEY" "$KEY$VALUE" "$FILE", iniFieldUpdate "$FILE"
|
||||
"Section" "Key" "Value" and RetroArch_setConfigOverride 'key' "value" "$FILE".
|
||||
"""
|
||||
found = []
|
||||
for number, line in script.code():
|
||||
command = words(line)
|
||||
if not command:
|
||||
continue
|
||||
used = {number}
|
||||
args = [script.expand(w.text, number, used) for w in command[1:]]
|
||||
name = command[0].raw
|
||||
if name == "changeLine" and len(args) == 3:
|
||||
key, value, file = args
|
||||
if not value.startswith(key):
|
||||
if BIOS in value:
|
||||
raise script.missing(f"changeLine value starting with its key at line {number}")
|
||||
continue
|
||||
value = value[len(key) :].strip()
|
||||
if len(value) >= 2 and value[0] == value[-1] and value[0] in "'\"":
|
||||
value = value[1:-1]
|
||||
found.append((file, "", key.strip().rstrip("=").strip(), value, used))
|
||||
elif name == "iniFieldUpdate" and len(args) == 4:
|
||||
file, section, key, value = args
|
||||
found.append((file, section, key, value, used))
|
||||
elif name == "RetroArch_setConfigOverride" and len(args) == 3:
|
||||
key, value, file = args
|
||||
found.append((file, "", key, value.strip('"'), used))
|
||||
return found
|
||||
|
||||
|
||||
def setter_records(tree: RepoTree, name: str, option_key: str | None = None) -> list[Launcher]:
|
||||
"""Records for the paths a script's setters write under the BIOS or storage directory.
|
||||
|
||||
A file named under bios/ or storage/ is a fixed name, grouped by config
|
||||
and directory. A bios directory is handed to the emulator, which picks.
|
||||
"""
|
||||
script = _script(tree, name)
|
||||
emulator = _emulator(name)
|
||||
# Each record with the config file it names.
|
||||
records: list[tuple[Launcher, str]] = []
|
||||
groups: dict[tuple[str, str], tuple[list[tuple[str, str]], list[str], set[int]]] = {}
|
||||
for file, section, key, value, lines in setters(script):
|
||||
config = posixpath.basename(file)
|
||||
paths = value.split(";")
|
||||
if not any(_is_bios(p) for p in paths) and not value.startswith(STORAGE + "/"):
|
||||
continue
|
||||
is_file = len(paths) == 1 and re.search(r"\.[A-Za-z0-9]+$", posixpath.basename(value))
|
||||
if is_file:
|
||||
folder = posixpath.dirname(value)
|
||||
keys, names, refs = groups.setdefault((config, folder), ([], [], set()))
|
||||
keys.append((section, key))
|
||||
names.append(posixpath.basename(value))
|
||||
refs |= lines
|
||||
continue
|
||||
if not any(_is_bios(p) for p in paths):
|
||||
continue
|
||||
if key not in DIRECTORY_KINDS:
|
||||
raise script.missing(f"known directory key, got {key}")
|
||||
records.append((
|
||||
Launcher(
|
||||
emulator=emulator,
|
||||
build="libretro" if emulator == "retroarch" else "standalone",
|
||||
kind=DIRECTORY_KINDS[key],
|
||||
names=[],
|
||||
source_ref=source_ref([(script.path, lines)]),
|
||||
search_dir=value,
|
||||
passes_to=describe_keys(config, ((section, key),)),
|
||||
),
|
||||
config,
|
||||
))
|
||||
for (config, folder), (keys, names, refs) in groups.items():
|
||||
records.append((
|
||||
Launcher(
|
||||
emulator=emulator,
|
||||
build="standalone",
|
||||
kind="fixed_name",
|
||||
names=names,
|
||||
source_ref=source_ref([(script.path, refs)]),
|
||||
search_dir=folder,
|
||||
passes_to=describe_keys(config, tuple(keys)),
|
||||
),
|
||||
config,
|
||||
))
|
||||
if not records:
|
||||
raise script.missing(f"setter writing a path under {BIOS}")
|
||||
if option_key:
|
||||
for record, config in records:
|
||||
# passes_to starts with the config name, cut at its first space.
|
||||
_add_option(tree, script, record, config.split(" ", 1)[0], option_key)
|
||||
return [record for record, _config in records]
|
||||
|
||||
|
||||
def _add_option(
|
||||
tree: RepoTree, script: Script, record: Launcher, config: str, option_key: str
|
||||
) -> None:
|
||||
"""depends_on_option from the value the shipped config gives option_key."""
|
||||
file_var = script.assignment_ending("/" + config)
|
||||
if file_var is None:
|
||||
raise script.missing(f"config variable for {config}")
|
||||
path = _repo_config(script, script.expand(file_var.value, file_var.line, set()))
|
||||
option = next((s for s in settings(tree.read(path)) if s.key == option_key), None)
|
||||
if option is None:
|
||||
raise LauncherPatternMissing(path, option_key)
|
||||
record.depends_on_option = f"{option_key} = {option.value} in the shipped {config}"
|
||||
record.source_ref += f", {source_ref([(path, {option.line})])}"
|
||||
|
||||
|
||||
def sed_rewrites(script: Script, function: str) -> list[tuple[str, str, str, set[int]]]:
|
||||
"""(config path, old prefix, new prefix, lines) for sed -i "s|old|new|g" "$file" in a function."""
|
||||
start, _ = script.find(rf"^\s*{re.escape(function)}\s*\(\)\s*\{{", f"function {function}")
|
||||
end = next(
|
||||
(n for n, line in script.code() if n > start and re.match(r"^\}", line)), len(script.lines)
|
||||
)
|
||||
found = []
|
||||
for number, line in script.code():
|
||||
if not start < number < end:
|
||||
continue
|
||||
command = words(line)
|
||||
if len(command) == 4 and command[0].raw == "sed" and command[1].raw == "-i":
|
||||
pattern = re.fullmatch(r"s\|([^|]*)\|([^|]*)\|g", command[2].text)
|
||||
if pattern is None:
|
||||
continue
|
||||
used: set[int] = {number}
|
||||
old, new, file = (
|
||||
script.expand(text, number, used).replace("\\/", "/")
|
||||
for text in (pattern.group(1), pattern.group(2), command[3].text)
|
||||
)
|
||||
found.append((file, old, new, used))
|
||||
return found
|
||||
|
||||
|
||||
def _rewritten(value: str, old: str, new: str) -> str | None:
|
||||
if not value.startswith(old):
|
||||
return None
|
||||
rest = value[len(old) :]
|
||||
return new.rstrip("/") + "/" + rest.lstrip("/")
|
||||
|
||||
|
||||
def ares(tree: RepoTree) -> list[Launcher]:
|
||||
"""settings.bml Firmware keys, their /home/deck/Emulation/bios/ prefix rewritten."""
|
||||
name = "emuDeckares.sh"
|
||||
script = _script(tree, name)
|
||||
rewrites = [
|
||||
r for r in sed_rewrites(script, "ares_setEmulationFolder") if _is_bios(r[2].rstrip("/"))
|
||||
]
|
||||
if not rewrites:
|
||||
raise script.missing("sed rewrite of the BIOS path")
|
||||
file, old, new, script_lines = rewrites[0]
|
||||
path = _repo_config(script, file)
|
||||
records = []
|
||||
system, in_firmware = "", False
|
||||
entries: dict[str, list[tuple[str, str, int]]] = {}
|
||||
for number, line in enumerate(tree.read(path).splitlines(), 1):
|
||||
indent = len(line) - len(line.lstrip(" "))
|
||||
text = line.strip()
|
||||
if indent == 0 and text:
|
||||
system, in_firmware = text, False
|
||||
elif indent == 2:
|
||||
in_firmware = text == "Firmware"
|
||||
elif indent == 4 and in_firmware and ":" in text:
|
||||
key, value = (part.strip() for part in text.split(":", 1))
|
||||
target = _rewritten(value, old, new)
|
||||
if target is not None:
|
||||
entries.setdefault(system, []).append((key, target, number))
|
||||
if not entries:
|
||||
raise LauncherPatternMissing(path, f"Firmware path under {old}")
|
||||
for system, found in entries.items():
|
||||
folder = posixpath.commonpath([posixpath.dirname(t) for _, t, _ in found])
|
||||
records.append(with_evidence(
|
||||
tree, script,
|
||||
Launcher(
|
||||
emulator="ares",
|
||||
build="standalone",
|
||||
kind="fixed_name",
|
||||
names=[posixpath.relpath(t, folder) for _, t, _ in found],
|
||||
source_ref=source_ref(
|
||||
[(path, {n for _, _, n in found}), (script.path, script_lines)]
|
||||
),
|
||||
slot=system,
|
||||
search_dir=folder,
|
||||
passes_to="settings.bml "
|
||||
+ ", ".join(f"{system}/Firmware/{k}" for k, _, _ in found),
|
||||
),
|
||||
posixpath.basename(path),
|
||||
))
|
||||
return records
|
||||
|
||||
|
||||
def melonds(tree: RepoTree) -> list[Launcher]:
|
||||
"""melonDS.ini paths set by changeLine, melonDS.toml paths shipped and rewritten by sed."""
|
||||
name = "emuDeckMelonDS.sh"
|
||||
script = _script(tree, name)
|
||||
records = [
|
||||
with_evidence(tree, script, record, str(record.passes_to or "").split(" ", 1)[0])
|
||||
for record in setter_records(tree, name, option_key="ExternalBIOSEnable")
|
||||
]
|
||||
# A config whose BIOS keys the setters write again keeps their values.
|
||||
set_by_setters = {file for file, _, _, value, _ in setters(script) if _is_bios(value)}
|
||||
for file, old, new, sed_lines in sed_rewrites(script, "melonDS_init"):
|
||||
if file in set_by_setters:
|
||||
continue
|
||||
path = _repo_config(script, file)
|
||||
found = []
|
||||
for setting in settings(tree.read(path)):
|
||||
target = _rewritten(setting.value, old, new)
|
||||
if target is not None and _is_bios(posixpath.dirname(target)):
|
||||
found.append((setting, target))
|
||||
if not found:
|
||||
continue
|
||||
folder = posixpath.commonpath([posixpath.dirname(t) for _, t in found])
|
||||
config = posixpath.basename(path)
|
||||
shipped = {s.key: s for s in settings(tree.read(path))}
|
||||
if "ExternalBIOSEnable" not in shipped or "ConsoleType" not in shipped:
|
||||
raise LauncherPatternMissing(path, "ExternalBIOSEnable and ConsoleType")
|
||||
option, console = shipped["ExternalBIOSEnable"], shipped["ConsoleType"]
|
||||
# The DS keys are read under ExternalBIOSEnable, the DSi keys only
|
||||
# when the console is a DSi (ConsoleType 1).
|
||||
record = Launcher(
|
||||
emulator="melonds",
|
||||
build="standalone",
|
||||
kind="fixed_name",
|
||||
names=[posixpath.relpath(t, folder) for _, t in found],
|
||||
source_ref=source_ref([
|
||||
(path, {option.line, console.line, *(s.line for s, _ in found)}),
|
||||
(script.path, sed_lines),
|
||||
]),
|
||||
search_dir=folder,
|
||||
passes_to=describe_keys(config, tuple((s.section, s.key) for s, _ in found)),
|
||||
depends_on_option=(
|
||||
f"[DS] keys: ExternalBIOSEnable = true, {option.value} in the shipped {config}; "
|
||||
f"[DSi] keys: ConsoleType = 1, {console.value} in the shipped {config}"
|
||||
),
|
||||
)
|
||||
records.append(with_evidence(tree, script, record, config))
|
||||
if len(records) < 2:
|
||||
raise script.missing("melonDS.toml BIOS paths rewritten by sed")
|
||||
return records
|
||||
|
||||
|
||||
# Scripts whose setters write a BIOS path or directory into the emulator config.
|
||||
SETTER_SCRIPTS = (
|
||||
"emuDeckRMG.sh",
|
||||
"emuDeckXemu.sh",
|
||||
"emuDeckDuckStation.sh",
|
||||
"emuDeckPCSX2QT.sh",
|
||||
"emuDeckARMSX2.sh",
|
||||
"emuDeckMAME.sh",
|
||||
"emuDeckRetroArch.sh",
|
||||
)
|
||||
|
||||
# Scripts that link a directory of bios/ to one the emulator reads.
|
||||
LINK_SCRIPTS = (
|
||||
"emuDeckFlycast.sh",
|
||||
"emuDeckAzahar.sh",
|
||||
"emuDeckCitron.sh",
|
||||
"emuDeckEden.sh",
|
||||
"emuDeckSuyu.sh",
|
||||
"emuDeckYuzu.sh",
|
||||
"emuDeckRyujinx.sh",
|
||||
"emuDeckShadPS4.sh",
|
||||
)
|
||||
|
||||
|
||||
def configured(tree: RepoTree) -> list[Launcher]:
|
||||
return [record for name in SETTER_SCRIPTS for record in setter_records(tree, name)]
|
||||
|
||||
|
||||
def links(tree: RepoTree) -> list[Launcher]:
|
||||
records: list[Launcher] = []
|
||||
for name in LINK_SCRIPTS:
|
||||
script = _script(tree, name)
|
||||
found = script.links(BIOS)
|
||||
if not found:
|
||||
raise script.missing(f"ln -s of a path under {BIOS}")
|
||||
records.extend(link_record(_emulator(name), script, link) for link in found)
|
||||
return records
|
||||
|
||||
|
||||
EXTRACTORS: tuple[Callable[[RepoTree], list[Launcher]], ...] = (
|
||||
ares,
|
||||
melonds,
|
||||
configured,
|
||||
links,
|
||||
)
|
||||
|
||||
SOURCE_SCRIPTS = ("emuDeckares.sh", "emuDeckMelonDS.sh", *SETTER_SCRIPTS, *LINK_SCRIPTS)
|
||||
|
||||
|
||||
def extract_launchers(tree: RepoTree) -> list[dict]:
|
||||
"""Every launcher record the extractors find, in extractor order."""
|
||||
return [record.entry() for extractor in EXTRACTORS for record in extractor(tree)]
|
||||
@@ -0,0 +1,684 @@
|
||||
"""EmuELEC's launcher layer, read from its packages at the pinned tag.
|
||||
|
||||
emuelecRunEmu.sh starts every game. A libretro core runs in RetroArch (or
|
||||
retrorun) with /storage/roms/bios as its system directory. A standalone
|
||||
emulator runs from the script the `case ${PLATFORM}` arm names for the core
|
||||
ES passes (`"${EMU}" = "flycastsa"`), and that script links, moves, copies
|
||||
or passes the file. Some packages ship the config the emulator reads
|
||||
(duckstation, hatari, advancemame, mame), others link a BIOS folder at
|
||||
install time (amiberry, timidity). The emulator of each record is the core
|
||||
name the dispatch tests, or the package that installs the link.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import posixpath
|
||||
import re
|
||||
from collections.abc import Callable
|
||||
|
||||
from .configgen import Launcher
|
||||
from scraper.launchers.shell import (
|
||||
describe_keys,
|
||||
fixed_paths,
|
||||
LauncherPatternMissing,
|
||||
Link,
|
||||
link_record,
|
||||
RepoTree,
|
||||
Script,
|
||||
settings,
|
||||
source_ref,
|
||||
words,
|
||||
)
|
||||
from .emuelec_runs import (
|
||||
BIN,
|
||||
BIOS_ROOT,
|
||||
EMULATORS,
|
||||
LIBRETRO,
|
||||
RETROARCH_MK,
|
||||
ROMS_ROOT,
|
||||
RUN_EMU,
|
||||
Runs,
|
||||
SX05RE,
|
||||
UTILS,
|
||||
ADVMAME_INSTALL,
|
||||
evidence,
|
||||
read,
|
||||
under,
|
||||
)
|
||||
|
||||
|
||||
def retroarch(tree: RepoTree, runs: Runs) -> list[Launcher]:
|
||||
"""system_directory, written by sed into the retroarch.cfg the package installs."""
|
||||
mk = read(tree, RETROARCH_MK)
|
||||
sed_line, sed = mk.find(
|
||||
r"s/# system_directory =/system_directory =((?:\\/|[^/])+)/", "system_directory sed"
|
||||
)
|
||||
run_line, _ = runs.script.find(
|
||||
r"RUNTHIS='\$\{RABIN\}.* -L /tmp/cores/\$\{EMU\}\.so --config \$\{RACONF\}",
|
||||
"RetroArch start with --config",
|
||||
)
|
||||
return [
|
||||
Launcher(
|
||||
emulator="retroarch",
|
||||
build="libretro",
|
||||
kind="passes_path",
|
||||
names=[],
|
||||
source_ref=source_ref([(mk.path, {sed_line}), (RUN_EMU, {run_line})]),
|
||||
search_dir=sed.group(1).replace("\\/", "/"),
|
||||
passes_to="retroarch.cfg system_directory (--config)",
|
||||
)
|
||||
]
|
||||
|
||||
|
||||
def retrorun(tree: RepoTree, runs: Runs) -> list[Launcher]:
|
||||
script = runs.script
|
||||
base_line, base = script.find(r'^\s*RUNTHIS="(\w+)"\s*$', "retrorun command")
|
||||
test_line, _ = script.find(
|
||||
rf'if \[\[ "\$\{{EMULATOR\}}" = "{base.group(1)}" \]\]', f"{base.group(1)} test"
|
||||
)
|
||||
run_line, run = script.find(r"RUNTHIS\+=.*\s(-d)\s+(\S+)\s", "retrorun -d", base_line)
|
||||
return [
|
||||
Launcher(
|
||||
emulator=base.group(1),
|
||||
build="libretro",
|
||||
kind="passes_path",
|
||||
names=[],
|
||||
source_ref=source_ref([(RUN_EMU, {test_line, base_line, run_line})]),
|
||||
search_dir=run.group(2),
|
||||
passes_to=f"{base.group(1)} {run.group(1)}",
|
||||
)
|
||||
]
|
||||
|
||||
|
||||
def freej2me(tree: RepoTree, runs: Runs) -> list[Launcher]:
|
||||
"""JAVA_HOME set for the core, and the jar its script copies beside the JDK."""
|
||||
script = runs.script
|
||||
test_line, test = script.find(r'if \[ \$\{EMU\} == "(\w+)_libretro" \]', "core test")
|
||||
call_line, call = script.find(r"^\s*(\S+\.sh)\s*$", "script call", test_line)
|
||||
java_line, java = script.find(r"^\s*(JAVA_HOME)='([^']+)'", "JAVA_HOME", test_line)
|
||||
export_line, _ = script.find(rf"^\s*export {java.group(1)}\s*$", "export", java_line)
|
||||
core = test.group(1)
|
||||
path = f"{LIBRETRO}/{core}/scripts/{call.group(1)}"
|
||||
started = read(tree, path)
|
||||
guard_line, guard = started.find(r'if \[\[ -f "([^"]+)" \]\]; then$', "JDK version test")
|
||||
copy_line, copy = started.find(r"^\s*cp -rf (\S+) (\S+)$", "jar copy", guard_line)
|
||||
source = copy.group(1)
|
||||
return [
|
||||
Launcher(
|
||||
emulator=core,
|
||||
build="libretro",
|
||||
kind="passes_path",
|
||||
names=[],
|
||||
source_ref=source_ref(
|
||||
[(RUN_EMU, {test_line, call_line, java_line, export_line}), (path, {guard_line})]
|
||||
),
|
||||
search_dir=java.group(2),
|
||||
passes_to=f"environment {java.group(1)}",
|
||||
),
|
||||
Launcher(
|
||||
emulator=core,
|
||||
build="libretro",
|
||||
kind="copies",
|
||||
names=[posixpath.basename(source)],
|
||||
source_ref=source_ref(
|
||||
[(RUN_EMU, {test_line, call_line}), (path, {guard_line, copy_line})]
|
||||
),
|
||||
search_dir=posixpath.dirname(source),
|
||||
passes_to=copy.group(2),
|
||||
depends_on_option=f"{guard.group(1)} exists",
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
def pico8(tree: RepoTree, runs: Runs) -> list[Launcher]:
|
||||
"""The folder the user drops in bios/ is moved where the binary runs from."""
|
||||
path = f"{BIN}/pico8.sh"
|
||||
script = read(tree, path)
|
||||
guard_line, guard = script.find(r'if \[\[ -e "([^"]+)" \]\]; then$', "new version test")
|
||||
folder = guard.group(1)
|
||||
copy_line, copy = script.find(
|
||||
rf"^\s*cp -rf {re.escape(folder)}/\* (\S+)$", "copy of the folder", guard_line
|
||||
)
|
||||
target = copy.group(1)
|
||||
remove_line, _ = script.find(rf"^\s*rm -rf {re.escape(folder)}$", "removal", copy_line)
|
||||
mode_line, mode = script.find(
|
||||
rf"^\s*chmod \+x {re.escape(target)}/([^/\s]+)$", "executable bit", remove_line
|
||||
)
|
||||
binary = mode.group(1)
|
||||
starts = {
|
||||
n for n, line in script.code() if re.match(rf"\s*{re.escape(target)}/{binary} -", line)
|
||||
}
|
||||
if not starts:
|
||||
raise script.missing(f"start of {target}/{binary}")
|
||||
name = posixpath.basename(path)
|
||||
return [
|
||||
Launcher(
|
||||
emulator=runs.emulator(name),
|
||||
build="standalone",
|
||||
kind="moves",
|
||||
names=[binary],
|
||||
source_ref=source_ref(
|
||||
[runs.ref(name), (path, {guard_line, copy_line, remove_line, mode_line, *starts})]
|
||||
),
|
||||
case_insensitive=False,
|
||||
search_dir=folder,
|
||||
passes_to=target,
|
||||
fails_when_missing=False,
|
||||
depends_on_option=f"{folder} exists",
|
||||
)
|
||||
]
|
||||
|
||||
|
||||
def _link_guard(script: Script, link: Link) -> set[int]:
|
||||
"""The `[ ! -L <link> ]` test the link waits for, when it is the one just above."""
|
||||
first = max(link.lines)
|
||||
tests = [
|
||||
number
|
||||
for number, line in script.code()
|
||||
if number < first
|
||||
and re.search(r"\[ ! -L ", line)
|
||||
and link.link in script.expand(line, number, set())
|
||||
]
|
||||
return {tests[-1]} if tests and first - tests[-1] <= 4 else set()
|
||||
|
||||
|
||||
# Start scripts whose ln -s commands put a BIOS folder where the emulator reads.
|
||||
LINK_SCRIPTS = (
|
||||
f"{EMULATORS}/flycastsa/scripts/flycast.sh",
|
||||
f"{EMULATORS}/flycast-dojo/scripts/flycastdojo.sh",
|
||||
)
|
||||
|
||||
# Packages whose package.mk links a BIOS folder into the installed tree.
|
||||
LINK_PACKAGES = (
|
||||
f"{EMULATORS}/amiberry",
|
||||
f"{EMULATORS}/amiberry-lite",
|
||||
f"{SX05RE}/tools/sound/timidity",
|
||||
)
|
||||
|
||||
|
||||
def links(tree: RepoTree, runs: Runs) -> list[Launcher]:
|
||||
records = []
|
||||
for path in LINK_SCRIPTS:
|
||||
script = read(tree, path)
|
||||
found = script.links(BIOS_ROOT)
|
||||
if not found:
|
||||
raise script.missing(f"ln -s of a path under {BIOS_ROOT}")
|
||||
name = posixpath.basename(path)
|
||||
for link in found:
|
||||
record = link_record(runs.emulator(name), script, link, guard_lines=_link_guard(script, link))
|
||||
record.source_ref = f"{source_ref([runs.ref(name)])}, {record.source_ref}"
|
||||
records.append(record)
|
||||
for package in LINK_PACKAGES:
|
||||
script = read(tree, f"{package}/package.mk")
|
||||
found = script.links(BIOS_ROOT, fixed={"INSTALL": ""})
|
||||
if not found:
|
||||
raise script.missing(f"ln -s of a path under {BIOS_ROOT}")
|
||||
records.extend(
|
||||
link_record(posixpath.basename(package), script, link) for link in found
|
||||
)
|
||||
return records
|
||||
|
||||
|
||||
def duckstation(tree: RepoTree, runs: Runs) -> list[Launcher]:
|
||||
"""The settings.ini the package ships hands a directory and leaves the paths empty."""
|
||||
package = f"{EMULATORS}/duckstation"
|
||||
path = f"{package}/config/settings.ini"
|
||||
found = {(s.section, s.key): s for s in settings(tree.read(path))}
|
||||
folder_key = ("BIOS", "SearchDirectory")
|
||||
file_keys = (("BIOS", "PathNTSCU"), ("BIOS", "PathNTSCJ"), ("BIOS", "PathPAL"))
|
||||
if folder_key not in found:
|
||||
raise LauncherPatternMissing(path, "[BIOS] SearchDirectory")
|
||||
set_files = [k for k in file_keys if k in found and found[k].value]
|
||||
if set_files:
|
||||
raise LauncherPatternMissing(path, f"empty [BIOS] {set_files[0][1]}")
|
||||
mk = read(tree, f"{package}/package.mk")
|
||||
mk_line, _ = mk.find(r"cp -rf \$\{PKG_DIR\}/config/\* ", "config install")
|
||||
script = read(tree, f"{package}/scripts/duckstation.sh")
|
||||
run_line, _ = script.find(r'-settings "\$\{CONFIG_DIR\}/settings\.ini"', "-settings")
|
||||
name = posixpath.basename(script.path)
|
||||
lines = {found[k].line for k in (folder_key, *file_keys) if k in found}
|
||||
unset = describe_keys("", file_keys).strip()
|
||||
return [evidence(
|
||||
Launcher(
|
||||
emulator=runs.emulator(name),
|
||||
build="standalone",
|
||||
kind="scans_dir",
|
||||
names=[],
|
||||
source_ref=source_ref(
|
||||
[runs.ref(name), (path, lines), (mk.path, {mk_line}), (script.path, {run_line})]
|
||||
),
|
||||
search_dir=found[folder_key].value,
|
||||
passes_to=f"settings.ini [BIOS] SearchDirectory (-settings), {unset} unset",
|
||||
),
|
||||
script,
|
||||
script.expand("${CONFIG_DIR}/settings.ini", run_line, set()),
|
||||
[f"[{s}] {k}" for s, k in (folder_key, *file_keys)],
|
||||
tree=tree,
|
||||
installed=[(mk.path, {mk_line})],
|
||||
)]
|
||||
|
||||
|
||||
YABASANSHIRO_SCRIPTS = (
|
||||
f"{EMULATORS}/yabasanshiroSA_1_11/scripts/yabasanshiro.sh",
|
||||
f"{EMULATORS}/yabasanshiroSA_1_5/scripts/yabasanshiro1_5.sh",
|
||||
)
|
||||
|
||||
|
||||
def yabasanshiro(tree: RepoTree, runs: Runs) -> list[Launcher]:
|
||||
"""The BIOS flag, set when the HLE option is off and the file exists."""
|
||||
records = []
|
||||
for path in YABASANSHIRO_SCRIPTS:
|
||||
script = read(tree, path)
|
||||
option_line, option = script.find(r"^\s*(\w+)=\$\(get_ee_setting (\w+) ", "HLE option")
|
||||
test_line, test = script.find(
|
||||
rf'if \[ "\$\{{{option.group(1)}\}}" != (\w+) \]', "HLE option test", option_line
|
||||
)
|
||||
exists_line, exists = script.find(r'if \[ -e "([^"]+)" \]', "BIOS test", test_line)
|
||||
bios = exists.group(1)
|
||||
flag_line, flag = script.find(
|
||||
rf'^\s*(\w+)="(-\w) {re.escape(bios)}"$', "BIOS flag", exists_line
|
||||
)
|
||||
run_line, run = script.find(
|
||||
rf"\{{\s*(\S+) .*\$\{{{flag.group(1)}\}}", "start with the flag", flag_line
|
||||
)
|
||||
name = posixpath.basename(path)
|
||||
records.append(
|
||||
Launcher(
|
||||
emulator=runs.emulator(name),
|
||||
build="standalone",
|
||||
kind="fixed_name",
|
||||
names=[posixpath.basename(bios)],
|
||||
source_ref=source_ref(
|
||||
[
|
||||
runs.ref(name),
|
||||
(path, {option_line, test_line, exists_line, flag_line, run_line}),
|
||||
]
|
||||
),
|
||||
case_insensitive=False,
|
||||
search_dir=posixpath.dirname(bios),
|
||||
passes_to=f"{run.group(1)} {flag.group(2)}",
|
||||
fails_when_missing=False,
|
||||
depends_on_option=f"{option.group(2)} != {test.group(1)}",
|
||||
)
|
||||
)
|
||||
return records
|
||||
|
||||
|
||||
def jzintv(tree: RepoTree, runs: Runs) -> list[Launcher]:
|
||||
path = f"{EMULATORS}/jzintv/scripts/jzintv.sh"
|
||||
script = read(tree, path)
|
||||
run_line, run = script.find(r"^\s*exec (\S+) .*\s(-p)\s+(\S+)\s", "start with -p")
|
||||
name = posixpath.basename(path)
|
||||
return [
|
||||
Launcher(
|
||||
emulator=runs.emulator(name),
|
||||
build="standalone",
|
||||
kind="passes_path",
|
||||
names=[],
|
||||
source_ref=source_ref([runs.ref(name), (path, {run_line})]),
|
||||
search_dir=run.group(3).rstrip("/"),
|
||||
passes_to=f"{run.group(1)} {run.group(2)}",
|
||||
)
|
||||
]
|
||||
|
||||
|
||||
def mupen64plus(tree: RepoTree, runs: Runs) -> list[Launcher]:
|
||||
"""The 64DD IPL names, tried in order, passed only beside a .ndd disk."""
|
||||
path = f"{EMULATORS}/mupen64plussa/mupen64plussa-core/m64p.sh"
|
||||
script = read(tree, path)
|
||||
fallbacks = [
|
||||
(number, found)
|
||||
for number, line in script.code()
|
||||
if (found := re.search(r'\[ ! -f "\$\{(\w+)\}" \] && \1="([^"]+)"', line))
|
||||
]
|
||||
if not fallbacks:
|
||||
raise script.missing("fallback name test")
|
||||
var = fallbacks[0][1].group(1)
|
||||
first = script.value(var, fallbacks[0][0])
|
||||
if first is None:
|
||||
raise script.missing(f"assignment of {var}")
|
||||
used = {first.line, *(n for n, _ in fallbacks)}
|
||||
paths = [
|
||||
script.expand(v, n, used)
|
||||
for n, v in [(first.line, first.value), *((n, f.group(2)) for n, f in fallbacks)]
|
||||
]
|
||||
folders = {posixpath.dirname(p) for p in paths}
|
||||
if len(folders) != 1:
|
||||
raise script.missing(f"one folder for the {var} names")
|
||||
test_line, test = script.find(
|
||||
rf'if \[ -f "([^"]+)" \] && \[ -f "\$\{{{var}\}}" \]', "disk and IPL test"
|
||||
)
|
||||
passes = [
|
||||
(number, found)
|
||||
for number, line in script.code()
|
||||
if (found := re.search(rf'^\s*(\S+) .*(--[\w-]+) "\$\{{{var}\}}"', line))
|
||||
]
|
||||
if not passes:
|
||||
raise script.missing(f"flag that hands {var}")
|
||||
flags = sorted({f"{f.group(1)} {f.group(2)}" for _, f in passes})
|
||||
name = posixpath.basename(path)
|
||||
return [
|
||||
Launcher(
|
||||
emulator=runs.emulator(name),
|
||||
build="standalone",
|
||||
kind="names_searched",
|
||||
names=[posixpath.basename(p) for p in paths],
|
||||
source_ref=source_ref(
|
||||
[runs.ref(name), (path, used | {test_line} | {n for n, _ in passes})]
|
||||
),
|
||||
case_insensitive=False,
|
||||
search_dir=folders.pop(),
|
||||
passes_to=", ".join(flags),
|
||||
fails_when_missing=False,
|
||||
depends_on_option=f'-f "{test.group(1)}"',
|
||||
)
|
||||
]
|
||||
|
||||
|
||||
def hatari(tree: RepoTree, runs: Runs) -> list[Launcher]:
|
||||
package = f"{EMULATORS}/hatarisa"
|
||||
script = read(tree, f"{package}/scripts/hatari.start")
|
||||
copy_line, copy = script.find(r'^\s*cp \S+/([\w.-]+\.cfg) "\$(\w+)"', "default config copy")
|
||||
run_lines = {
|
||||
n
|
||||
for n, line in script.code()
|
||||
if n > copy_line and f'--configfile "${copy.group(2)}"' in line
|
||||
}
|
||||
if not run_lines:
|
||||
raise script.missing(f"--configfile ${copy.group(2)}")
|
||||
path = f"{package}/config/conf/{copy.group(1)}"
|
||||
found = settings(tree.read(path))
|
||||
keys = [
|
||||
(s.section, s.key)
|
||||
for s in found
|
||||
if under(s.value) and "." in posixpath.basename(s.value)
|
||||
]
|
||||
if not keys:
|
||||
raise LauncherPatternMissing(path, f"key naming a file under {BIOS_ROOT}")
|
||||
value, lines = fixed_paths(found, keys, path)
|
||||
mk = read(tree, f"{package}/package.mk")
|
||||
mk_line, _ = mk.find(r"cp -R \$\{PKG_DIR\}/config/\* ", "config install")
|
||||
name = posixpath.basename(script.path)
|
||||
return [evidence(
|
||||
Launcher(
|
||||
emulator=runs.emulator(name),
|
||||
build="standalone",
|
||||
kind="fixed_name",
|
||||
names=list(value.names),
|
||||
source_ref=source_ref(
|
||||
[runs.ref(name), (path, lines), (mk.path, {mk_line}),
|
||||
(script.path, {copy_line, *run_lines})]
|
||||
),
|
||||
search_dir=value.search_dir,
|
||||
passes_to=f"{describe_keys(copy.group(1), value.keys)} (--configfile)",
|
||||
),
|
||||
script,
|
||||
script.expand("${" + copy.group(2) + "}", copy_line, set()),
|
||||
[f"[{s}] {k}" if s else k for s, k in value.keys],
|
||||
source_name=copy.group(1),
|
||||
)]
|
||||
|
||||
|
||||
_ADVMAME_SYSTEM = re.compile(r'^\s*if \[\[ "\$\{1\}" = "([\w-]+)" \]\]; then$')
|
||||
_ADVMAME_SED = re.compile(r'^\s*sed -i "s\|([^|]+)\|([^|]+)\|g" \$\{CONFIG_DIR\}/advmame\.rc$')
|
||||
|
||||
|
||||
def advancemame(tree: RepoTree, runs: Runs) -> list[Launcher]:
|
||||
"""Folder keys of the advmame.rc package.mk installs, one per device branch.
|
||||
|
||||
A key under the roms root is one too: dir_rom is /storage/roms/mame. The
|
||||
start script rewrites the config for the system it is launched for
|
||||
(advmame.sh:26-30): /roms/mame becomes /roms/arcade for arcade, so that
|
||||
system reads its own record.
|
||||
"""
|
||||
package = f"{EMULATORS}/advancemame"
|
||||
mk = read(tree, f"{package}/package.mk")
|
||||
installs = [
|
||||
(number, found.group(1))
|
||||
for number, line in mk.code()
|
||||
if (found := ADVMAME_INSTALL.search(line))
|
||||
]
|
||||
if not installs:
|
||||
raise mk.missing("advmame.rc install")
|
||||
by_value: dict[tuple[tuple[str, str], ...], list[tuple[str, set[int], int]]] = {}
|
||||
for mk_line, file in installs:
|
||||
path = f"{package}/config/{file}"
|
||||
keys = [s for s in settings(tree.read(path), separator=" ") if under(s.value, ROMS_ROOT)]
|
||||
if not any(under(s.value) for s in keys):
|
||||
raise LauncherPatternMissing(path, f"key naming a folder under {BIOS_ROOT}")
|
||||
value = tuple((s.key, s.value) for s in keys)
|
||||
by_value.setdefault(value, []).append((path, {s.line for s in keys}, mk_line))
|
||||
if len(by_value) != 1:
|
||||
raise mk.missing("one set of BIOS folders for every device")
|
||||
((value, configs),) = by_value.items()
|
||||
script = read(tree, f"{package}/bin/advmame.sh")
|
||||
run_line, _ = script.find(r"^\s*(?:\w+=\S+ )*advmame ", "advmame start")
|
||||
test_line, test = script.find(_ADVMAME_SYSTEM.pattern, "system test", end=run_line)
|
||||
sed_line, sed = script.find(_ADVMAME_SED.pattern, "system rewrite", test_line + 1, test_line + 1)
|
||||
name = posixpath.basename(script.path)
|
||||
|
||||
def refs(*lines: int) -> str:
|
||||
return source_ref([
|
||||
runs.ref(name),
|
||||
*((path, lines) for path, lines, _ in configs),
|
||||
(mk.path, {mk_line for _, _, mk_line in configs}),
|
||||
(script.path, {run_line, *lines}),
|
||||
])
|
||||
|
||||
target = script.expand("${CONFIG_DIR}/advmame.rc", run_line, set())
|
||||
|
||||
def proved(record: Launcher, key: str) -> Launcher:
|
||||
return evidence(record, script, target, [key], rewrites={sed_line}, tree=tree,
|
||||
installed=[(mk.path, {mk_line for _, _, mk_line in configs})])
|
||||
|
||||
records = []
|
||||
for key, folder in value:
|
||||
rewritten = folder.replace(sed.group(1), sed.group(2))
|
||||
if rewritten != folder:
|
||||
# Every system but the one the script rewrites the key for, and
|
||||
# that system with the rewritten folder.
|
||||
records.append(proved(Launcher(
|
||||
emulator=runs.emulator(name), build="standalone", kind="passes_path", names=[],
|
||||
source_ref=refs(test_line, sed_line), search_dir=folder,
|
||||
passes_to=f"advmame.rc {key}",
|
||||
depends_on_option=f"system != {test.group(1)}",
|
||||
), key))
|
||||
records.append(proved(Launcher(
|
||||
emulator=runs.emulator(name), build="standalone", kind="passes_path", names=[],
|
||||
source_ref=refs(test_line, sed_line), search_dir=rewritten,
|
||||
passes_to=f"advmame.rc {key}", systems=[test.group(1)],
|
||||
), key))
|
||||
continue
|
||||
records.append(proved(Launcher(
|
||||
emulator=runs.emulator(name), build="standalone", kind="passes_path", names=[],
|
||||
source_ref=refs(), search_dir=folder, passes_to=f"advmame.rc {key}",
|
||||
), key))
|
||||
return records
|
||||
|
||||
|
||||
def mame(tree: RepoTree, runs: Runs) -> list[Launcher]:
|
||||
"""The files mame.sh copies into bios/mame, and the folders mame.ini hands the core."""
|
||||
package = f"{LIBRETRO}/mame"
|
||||
script = read(tree, f"{package}/scripts/mame.sh")
|
||||
name = posixpath.basename(script.path)
|
||||
emulator = runs.emulator(name)
|
||||
records = []
|
||||
guard: tuple[int, str] | None = None
|
||||
for number, line in script.code():
|
||||
if found := re.search(r'if \[ ! -f "([^"]+)" \]', line):
|
||||
guard = (number, found.group(1))
|
||||
continue
|
||||
copy = re.match(r'\s*cp -rf "([^"]+)/"(\S+) "([^"]+)"\s*$', line)
|
||||
if copy is None:
|
||||
continue
|
||||
if guard is None:
|
||||
raise script.missing(f"test before the copy at line {number}")
|
||||
if not under(copy.group(3)):
|
||||
continue
|
||||
records.append(
|
||||
Launcher(
|
||||
emulator=emulator,
|
||||
build="libretro",
|
||||
kind="copies",
|
||||
names=[copy.group(2)],
|
||||
source_ref=source_ref([runs.ref(name), (script.path, {guard[0], number})]),
|
||||
search_dir=copy.group(1),
|
||||
passes_to=copy.group(3),
|
||||
fails_when_missing=False,
|
||||
depends_on_option=f"{guard[1]} absent",
|
||||
)
|
||||
)
|
||||
if not records:
|
||||
raise script.missing(f"copy into {BIOS_ROOT}")
|
||||
# mame.ini hands the core no folder: MAME.opt turns on
|
||||
# mame_mame_paths_enable, so the core passes no path option
|
||||
# (libretro mame src/osd/libretro/libretro-internal/retro_init.cpp:554-555),
|
||||
# and the ini MAME would read sits under a working directory no launcher
|
||||
# sets (src/emu/emuopts.cpp:49). Only the copies are the launcher's.
|
||||
return records
|
||||
|
||||
|
||||
def scummvm(tree: RepoTree, runs: Runs) -> list[Launcher]:
|
||||
"""--extrapath for the standalone build, and the scummvm.ini copied for the core."""
|
||||
path = f"{EMULATORS}/scummvmsa/bin/scummvm.start"
|
||||
script = read(tree, path)
|
||||
name = posixpath.basename(path)
|
||||
test_line, test = script.find(r'^\s*if \[ -d "([^"]+)" \]; then\s*$', "extra folder test")
|
||||
set_line, set_ = script.find(r'^\s*(\w+)="(--[\w-]+)=([^"]+)"', "extra path", test_line)
|
||||
run_line, run = script.find(rf"^\s*(\S+) .*\${set_.group(1)}\b", "start with it", set_line)
|
||||
core_line, core = script.find(r"-L /tmp/cores/(\w+)_libretro\.so", "libretro start")
|
||||
arm_line, arm = script.find(r'^\s*"(\w+)"\)', "setup arm", core_line)
|
||||
copy_line, copy = script.find(r"^\s*cp (\S+) (\S+)$", "copy into the BIOS folder", arm_line)
|
||||
launched = sorted({
|
||||
m.group(1) for _, line in runs.script.code()
|
||||
if (m := re.search(rf"\b{re.escape(name)} (\w+)", line))
|
||||
})
|
||||
if not launched:
|
||||
raise runs.script.missing(f"start of {name} with an action")
|
||||
action = f"{name} {arm.group(1)}"
|
||||
if arm.group(1) not in launched:
|
||||
# The copy runs from the setup action, never from a launch.
|
||||
action += f", an action no launch runs ({RUN_EMU.rsplit('/', 1)[-1]} passes {', '.join(launched)})"
|
||||
used = {copy_line}
|
||||
source = script.expand(copy.group(1), copy_line, used)
|
||||
target = script.expand(copy.group(2), copy_line, used)
|
||||
if not under(target):
|
||||
raise script.missing(f"copy into {BIOS_ROOT}")
|
||||
return [
|
||||
Launcher(
|
||||
emulator=runs.emulator(name),
|
||||
build="standalone",
|
||||
kind="passes_path",
|
||||
names=[],
|
||||
source_ref=source_ref([runs.ref(name), (path, {test_line, set_line, run_line})]),
|
||||
search_dir=set_.group(3),
|
||||
passes_to=f"{run.group(1)} {set_.group(2)}",
|
||||
depends_on_option=f"{test.group(1)} exists",
|
||||
),
|
||||
Launcher(
|
||||
emulator=core.group(1),
|
||||
build="libretro",
|
||||
kind="copies",
|
||||
names=[posixpath.basename(source)],
|
||||
source_ref=source_ref([(path, {core_line, arm_line} | used)]),
|
||||
search_dir=posixpath.dirname(source),
|
||||
passes_to=target,
|
||||
fails_when_missing=False,
|
||||
depends_on_option=action,
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
def dolphin(tree: RepoTree, runs: Runs) -> list[Launcher]:
|
||||
path = f"{EMULATORS}/dolphinSA/scripts/dolphin.sh"
|
||||
script = read(tree, path)
|
||||
run_line, run = script.find(r"\b(XDG_DATA_HOME)=(\S+) .*\bdolphin-emu", "XDG_DATA_HOME start")
|
||||
name = posixpath.basename(path)
|
||||
return [
|
||||
Launcher(
|
||||
emulator=runs.emulator(name),
|
||||
build="standalone",
|
||||
kind="passes_path",
|
||||
names=[],
|
||||
source_ref=source_ref([runs.ref(name), (path, {run_line})]),
|
||||
search_dir=run.group(2),
|
||||
passes_to=f"environment {run.group(1)}",
|
||||
)
|
||||
]
|
||||
|
||||
|
||||
def midi(tree: RepoTree, runs: Runs) -> list[Launcher]:
|
||||
"""The MIDI synth set_midi_source starts for the ra_midi_output setting."""
|
||||
script = runs.script
|
||||
setting_line, setting = script.find(
|
||||
r'^\s*(\w+)=\$\(get_ee_setting "(\w*midi\w*)" ', "MIDI setting"
|
||||
)
|
||||
call_line, _ = script.find(
|
||||
rf'set_midi_source "\$\{{{setting.group(1)}\}}"', "set_midi_source call", setting_line
|
||||
)
|
||||
utils = read(tree, UTILS)
|
||||
head_line, _ = utils.find(r"^\s*function set_midi_source\(\)", "set_midi_source")
|
||||
end_line, _ = utils.find(r"^\s*esac\b", "end of the source case", head_line)
|
||||
records = []
|
||||
arm: tuple[int, str] | None = None
|
||||
for number, line in utils.code():
|
||||
if number <= head_line or number >= end_line:
|
||||
continue
|
||||
if found := re.match(r"\s*([\w-]+)\)\s*$", line):
|
||||
arm = (number, found.group(1))
|
||||
continue
|
||||
command = [w.text for w in words(line)]
|
||||
paths = [
|
||||
(command[i - 1], value)
|
||||
for i, value in enumerate(command)
|
||||
if i and command[i - 1].startswith("-") and re.search(r"(^|/)bios(/|$)", value)
|
||||
]
|
||||
if not paths or arm is None:
|
||||
continue
|
||||
((flag, value),) = paths
|
||||
is_file = "." in posixpath.basename(value) and under(value)
|
||||
records.append(
|
||||
Launcher(
|
||||
emulator=command[0],
|
||||
build="standalone",
|
||||
kind="fixed_name" if is_file else "passes_path",
|
||||
names=[posixpath.relpath(value, BIOS_ROOT)] if is_file else [],
|
||||
source_ref=source_ref(
|
||||
[(RUN_EMU, {setting_line, call_line}), (UTILS, {head_line, arm[0], number})]
|
||||
),
|
||||
slot=arm[1],
|
||||
case_insensitive=False if is_file else None,
|
||||
search_dir=BIOS_ROOT if is_file else value.rstrip("/"),
|
||||
passes_to=f"{command[0]} {flag}",
|
||||
fails_when_missing=False,
|
||||
depends_on_option=f"{setting.group(2)} = {arm[1]}",
|
||||
)
|
||||
)
|
||||
if not records:
|
||||
raise utils.missing("MIDI synth started with a BIOS path")
|
||||
return records
|
||||
|
||||
|
||||
EXTRACTORS: tuple[Callable[[RepoTree, Runs], list[Launcher]], ...] = (
|
||||
retroarch,
|
||||
retrorun,
|
||||
freej2me,
|
||||
mame,
|
||||
pico8,
|
||||
links,
|
||||
duckstation,
|
||||
yabasanshiro,
|
||||
jzintv,
|
||||
mupen64plus,
|
||||
hatari,
|
||||
advancemame,
|
||||
scummvm,
|
||||
dolphin,
|
||||
midi,
|
||||
)
|
||||
|
||||
|
||||
def extract_launchers(tree: RepoTree) -> list[dict]:
|
||||
"""Every launcher record the extractors find, in extractor order."""
|
||||
runs = Runs(tree)
|
||||
return [record.entry() for extractor in EXTRACTORS for record in extractor(tree, runs)]
|
||||
@@ -0,0 +1,151 @@
|
||||
"""Which script emuelecRunEmu.sh starts for each core, and the lines that put a config in place."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import posixpath
|
||||
import re
|
||||
from collections.abc import Iterable
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
from .configgen import Launcher
|
||||
from .shell import (
|
||||
RepoTree,
|
||||
Script,
|
||||
apply_evidence,
|
||||
config_placement,
|
||||
first_boot_placement,
|
||||
words,
|
||||
)
|
||||
from model.launcherrecords import join_emulators
|
||||
|
||||
|
||||
SX05RE = "packages/sx05re"
|
||||
BIN = f"{SX05RE}/emuelec/bin"
|
||||
RUN_EMU = f"{BIN}/emuelecRunEmu.sh"
|
||||
UTILS = f"{BIN}/emuelec-utils"
|
||||
EMULATORS = f"{SX05RE}/emulators"
|
||||
LIBRETRO = f"{SX05RE}/libretro"
|
||||
RETROARCH_MK = f"{SX05RE}/libretro_base/retroarch/package.mk"
|
||||
BIOS_ROOT = "/storage/roms/bios"
|
||||
EMUELEC_MK = f"{SX05RE}/emuelec/package.mk"
|
||||
# The copy of every package's /usr/config into /storage/.config at each boot,
|
||||
# an existing file kept (cp -i answered by false).
|
||||
USERCONFIG = "packages/sysutils/systemd/scripts/userconfig-setup"
|
||||
# The roms root that holds it (packages/sx05re/libretro_base/retroarch/package.mk:112,117).
|
||||
ROMS_ROOT = "/storage/roms"
|
||||
|
||||
_EMU_TEST = re.compile(r'\$\{?EMU\}?"?\s*==?\s*"([^"]+)"')
|
||||
_ARM = re.compile(r'^\s*((?:"[^"]+"\|?)+)\)\s*$')
|
||||
_RUNTHIS = re.compile(r"""^\s*RUNTHIS\+?=(['"])(.*)\1\s*$""")
|
||||
_SCRIPT = re.compile(r"[\w./-]+\.(?:sh|start)$")
|
||||
ADVMAME_INSTALL = re.compile(r"cp -r \$\{PKG_DIR\}/config/(advmame\.rc\w*) \S+/advmame\.rc$")
|
||||
|
||||
|
||||
@dataclass
|
||||
class Dispatch:
|
||||
"""The cores emuelecRunEmu.sh hands to one script, and the lines that do it."""
|
||||
|
||||
emulators: list[str] = field(default_factory=list)
|
||||
lines: set[int] = field(default_factory=set)
|
||||
|
||||
|
||||
class Runs:
|
||||
"""emuelecRunEmu.sh, read once: which core starts which script."""
|
||||
|
||||
def __init__(self, tree: RepoTree) -> None:
|
||||
self.script = Script(RUN_EMU, tree.read(RUN_EMU))
|
||||
self.by_script: dict[str, Dispatch] = {}
|
||||
emu: tuple[str, int] | None = None
|
||||
arm: tuple[list[str], int] | None = None
|
||||
for number, line in self.script.code():
|
||||
if found := _ARM.match(line):
|
||||
arm = ([p.strip('"') for p in found.group(1).split("|") if p], number)
|
||||
emu = None
|
||||
continue
|
||||
if re.match(r"\s*(;;|esac\b)", line):
|
||||
arm, emu = None, None
|
||||
continue
|
||||
if found := _EMU_TEST.search(line):
|
||||
emu = (found.group(1).removesuffix("_libretro"), number)
|
||||
continue
|
||||
if re.match(r"\s*fi\b", line):
|
||||
emu = None
|
||||
continue
|
||||
run = _RUNTHIS.match(line)
|
||||
command = words(run.group(2) if run else line)
|
||||
name = next(
|
||||
(posixpath.basename(w.text) for w in command if _SCRIPT.fullmatch(w.text)), None
|
||||
)
|
||||
if name is None:
|
||||
continue
|
||||
if emu is not None:
|
||||
names, at = [emu[0]], emu[1]
|
||||
elif arm is not None:
|
||||
names, at = arm
|
||||
else:
|
||||
continue
|
||||
entry = self.by_script.setdefault(name, Dispatch())
|
||||
entry.emulators.extend(n for n in names if n not in entry.emulators)
|
||||
entry.lines |= {at, number}
|
||||
if not self.by_script:
|
||||
raise self.script.missing("script started for a core")
|
||||
|
||||
def of(self, name: str) -> Dispatch:
|
||||
if name not in self.by_script:
|
||||
raise self.script.missing(f"start of {name}")
|
||||
return self.by_script[name]
|
||||
|
||||
def emulator(self, name: str) -> str:
|
||||
return join_emulators(self.of(name).emulators)
|
||||
|
||||
def ref(self, name: str) -> tuple[str, set[int]]:
|
||||
return (RUN_EMU, set(self.of(name).lines))
|
||||
|
||||
|
||||
def _storage_path(tree: RepoTree, target: str) -> str:
|
||||
"""target with the /emuelec link resolved to the folder it points at.
|
||||
|
||||
The emuelec package links /emuelec to /storage/.config/emuelec, where
|
||||
the first-boot copy of /usr/config lands.
|
||||
"""
|
||||
mk = read(tree, EMUELEC_MK)
|
||||
_line, link = mk.find(r"ln -sf (/storage/\S+) \$\{INSTALL\}(/emuelec)$", "/emuelec link")
|
||||
if target == link.group(2) or target.startswith(link.group(2) + "/"):
|
||||
return link.group(1) + target[len(link.group(2)):]
|
||||
return target
|
||||
|
||||
|
||||
def evidence(
|
||||
record: Launcher,
|
||||
script: Script,
|
||||
target: str,
|
||||
keys: list[str],
|
||||
source_name: str = "",
|
||||
rewrites: Iterable[int] = (),
|
||||
tree: RepoTree | None = None,
|
||||
installed: Iterable[tuple[str, Iterable[int]]] = (),
|
||||
) -> Launcher:
|
||||
"""A config record with the lines that put its file in place: the
|
||||
first-boot copy of /usr/config when ``tree`` is given, then the start
|
||||
script's own. ``installed`` are the package.mk lines putting the file
|
||||
in /usr/config.
|
||||
|
||||
``rewrites`` are lines the extractor read as rewriting the record's
|
||||
values without naming their keys (advmame.sh's sed of /roms/mame).
|
||||
"""
|
||||
placements = []
|
||||
if tree is not None:
|
||||
placements.append(first_boot_placement(read(tree, USERCONFIG), _storage_path(tree, target)))
|
||||
placement = config_placement(script, target, keys, source_name=source_name,
|
||||
required=not placements or not placements[0].install)
|
||||
placement.overrides |= set(rewrites)
|
||||
placements.append(placement)
|
||||
return apply_evidence(record, placements, installed)
|
||||
|
||||
|
||||
def read(tree: RepoTree, path: str) -> Script:
|
||||
return Script(path, tree.read(path))
|
||||
|
||||
|
||||
def under(path: str, root: str = BIOS_ROOT) -> bool:
|
||||
return path.rstrip("/") == root or path.startswith(root + "/")
|
||||
@@ -0,0 +1,579 @@
|
||||
"""KNULLI's launcher layer, read from its configgen and its board scripts.
|
||||
|
||||
KNULLI is built on Batocera and keeps configgen under its own package
|
||||
(package/system/knulli-configgen). Where a generator is still Batocera's
|
||||
code (DuckStation, xemu, mupen64plus, x16emu, the flycast environment, the
|
||||
hatari and melonDS forms batocera_searches and batocera_config_writes accept),
|
||||
Batocera's extractor reads it. The others are older or KNULLI's own: the lexaloffle generator logs
|
||||
and returns instead of raising, libretroOptions is one function of
|
||||
`if (system.config['core'] == ...)` blocks, and the PICO-8 binary is
|
||||
installed by board/fsoverlay/usr/bin/knulli-install-pico8.
|
||||
|
||||
The remaining generators name a /userdata/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 the context that consumes it, and
|
||||
GENERIC_SITES says, per generator, whether the path is a file or a directory.
|
||||
A generator in that table that no longer names a BIOS path raises
|
||||
LauncherShapeError, as every other extractor does.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import ast
|
||||
import posixpath
|
||||
import re
|
||||
from collections.abc import Callable
|
||||
from dataclasses import dataclass
|
||||
|
||||
import yaml
|
||||
|
||||
from model.launcherrecords import emulator_names, join_emulators
|
||||
from .batocera import (
|
||||
PATH_PATCHES,
|
||||
Extraction,
|
||||
extraction,
|
||||
config_directories,
|
||||
environment_directories,
|
||||
patched_paths,
|
||||
working_directories,
|
||||
)
|
||||
from .batocera_config_writes import render, system_branches, melonds, mupen64plus, x16emu, xemu
|
||||
from .batocera_searches import duckstation, duckstation_legacy, hatari
|
||||
from .batocera_configgen import Configgen, _path_value
|
||||
from .configgen import Launcher, LauncherShapeError, Source, _assigned_name
|
||||
from scraper.launchers.shell 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"
|
||||
LIBRETRO_OPTIONS = f"{GENERATORS}/libretro/libretroOptions.py"
|
||||
PICO8_INSTALLER = "board/fsoverlay/usr/bin/knulli-install-pico8"
|
||||
ES_FEATURES = "package/emulationstation/knulli-es-system/es_features.yml"
|
||||
|
||||
# The generators of Batocera's config_directories that KNULLI keeps in the
|
||||
# same shape: openMSX's filepool lines and amiberry's rom_path.
|
||||
CONFIG_DIRECTORY_GENERATORS = ("openmsx.openmsxGenerator", "amiberry.amiberryGenerator")
|
||||
|
||||
|
||||
def knulli_config_directories(cg: Configgen) -> list[Launcher]:
|
||||
return config_directories(cg, CONFIG_DIRECTORY_GENERATORS)
|
||||
|
||||
|
||||
# Batocera's extractors that read KNULLI's generators unchanged.
|
||||
SHARED = (
|
||||
duckstation, duckstation_legacy, hatari, xemu, melonds, mupen64plus, x16emu,
|
||||
environment_directories, working_directories, knulli_config_directories,
|
||||
)
|
||||
|
||||
|
||||
def _lines(node: ast.AST) -> tuple[int, int]:
|
||||
"""First and last line of a node."""
|
||||
first: int = getattr(node, "lineno", 0)
|
||||
return first, getattr(node, "end_lineno", None) or first
|
||||
|
||||
|
||||
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)
|
||||
|
||||
|
||||
def _error_guard(
|
||||
src: Source, scope: ast.FunctionDef, test: Callable[[ast.expr], bool], what: str
|
||||
) -> tuple[ast.If, ast.JoinedStr]:
|
||||
"""`if <test>: eslog.error(f"..."); return -1` and its message."""
|
||||
found = []
|
||||
for node in ast.walk(scope):
|
||||
if not (isinstance(node, ast.If) and test(node.test) and len(node.body) == 2):
|
||||
continue
|
||||
logged, returned = node.body
|
||||
if (
|
||||
isinstance(logged, ast.Expr)
|
||||
and isinstance(logged.value, ast.Call)
|
||||
and ast.unparse(logged.value.func) == "eslog.error"
|
||||
and logged.value.args
|
||||
and isinstance(logged.value.args[0], ast.JoinedStr)
|
||||
and isinstance(returned, ast.Return)
|
||||
):
|
||||
found.append((node, logged.value.args[0]))
|
||||
if len(found) != 1:
|
||||
src.fail(f"expected one `if {what}: eslog.error(...); return`, found {len(found)}")
|
||||
return found[0]
|
||||
|
||||
|
||||
def lexaloffle(cg: Configgen) -> list[Launcher]:
|
||||
"""Per system, BIN_PATH under /userdata/bios run as the emulator binary."""
|
||||
module = "lexaloffle.lexaloffleGenerator"
|
||||
src = cg.generator(module)
|
||||
generate = src.function("generate")
|
||||
defined = {
|
||||
name: node for node in src.tree.body if (name := _assigned_name(node)) is not None
|
||||
}
|
||||
constants = dict(cg.paths)
|
||||
for name, node in defined.items():
|
||||
value = _path_value(_bound(node), constants)
|
||||
if value is not None:
|
||||
constants[name] = value
|
||||
missing, missing_message = _error_guard(
|
||||
src, generate,
|
||||
lambda t: isinstance(t, ast.UnaryOp) and isinstance(t.op, ast.Not)
|
||||
and isinstance(t.operand, ast.Call) and ast.unparse(t.operand.func).endswith(".exists"),
|
||||
"not <binary>.exists()",
|
||||
)
|
||||
tested = missing.test
|
||||
if not (isinstance(tested, ast.UnaryOp) and isinstance(tested.operand, ast.Call)):
|
||||
src.fail("not <binary>.exists() tests no call")
|
||||
binary = ast.unparse(tested.operand.func).removesuffix(".exists")
|
||||
access, access_message = _error_guard(
|
||||
src, generate,
|
||||
lambda t: isinstance(t, ast.UnaryOp) and isinstance(t.op, ast.Not)
|
||||
and ast.unparse(t.operand).startswith(f"os.access({binary}"),
|
||||
f"not os.access({binary}, ...)",
|
||||
)
|
||||
commands = [
|
||||
node for node in ast.walk(generate)
|
||||
if isinstance(node, ast.Assign) and isinstance(node.value, ast.List)
|
||||
and node.value.elts and ast.unparse(node.value.elts[0]) == binary
|
||||
]
|
||||
if len(commands) != 1:
|
||||
src.fail(f"expected one command line starting with {binary}, found {len(commands)}")
|
||||
prefix = cg.bios.rstrip("/") + "/"
|
||||
launchers = []
|
||||
for system, branch in system_branches(generate):
|
||||
bound = [
|
||||
(stmt, held) for stmt in branch.body
|
||||
if _assigned_name(stmt) == binary and isinstance((held := _bound(stmt)), ast.Name)
|
||||
]
|
||||
if len(bound) != 1:
|
||||
src.fail(f"the {system} branch does not set {binary} once")
|
||||
bound_stmt, bound_value = bound[0]
|
||||
constant = ast.unparse(bound_value)
|
||||
path = constants.get(constant)
|
||||
if path is None or not path.startswith(prefix):
|
||||
src.fail(f"{constant} is not a path under {cg.bios}")
|
||||
messages = [render(m, binary, path) for m in (missing_message, access_message)]
|
||||
launchers.append(Launcher(
|
||||
emulator=cg.emulator(module), build="standalone", kind="fixed_name",
|
||||
slot=system, names=[path[len(prefix):]], case_insensitive=False,
|
||||
search_dir=cg.bios, passes_to="exec",
|
||||
fails_when_missing=", ".join(messages),
|
||||
source_ref=src.ref([
|
||||
src.span(defined[constant]), src.span(branch.test), src.span(bound_stmt),
|
||||
_lines(missing), _lines(access),
|
||||
src.span(commands[0]),
|
||||
]),
|
||||
))
|
||||
if not launchers:
|
||||
src.fail("generate no longer branches on system.name")
|
||||
return launchers
|
||||
|
||||
|
||||
def pico8_installer(read: Callable[[str], str], bios: str) -> list[Launcher]:
|
||||
"""knulli-install-pico8: unzips the Raspberry Pi build and moves it into the BIOS folder."""
|
||||
script = Script(PICO8_INSTALLER, read(PICO8_INSTALLER))
|
||||
lines: set[int] = set()
|
||||
archive_line, archive = script.find(r"\$\(ls -d (\S+\.zip)", "the PICO-8 zip lookup")
|
||||
lines.add(archive_line)
|
||||
guard_line, _ = script.find(r'^if \[ -z \$PICO_8_ZIPFILE \]', "the missing zip test")
|
||||
message_line, message = script.find(r'^\s*echo "([^"]+)"', "the missing zip message", guard_line)
|
||||
lines |= {guard_line, message_line}
|
||||
names: list[str] = []
|
||||
prefix = bios.rstrip("/") + "/"
|
||||
for number, line in script.code():
|
||||
moved = re.match(r"\s*mv\s+(\S+)\s+(\S+)\s*$", line)
|
||||
if moved is None:
|
||||
continue
|
||||
used: set[int] = set()
|
||||
source = script.expand(moved.group(1), number, used)
|
||||
target = script.expand(moved.group(2).strip('"'), number, used)
|
||||
if not target.startswith(prefix):
|
||||
continue
|
||||
if target.endswith("/"):
|
||||
target += source.rsplit("/", 1)[-1]
|
||||
names.append(target[len(prefix):])
|
||||
lines |= used | {number}
|
||||
if not names:
|
||||
raise script.missing(f"mv into {bios}")
|
||||
folder = names[0].rsplit("/", 1)[0]
|
||||
return [Launcher(
|
||||
emulator="lexaloffle", build="standalone", kind="moves", names=names,
|
||||
case_insensitive=False, search_dir=bios,
|
||||
passes_to=f"moved from {archive.group(1)} into {prefix}{folder}",
|
||||
fails_when_missing=message.group(1),
|
||||
source_ref=source_ref([(PICO8_INSTALLER, lines)]),
|
||||
)]
|
||||
|
||||
|
||||
def _quoted(node: ast.AST) -> str | None:
|
||||
"""The value of a '"name"' core option literal."""
|
||||
if isinstance(node, ast.Constant) and isinstance(node.value, str):
|
||||
value = node.value
|
||||
if len(value) >= 2 and value[0] == value[-1] == '"':
|
||||
return value[1:-1]
|
||||
return None
|
||||
|
||||
|
||||
# libretro core options whose value names the BIOS file the core opens,
|
||||
# the same two batocera.FILE_OPTIONS reads.
|
||||
FILE_OPTIONS = ("o2em_bios", "neocd_bios")
|
||||
|
||||
|
||||
def core_file_options(cg: Configgen) -> list[Launcher]:
|
||||
"""if isOptSet(o): save(o, option) elif ...: save(o, '"a"') else: save(o, '"b"')."""
|
||||
src = cg.source(LIBRETRO_OPTIONS)
|
||||
function = src.function("generateCoreSettings")
|
||||
launchers = []
|
||||
for setting in FILE_OPTIONS:
|
||||
chains = [
|
||||
node for node in ast.walk(function)
|
||||
if isinstance(node, ast.If)
|
||||
and ast.unparse(node.test) == f"system.isOptSet({setting!r})"
|
||||
]
|
||||
if len(chains) != 1:
|
||||
src.fail(f"expected one `if system.isOptSet({setting!r})`, found {len(chains)}")
|
||||
chain = chains[0]
|
||||
names: list[str] = []
|
||||
conditions: list[str] = []
|
||||
branch: ast.If | None = chain
|
||||
tail: list[ast.stmt] = chain.orelse
|
||||
while branch is not None:
|
||||
tail = branch.orelse
|
||||
if branch is not chain:
|
||||
saved = _saved(branch.body, setting)
|
||||
if saved is None:
|
||||
src.fail(f"a branch of {setting} saves no literal name")
|
||||
names.append(saved)
|
||||
conditions.append(ast.unparse(branch.test))
|
||||
branch = tail[0] if len(tail) == 1 and isinstance(tail[0], ast.If) else None
|
||||
default = _saved(tail, setting)
|
||||
if default is None:
|
||||
src.fail(f"{setting} has no literal default")
|
||||
names.append(default)
|
||||
holder = next(
|
||||
(
|
||||
node for node in ast.walk(function)
|
||||
if isinstance(node, ast.If) and _cores_of(node.test)
|
||||
and any(child is chain for child in ast.walk(node))
|
||||
),
|
||||
None,
|
||||
)
|
||||
if holder is None:
|
||||
src.fail(f"{setting} is not set under a core test")
|
||||
depends = setting if not conditions else f"{setting} (default by {', '.join(conditions)})"
|
||||
launchers.append(Launcher(
|
||||
emulator=join_emulators(_cores_of(holder.test)), build="libretro", kind="core_option",
|
||||
names=names, passes_to=f"core option {setting}", depends_on_option=depends,
|
||||
source_ref=src.ref([src.span(holder.test), _lines(chain)]),
|
||||
))
|
||||
return launchers
|
||||
|
||||
|
||||
def _saved(body: list[ast.stmt], setting: str) -> str | None:
|
||||
"""The literal a one-statement body saves under setting."""
|
||||
if len(body) != 1 or not isinstance(body[0], ast.Expr):
|
||||
return None
|
||||
call = body[0].value
|
||||
if (
|
||||
isinstance(call, ast.Call)
|
||||
and isinstance(call.func, ast.Attribute)
|
||||
and call.func.attr == "save"
|
||||
and len(call.args) == 2
|
||||
and isinstance(call.args[0], ast.Constant)
|
||||
and call.args[0].value == setting
|
||||
):
|
||||
return _quoted(call.args[1])
|
||||
return None
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Generic reading of the /userdata/bios paths a generator hands over.
|
||||
|
||||
|
||||
GENERIC_SITES = (
|
||||
GenericSites("dolphin/dolphinGenerator.py", "fixed_name"),
|
||||
GenericSites("yabasanshiro/yabasanshiroGenerator.py", "fixed_name"),
|
||||
GenericSites("rpcs3/rpcs3Generator.py", "fixed_name"),
|
||||
GenericSites("ryujinx/ryujinxGenerator.py", "fixed_name"),
|
||||
GenericSites("pcsx2/pcsx2Generator.py", "fixed_name"),
|
||||
GenericSites("aethersx2/aethersx2Generator.py", "fixed_name"),
|
||||
GenericSites("gsplus/gsplusGenerator.py", "passes_path"),
|
||||
GenericSites("tsugaru/tsugaruGenerator.py", "passes_path"),
|
||||
GenericSites("scummvm/scummvmGenerator.py", "passes_path"),
|
||||
GenericSites("fsuae/fsuaeGenerator.py", "passes_path"),
|
||||
GenericSites("mame/mameGenerator.py", "passes_path"),
|
||||
GenericSites("fpinball/fpinballGenerator.py", "passes_path"),
|
||||
GenericSites(
|
||||
"libretro/libretroRetroarchCustom.py", "passes_path", "libretro", emulator="retroarch"
|
||||
),
|
||||
GenericSites("libretro/libretroConfig.py", "passes_path", "libretro"),
|
||||
GenericSites(
|
||||
"libretro/libretroMAMEConfig.py", "passes_path", "libretro",
|
||||
caller=("libretro/libretroConfig.py", "generateMAMEConfigs"),
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
# 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.
|
||||
RELATIVE_FOLDERS = (
|
||||
("pcsx2/pcsx2Generator.py", "configureINI"),
|
||||
("aethersx2/aethersx2Generator.py", "configureINI"),
|
||||
)
|
||||
|
||||
|
||||
def relative_folders(
|
||||
cg: Configgen, specs: tuple[tuple[str, str], ...] = RELATIVE_FOLDERS
|
||||
) -> list[Launcher]:
|
||||
"""parser.set(section, key, "../<path>") resolved against config_directory."""
|
||||
launchers = []
|
||||
for path, function_name in specs:
|
||||
src = cg.source(f"{cg.generators}/{path}")
|
||||
reader = _Reader(cg, src)
|
||||
function = src.function(function_name)
|
||||
if not function.args.args:
|
||||
src.fail(f"{function_name} takes no config folder")
|
||||
folder = function.args.args[0].arg
|
||||
ini = [
|
||||
node for node in ast.walk(function)
|
||||
if isinstance(node, ast.Assign) and isinstance(node.value, ast.BinOp)
|
||||
and ast.unparse(node.value).startswith(f"{folder} /")
|
||||
and ast.unparse(node.value).endswith(".ini'")
|
||||
]
|
||||
if len(ini) != 1:
|
||||
src.fail(f"{function_name} builds no one ini path under {folder}")
|
||||
parts = sorted(
|
||||
(n for n in ast.walk(ini[0].value)
|
||||
if isinstance(n, ast.Constant) and isinstance(n.value, str)),
|
||||
key=lambda n: (n.lineno, n.col_offset),
|
||||
)
|
||||
ini_name = posixpath.join(*(str(n.value) for n in parts))
|
||||
calls = [
|
||||
node for node in ast.walk(src.tree)
|
||||
if isinstance(node, ast.Call) and isinstance(node.func, ast.Name)
|
||||
and node.func.id == function_name and node.args
|
||||
]
|
||||
if len(calls) != 1:
|
||||
src.fail(f"expected one call of {function_name}, found {len(calls)}")
|
||||
base = reader.resolve(calls[0].args[0])
|
||||
if base is None or not base.startswith("/"):
|
||||
src.fail(f"{function_name} is given a folder that is not a path")
|
||||
found = 0
|
||||
for call in ast.walk(function):
|
||||
if not (
|
||||
isinstance(call, ast.Call) and isinstance(call.func, ast.Attribute)
|
||||
and call.func.attr == "set" and len(call.args) == 3
|
||||
and all(isinstance(a, ast.Constant) for a in call.args)
|
||||
):
|
||||
continue
|
||||
section, key, value = (str(a.value) for a in call.args if isinstance(a, ast.Constant))
|
||||
if not value.startswith("../"):
|
||||
continue
|
||||
resolved = posixpath.normpath(posixpath.join(base, value))
|
||||
if not reader.under_bios(resolved):
|
||||
continue
|
||||
found += 1
|
||||
launchers.append(Launcher(
|
||||
emulator=cg.emulator(path.removesuffix(".py").replace("/", ".")),
|
||||
build="standalone", kind="passes_path", names=[], search_dir=resolved,
|
||||
passes_to=f"{ini_name} [{section}] {key} = {value}, relative to {base}",
|
||||
fails_when_missing=False,
|
||||
source_ref=src.ref([
|
||||
src.span(reader.statement_of(calls[0])), src.span(ini[0]), _lines(call),
|
||||
]),
|
||||
))
|
||||
if not found:
|
||||
src.fail(f"{function_name} writes no relative folder under {cg.bios}")
|
||||
return launchers
|
||||
|
||||
|
||||
def _yaml_node(root: yaml.Node, keys: tuple[str, ...], path: str) -> yaml.Node:
|
||||
node = root
|
||||
for key in keys:
|
||||
if not isinstance(node, yaml.MappingNode):
|
||||
raise LauncherShapeError(f"{path}: {key} is not under a mapping")
|
||||
found = [v for k, v in node.value if isinstance(k, yaml.ScalarNode) and k.value == key]
|
||||
if len(found) != 1:
|
||||
raise LauncherShapeError(f"{path}: no {'/'.join(keys)}")
|
||||
node = found[0]
|
||||
return node
|
||||
|
||||
|
||||
def option_choices(read: Callable[[str], str], keys: tuple[str, ...]) -> tuple[list[str], tuple[int, int]]:
|
||||
"""The values es_features.yml offers for an option, and their lines."""
|
||||
node = _yaml_node(yaml.compose(read(ES_FEATURES)), (*keys, "choices"), ES_FEATURES)
|
||||
if not isinstance(node, yaml.MappingNode) or not node.value:
|
||||
raise LauncherShapeError(f"{ES_FEATURES}: {'/'.join(keys)} has no choices")
|
||||
values = [str(v.value) for _k, v in node.value if isinstance(v, yaml.ScalarNode)]
|
||||
return values, (node.start_mark.line + 1, node.end_mark.line)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class BootDisk:
|
||||
"""A generator that names a BIOS file from an option value, and the ES feature offering it."""
|
||||
|
||||
path: str
|
||||
feature: tuple[str, ...]
|
||||
build: str = "standalone"
|
||||
caller: tuple[str, str] | None = None
|
||||
|
||||
|
||||
BOOT_DISKS = (
|
||||
BootDisk("mame/mameGenerator.py", ("mame", "systems", "macintosh", "cfeatures")),
|
||||
BootDisk(
|
||||
"libretro/libretroMAMEConfig.py",
|
||||
("libretro", "cores", "mame", "systems", "macintosh", "cfeatures"), "libretro",
|
||||
("libretro/libretroConfig.py", "generateMAMEConfigs"),
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def _option_template(reader: _Reader, node: ast.AST) -> tuple[str, str] | None:
|
||||
"""(option, name) for '<bios>/' + system.config[option] + '<suffix>'."""
|
||||
if not (isinstance(node, ast.BinOp) and isinstance(node.op, ast.Add)):
|
||||
return None
|
||||
left, suffix = node.left, node.right
|
||||
if not (
|
||||
isinstance(left, ast.BinOp) and isinstance(left.op, ast.Add)
|
||||
and isinstance(left.left, ast.Constant) and isinstance(suffix, ast.Constant)
|
||||
and isinstance(left.right, ast.Subscript)
|
||||
and ast.unparse(left.right.value) == "system.config"
|
||||
and isinstance(left.right.slice, ast.Constant)
|
||||
):
|
||||
return None
|
||||
prefix = str(left.left.value).strip('"')
|
||||
if not prefix.startswith(reader.bios + "/"):
|
||||
return None
|
||||
option = str(left.right.slice.value)
|
||||
name = prefix[len(reader.bios) + 1:] + "{" + option + "}" + str(suffix.value).strip('"')
|
||||
return option, name
|
||||
|
||||
|
||||
def boot_disks(
|
||||
cg: Configgen, read: Callable[[str], str], specs: tuple[BootDisk, ...] = BOOT_DISKS
|
||||
) -> list[Launcher]:
|
||||
"""`if system.config[o] in [...]: X = bios + o + ext else: X = bios + o + ext2`."""
|
||||
launchers = []
|
||||
for spec in specs:
|
||||
src = cg.source(f"{cg.generators}/{spec.path}")
|
||||
reader = _Reader(cg, src)
|
||||
module = spec.path.removesuffix(".py").replace("/", ".")
|
||||
emulator = (
|
||||
join_emulators(_caller_cores(cg, spec.caller)) if spec.caller else cg.emulator(module)
|
||||
)
|
||||
if spec.caller and spec.feature[:2] == ("libretro", "cores"):
|
||||
# The option is offered for one core of the system: es_features
|
||||
# lists it under that core, the other cores the generator serves
|
||||
# never see it (KNULLI's macintosh offers mame alone).
|
||||
core = spec.feature[2]
|
||||
if core not in emulator_names(emulator):
|
||||
src.fail(f"es_features offers the option for {core}, which the generator does not serve")
|
||||
emulator = core
|
||||
found = 0
|
||||
for chain in ast.walk(src.tree):
|
||||
if not (
|
||||
isinstance(chain, ast.If) and isinstance(chain.test, ast.Compare)
|
||||
and isinstance(chain.test.ops[0], ast.In)
|
||||
and isinstance(chain.test.comparators[0], ast.List)
|
||||
and ast.unparse(chain.test.left).startswith("system.config[")
|
||||
):
|
||||
continue
|
||||
branches = [(chain.body, True), (chain.orelse, False)]
|
||||
templates = []
|
||||
for body, listed in branches:
|
||||
flag = next(
|
||||
(str(s.value.value) for s in body if isinstance(s, ast.Assign)
|
||||
and isinstance(s.value, ast.Constant) and str(s.value.value).startswith("-")),
|
||||
None,
|
||||
)
|
||||
named = [
|
||||
(s, t) for s in body if isinstance(s, ast.Assign)
|
||||
and (t := _option_template(reader, s.value)) is not None
|
||||
]
|
||||
if flag is None or len(named) != 1:
|
||||
break
|
||||
templates.append((listed, flag, *named[0]))
|
||||
if len(templates) != 2:
|
||||
continue
|
||||
option = templates[0][3][0]
|
||||
if option != templates[1][3][0] or ast.unparse(chain.test.left) != f"system.config[{option!r}]":
|
||||
src.fail(f"line {chain.lineno} names a file from two options")
|
||||
listed_values = [
|
||||
str(e.value) for e in chain.test.comparators[0].elts if isinstance(e, ast.Constant)
|
||||
]
|
||||
offered, lines = option_choices(read, (*spec.feature, option))
|
||||
holder = reader.parents.get(id(chain))
|
||||
body = getattr(holder, "body", [])
|
||||
index = next(i for i, stmt in enumerate(body) if stmt is chain)
|
||||
added = body[index + 1] if index + 1 < len(body) else None
|
||||
if not (
|
||||
isinstance(added, ast.AugAssign) and isinstance(added.value, ast.List)
|
||||
and ast.unparse(added.target) in COMMAND_NAMES
|
||||
):
|
||||
src.fail(f"the file chosen at line {chain.lineno} is not put on the command line")
|
||||
for listed, flag, statement, (_, name) in templates:
|
||||
values = listed_values if listed else [v for v in offered if v not in listed_values]
|
||||
if not values:
|
||||
src.fail(f"no {option} value reaches the branch at line {statement.lineno}")
|
||||
tests, spans = reader.conditions(statement)
|
||||
found += 1
|
||||
launchers.append(Launcher(
|
||||
emulator=emulator, build=spec.build, kind="fixed_name", names=[name],
|
||||
expands={option: values}, case_insensitive=False, search_dir=cg.bios,
|
||||
passes_to=f"command line {flag}", fails_when_missing=False,
|
||||
depends_on_option=f"{option} ({' and '.join(tests)})",
|
||||
# The values the menu offers come from es_features.yml;
|
||||
# the generator writing the choice is the evidence.
|
||||
choices_from=None if listed else f"{ES_FEATURES}:{lines[0]}-{lines[1]}",
|
||||
source_ref=src.ref([*spans, src.span(statement), _lines(added)]),
|
||||
))
|
||||
if not found:
|
||||
src.fail("names no BIOS file from an option value")
|
||||
return launchers
|
||||
|
||||
|
||||
EXTRACTORS: tuple[Callable[[Configgen], list[Launcher]], ...] = (
|
||||
*SHARED, lexaloffle, core_file_options, relative_folders,
|
||||
)
|
||||
|
||||
|
||||
# KNULLI builds Batocera's emulator packages from this submodule, at the
|
||||
# batocera.linux commit it pins: Citron's path patch is there.
|
||||
BATOCERA_SUBMODULE = "batocera"
|
||||
|
||||
|
||||
def extract_launchers(
|
||||
read: Callable[[str], str], batocera: Callable[[str], str] | None = None
|
||||
) -> Extraction:
|
||||
"""Every launcher record, read through `read(repo-relative path)`.
|
||||
|
||||
`batocera` reads the batocera submodule at its pinned commit. The
|
||||
records it gives name the file by its path in KNULLI's repository.
|
||||
"""
|
||||
cg = configgen(read)
|
||||
launchers = [launcher for extractor in EXTRACTORS for launcher in extractor(cg)]
|
||||
launchers += pico8_installer(read, cg.bios)
|
||||
launchers += boot_disks(cg, read)
|
||||
for spec in GENERIC_SITES:
|
||||
launchers += bios_sites(cg, spec)
|
||||
if batocera is not None:
|
||||
prefix = f"{BATOCERA_SUBMODULE}/"
|
||||
launchers += patched_paths(
|
||||
lambda path: batocera(path.removeprefix(prefix)),
|
||||
tuple(prefix + patch for patch in PATH_PATCHES),
|
||||
)
|
||||
return extraction(launchers, cg.bios)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"CONFIGGEN", "GENERIC_SITES", "LauncherPatternMissing", "LauncherShapeError",
|
||||
"bios_sites", "configgen", "core_file_options", "extract_launchers", "lexaloffle",
|
||||
"pico8_installer",
|
||||
]
|
||||
@@ -0,0 +1,290 @@
|
||||
"""Recalbox's launcher layer, read from the configgen generators.
|
||||
|
||||
Recalbox's configgen decides which file name each emulator is given and
|
||||
where it is handed over: Hatari's generator walks a TOS cascade per machine,
|
||||
PCSX2's picks a BIOS by the region token of the rom name, and for every
|
||||
libretro core libretroRetroarch chooses the directory RetroArch receives as
|
||||
system_directory. That is the platform's behaviour, so it is recorded here
|
||||
with the lines of the pinned tag that say it.
|
||||
|
||||
Each extractor reads one known shape with ast and raises LauncherShapeError
|
||||
when the shape is gone, as the Batocera reader does.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import ast
|
||||
from collections.abc import Callable
|
||||
from typing import Any
|
||||
|
||||
from model.launcherrecords import emulator_names, join_emulators
|
||||
from .configgen import (
|
||||
Launcher,
|
||||
LauncherShapeError,
|
||||
_assigned_name,
|
||||
_calls,
|
||||
_innermost_function,
|
||||
_locate,
|
||||
end_line,
|
||||
)
|
||||
from .recalbox_cascades import gsplus, hatari, hatari_libretro
|
||||
from .recalbox_configgen import (
|
||||
ALL_CORES,
|
||||
AMIBERRY_CONFIG,
|
||||
AMIBERRY_GLOBAL,
|
||||
AMIBERRY_KICKSTARTS,
|
||||
AMIBERRY_SUBSYSTEMS,
|
||||
CORES,
|
||||
CORE_ASSETS,
|
||||
Configgen,
|
||||
DOLPHIN,
|
||||
FILES_MODULE,
|
||||
FILE_OPTIONS,
|
||||
GSPLUS,
|
||||
HATARI,
|
||||
LAUNCHER,
|
||||
LIBRETRO_GENERATOR,
|
||||
MUPEN_CONFIG,
|
||||
PCSX2,
|
||||
RETROARCH,
|
||||
SYSTEM_DIRECTORY,
|
||||
XEMU,
|
||||
XROAR,
|
||||
expr_call,
|
||||
handler_map,
|
||||
local_string_lists,
|
||||
is_setter_call,
|
||||
setter_branches,
|
||||
string,
|
||||
string_constant,
|
||||
spell,
|
||||
)
|
||||
from .recalbox_emulators import amiberry, dolphin, mupen64plus, pcsx2, xemu, xroar
|
||||
|
||||
|
||||
SOURCE_FILES = (
|
||||
FILES_MODULE, LAUNCHER, RETROARCH, CORES, LIBRETRO_GENERATOR, HATARI, GSPLUS,
|
||||
AMIBERRY_KICKSTARTS, AMIBERRY_SUBSYSTEMS, AMIBERRY_CONFIG, AMIBERRY_GLOBAL, PCSX2, DOLPHIN, XEMU,
|
||||
MUPEN_CONFIG, XROAR,
|
||||
)
|
||||
|
||||
|
||||
def system_directories(cg: Configgen) -> list[Launcher]:
|
||||
"""`match self.system.Core` per core, then the overrides per system."""
|
||||
src = cg.source(RETROARCH)
|
||||
matches = [
|
||||
node for node in ast.walk(src.tree)
|
||||
if isinstance(node, ast.Match)
|
||||
and ast.unparse(node.subject) == "self.system.Core"
|
||||
and any(is_setter_call(c, SYSTEM_DIRECTORY) for c in _calls(node, attr="setString"))
|
||||
]
|
||||
if len(matches) != 1:
|
||||
src.fail(f"expected one match on the core writing {SYSTEM_DIRECTORY}, "
|
||||
f"found {len(matches)}")
|
||||
match = matches[0]
|
||||
scope = _innermost_function(src, match)
|
||||
env = cg.env(src, scope)
|
||||
local_lists = local_string_lists(src, scope)
|
||||
lists = {name: values for name, (values, _node) in local_lists.items()}
|
||||
|
||||
def record(emulator: str, condition: str | None, call: ast.Call,
|
||||
spans: list[tuple[int, int]]) -> Launcher:
|
||||
directory = cg.bios_dir(spell(call.args[1], env), src, f"line {call.lineno}")
|
||||
return Launcher(
|
||||
emulator=emulator, build="libretro", kind="passes_path", names=[],
|
||||
search_dir=directory, passes_to=f"retroarch {SYSTEM_DIRECTORY}",
|
||||
depends_on_option=condition, source_ref=src.ref(spans),
|
||||
)
|
||||
|
||||
launchers = []
|
||||
for case in match.cases:
|
||||
if case.guard is not None:
|
||||
src.fail(f"line {case.pattern.lineno}: a guarded case is not read")
|
||||
pattern = case.pattern
|
||||
options = pattern.patterns if isinstance(pattern, ast.MatchOr) else [pattern]
|
||||
cores = [core for p in options
|
||||
if isinstance(p, ast.MatchValue)
|
||||
and (core := string_constant(src, p.value, "core name")) is not None]
|
||||
wildcard = isinstance(pattern, ast.MatchAs) and pattern.pattern is None
|
||||
if not wildcard and len(cores) != len(options):
|
||||
src.fail(f"line {pattern.lineno}: case pattern is not a list of core names")
|
||||
branches = setter_branches(src, case.body, SYSTEM_DIRECTORY, lists)
|
||||
if not branches:
|
||||
src.fail(f"line {pattern.lineno}: case writes no {SYSTEM_DIRECTORY}")
|
||||
for condition, call, start in branches:
|
||||
if wildcard:
|
||||
words = ["core with no case of its own"] + ([condition] if condition else [])
|
||||
condition = ", ".join(words)
|
||||
launchers.append(record(
|
||||
join_emulators(cores) or ALL_CORES, condition, call,
|
||||
[(pattern.lineno, pattern.lineno), (start, end_line(call))],
|
||||
))
|
||||
|
||||
located = _locate(scope, lambda stmt: stmt is match)
|
||||
if located is None:
|
||||
src.fail(f"no statement list holds the match on the core writing {SYSTEM_DIRECTORY}")
|
||||
body, index = located
|
||||
overrides = setter_branches(src, body[index + 1:], SYSTEM_DIRECTORY, lists)
|
||||
if not overrides:
|
||||
src.fail(f"no per-system {SYSTEM_DIRECTORY} after the match on the core")
|
||||
tests = {node.lineno: node.test for node in ast.walk(scope) if isinstance(node, ast.If)}
|
||||
for condition, call, start in overrides:
|
||||
if condition is None:
|
||||
src.fail(f"line {call.lineno}: {SYSTEM_DIRECTORY} rewritten for every system")
|
||||
read = {n.id for n in ast.walk(tests[start]) if isinstance(n, ast.Name)} \
|
||||
if start in tests else set()
|
||||
spans = [(start, end_line(call))]
|
||||
spans += [src.span(node) for name, (_v, node) in local_lists.items() if name in read]
|
||||
launchers.append(record(
|
||||
ALL_CORES, f"{condition}, replacing the directory chosen by core", call, spans,
|
||||
))
|
||||
return launchers
|
||||
|
||||
|
||||
def core_directory(directories: list[Launcher], core: str) -> Launcher:
|
||||
"""The unconditional system_directory record that applies to `core`."""
|
||||
for launcher in directories:
|
||||
if core in emulator_names(launcher.emulator) and launcher.depends_on_option is None:
|
||||
return launcher
|
||||
for launcher in directories:
|
||||
if launcher.emulator == ALL_CORES and launcher.depends_on_option == \
|
||||
"core with no case of its own":
|
||||
return launcher
|
||||
raise LauncherShapeError(f"{RETROARCH}: no {SYSTEM_DIRECTORY} applies to {core}")
|
||||
|
||||
|
||||
def core_assets(cg: Configgen) -> list[Launcher]:
|
||||
"""`if self.system.Core == x: setString("core_assets_directory", dir)`."""
|
||||
src = cg.source(RETROARCH)
|
||||
env = cg.env(src)
|
||||
launchers = []
|
||||
for node in ast.walk(src.tree):
|
||||
if not (
|
||||
isinstance(node, ast.If)
|
||||
and isinstance(node.test, ast.Compare)
|
||||
and ast.unparse(node.test.left) == "self.system.Core"
|
||||
and isinstance(node.test.ops[0], ast.Eq)
|
||||
):
|
||||
continue
|
||||
core = string_constant(src, node.test.comparators[0], "core name")
|
||||
if core is None:
|
||||
continue
|
||||
calls = [c for stmt in node.body if (c := expr_call(stmt)) and is_setter_call(c, CORE_ASSETS)]
|
||||
if len(calls) != 1:
|
||||
continue
|
||||
call = calls[0]
|
||||
launchers.append(Launcher(
|
||||
emulator=core, build="libretro", kind="passes_path",
|
||||
names=[], search_dir=cg.bios_dir(spell(call.args[1], env), src, CORE_ASSETS),
|
||||
passes_to=f"retroarch {CORE_ASSETS}",
|
||||
source_ref=src.ref([(node.lineno, end_line(call))]),
|
||||
))
|
||||
if not launchers:
|
||||
src.fail(f"no core is given a {CORE_ASSETS}")
|
||||
return launchers
|
||||
|
||||
|
||||
def content_files(cg: Configgen) -> list[Launcher]:
|
||||
"""`if core == x:` writing a BIOS path into a file loaded as the content."""
|
||||
src = cg.source(LIBRETRO_GENERATOR)
|
||||
files = cg.source(FILES_MODULE)
|
||||
env = cg.env(src)
|
||||
launchers = []
|
||||
for node in ast.walk(src.tree):
|
||||
if not (
|
||||
isinstance(node, ast.If)
|
||||
and isinstance(node.test, ast.Compare)
|
||||
and ast.unparse(node.test.left) == "core"
|
||||
):
|
||||
continue
|
||||
core = string_constant(src, node.test.comparators[0], "core name")
|
||||
if core is None:
|
||||
continue
|
||||
refs = [n for n in ast.walk(node) if isinstance(n, ast.Attribute)
|
||||
and ast.unparse(n.value) == "recalboxFiles"]
|
||||
names = list(dict.fromkeys(
|
||||
name for n in refs if (name := cg.under_bios(spell(n, env))) is not None
|
||||
))
|
||||
opened = [c for c in _calls(node, name="open")
|
||||
if len(c.args) == 2 and spell(c.args[1], env) == "w"]
|
||||
if not names:
|
||||
continue
|
||||
target = spell(opened[0].args[0], env) if len(opened) == 1 else None
|
||||
returned = [n for n in ast.walk(node) if isinstance(n, ast.Return)]
|
||||
if target is None or not returned:
|
||||
src.fail(f"line {node.lineno}: BIOS path is not written to a file passed on")
|
||||
constants = {n.attr for n in refs if cg.under_bios(spell(n, env)) is not None}
|
||||
lines = [n.lineno for n in files.tree.body if _assigned_name(n) in constants]
|
||||
launchers.append(Launcher(
|
||||
emulator=core, build="libretro", kind="fixed_name",
|
||||
names=names, case_insensitive=False, search_dir=cg.bios,
|
||||
passes_to=f"written into {target}, which is loaded as the content",
|
||||
fails_when_missing=False,
|
||||
source_ref=f"{src.ref([(node.lineno, end_line(node))])}, "
|
||||
f"{files.ref([(line, line) for line in lines])}",
|
||||
))
|
||||
if not launchers:
|
||||
src.fail("no core is given a BIOS path through a content file")
|
||||
return launchers
|
||||
|
||||
|
||||
def core_file_options(cg: Configgen, directories: list[Launcher]) -> list[Launcher]:
|
||||
"""System handlers that set a core option naming the file the core opens."""
|
||||
src = cg.source(CORES)
|
||||
handlers = handler_map(src, "fillCoresConfiguration", "specificSystemHandlers")
|
||||
table = src.assignment(
|
||||
"specificSystemHandlers", src.function("fillCoresConfiguration")
|
||||
).value
|
||||
if not isinstance(table, ast.Dict):
|
||||
src.fail("specificSystemHandlers is not a dict display")
|
||||
defined = {n.name: n for n in ast.walk(src.tree) if isinstance(n, ast.FunctionDef)}
|
||||
launchers = []
|
||||
for function_name, systems in handlers.items():
|
||||
function = defined.get(function_name)
|
||||
if function is None:
|
||||
continue
|
||||
for call in _calls(function, attr="setString"):
|
||||
if not (len(call.args) == 2 and all(isinstance(a, ast.Constant) for a in call.args)
|
||||
and string(call.args[0]) in FILE_OPTIONS):
|
||||
continue
|
||||
option = string_constant(src, call.args[0], "core option")
|
||||
value = string_constant(src, call.args[1], "core option value")
|
||||
if option is None or value is None:
|
||||
continue
|
||||
core = FILE_OPTIONS[option]
|
||||
directory = core_directory(directories, core)
|
||||
spans = [(k.lineno, k.lineno) for k, v in zip(table.keys, table.values)
|
||||
if k is not None and isinstance(v, ast.Attribute) and v.attr == function_name]
|
||||
launchers.append(Launcher(
|
||||
emulator=core, build="libretro", kind="core_option",
|
||||
names=[value.strip('"')], search_dir=directory.search_dir,
|
||||
passes_to=f"core option {option}",
|
||||
depends_on_option=f"system {', '.join(systems)}",
|
||||
source_ref=f"{src.ref([(function.lineno, function.end_lineno or function.lineno), *spans])}, "
|
||||
f"{directory.source_ref}",
|
||||
))
|
||||
found = {str(launcher.passes_to).split()[-1] for launcher in launchers}
|
||||
missing = sorted(set(FILE_OPTIONS) - found)
|
||||
if missing:
|
||||
src.fail(f"no system handler sets {', '.join(missing)}")
|
||||
return launchers
|
||||
|
||||
|
||||
STANDALONE: tuple[Callable[[Configgen], list[Launcher]], ...] = (
|
||||
hatari, gsplus, amiberry, pcsx2, xemu, mupen64plus, xroar,
|
||||
)
|
||||
LIBRETRO: tuple[Callable[[Configgen], list[Launcher]], ...] = (
|
||||
core_assets, hatari_libretro, content_files,
|
||||
)
|
||||
|
||||
|
||||
def extract_launchers(read: Callable[[str], str]) -> list[dict[str, Any]]:
|
||||
"""Every launcher record, read through `read(repo-relative path)`."""
|
||||
cg = Configgen(read)
|
||||
directories = system_directories(cg)
|
||||
launchers = [launcher for extractor in STANDALONE for launcher in extractor(cg)]
|
||||
launchers += dolphin(cg)
|
||||
launchers += directories
|
||||
launchers += [launcher for extractor in LIBRETRO for launcher in extractor(cg)]
|
||||
launchers += core_file_options(cg, directories)
|
||||
return [launcher.entry() for launcher in launchers]
|
||||
@@ -0,0 +1,430 @@
|
||||
"""Recalbox paths tried with os.path.exists down a chain: Hatari's TOS and the GSplus ROM."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import ast
|
||||
import posixpath
|
||||
from collections.abc import Mapping
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
from .configgen import (
|
||||
Launcher,
|
||||
Source,
|
||||
_assigned_name,
|
||||
_calls,
|
||||
_locate,
|
||||
assigned_value,
|
||||
end_line,
|
||||
)
|
||||
from .recalbox_configgen import (
|
||||
BUILTIN_TOKEN,
|
||||
CORES,
|
||||
Configgen,
|
||||
GSPLUS,
|
||||
HATARI,
|
||||
TOS_FUNCTIONS,
|
||||
assignments,
|
||||
expr_call,
|
||||
is_setter_call,
|
||||
string,
|
||||
string_constant,
|
||||
spell,
|
||||
)
|
||||
|
||||
|
||||
def _exists_arg(test: ast.expr) -> ast.expr | None:
|
||||
"""X in `not os.path.exists(X)`."""
|
||||
if (
|
||||
isinstance(test, ast.UnaryOp)
|
||||
and isinstance(test.op, ast.Not)
|
||||
and isinstance(test.operand, ast.Call)
|
||||
and ast.unparse(test.operand.func) == "os.path.exists"
|
||||
and len(test.operand.args) == 1
|
||||
):
|
||||
return test.operand.args[0]
|
||||
return None
|
||||
|
||||
|
||||
def _assigns(stmt: ast.stmt, var: str) -> ast.expr | None:
|
||||
if isinstance(stmt, (ast.Assign, ast.AnnAssign)) and _assigned_name(stmt) == var:
|
||||
return stmt.value
|
||||
return None
|
||||
|
||||
|
||||
def _skip_imports(body: list[ast.stmt], index: int) -> int:
|
||||
while index < len(body) and isinstance(body[index], (ast.Import, ast.ImportFrom)):
|
||||
index += 1
|
||||
return index
|
||||
|
||||
|
||||
def _written_path(call: ast.Call, paths: set[str]) -> str | None:
|
||||
"""X when the last argument of `call` is str(X), X one of `paths`."""
|
||||
if not call.args:
|
||||
return None
|
||||
last = call.args[-1]
|
||||
if (
|
||||
isinstance(last, ast.Call)
|
||||
and ast.unparse(last.func) == "str"
|
||||
and isinstance(last.args[0], ast.Name)
|
||||
and last.args[0].id in paths
|
||||
):
|
||||
return last.args[0].id
|
||||
return None
|
||||
|
||||
|
||||
def _tos_setter(
|
||||
src: Source, scope: ast.FunctionDef, env: Mapping[str, str]
|
||||
) -> tuple[ast.Call, str, str]:
|
||||
"""The setting written from str(<path>), the path variable, and where it goes."""
|
||||
paths = {
|
||||
name for _node, name, value in assignments(ast.walk(scope))
|
||||
if isinstance(value, ast.Call) and ast.unparse(value.func) == "os.path.join"
|
||||
}
|
||||
setters = [
|
||||
(call, var) for call in _calls(scope, attr="setString")
|
||||
if (var := _written_path(call, paths)) is not None
|
||||
]
|
||||
if len(setters) != 1:
|
||||
src.fail(f"{scope.name}: expected one setting written from str(<path>)")
|
||||
setter, var = setters[0]
|
||||
keys = [spell(arg, env) for arg in setter.args[:-1]]
|
||||
if None in keys or len(keys) not in (1, 2):
|
||||
src.fail(f"{scope.name}: the TOS is written under a key that is not read")
|
||||
passes_to = f"[{keys[0]}] {keys[1]}" if len(keys) == 2 else f"core option {keys[0]}"
|
||||
return setter, var, passes_to
|
||||
|
||||
|
||||
@dataclass
|
||||
class _Cascade:
|
||||
"""What the branches between the TOS assignment and its setter decide."""
|
||||
|
||||
end: ast.stmt
|
||||
chosen: dict[str, str | None] = field(default_factory=dict)
|
||||
fallbacks: list[str] = field(default_factory=list)
|
||||
absolute: bool | None = None
|
||||
override: tuple[str, str] | None = None
|
||||
|
||||
|
||||
def _is_machine_branch(stmt: ast.If) -> bool:
|
||||
return (
|
||||
isinstance(stmt.test, ast.Compare)
|
||||
and isinstance(stmt.test.comparators[0], ast.Name)
|
||||
and stmt.test.comparators[0].id.startswith("MACHINE_")
|
||||
)
|
||||
|
||||
|
||||
def _machine_branches(
|
||||
src: Source, env: Mapping[str, str], stmt: ast.If, var: str, cascade: _Cascade
|
||||
) -> None:
|
||||
"""`if machine == MACHINE_X: var = ...` down its elif chain."""
|
||||
node: ast.If | None = stmt
|
||||
while node is not None:
|
||||
value = _assigns(node.body[0], var) if len(node.body) == 1 else None
|
||||
machine = node.test.comparators[0] if isinstance(node.test, ast.Compare) else None
|
||||
if value is None or not isinstance(machine, ast.Name):
|
||||
src.fail(f"line {node.lineno}: machine branch does not set {var}")
|
||||
cascade.chosen[machine.id] = spell(value, env)
|
||||
orelse = node.orelse
|
||||
node = orelse[0] if len(orelse) == 1 and isinstance(orelse[0], ast.If) else None
|
||||
|
||||
|
||||
def _existence_steps(
|
||||
cg: Configgen, src: Source, env: Mapping[str, str], stmt: ast.If, var: str,
|
||||
cascade: _Cascade,
|
||||
) -> None:
|
||||
"""`if not os.path.exists(var): var = ...`, each step nested in the last."""
|
||||
node: ast.If | None = stmt
|
||||
while node is not None:
|
||||
tested = _exists_arg(node.test)
|
||||
is_abs = isinstance(tested, ast.Name) and tested.id == var
|
||||
is_rel = (
|
||||
isinstance(tested, ast.Call)
|
||||
and ast.unparse(tested.func) == "os.path.join"
|
||||
and spell(tested.args[0], env) == cg.bios
|
||||
and ast.unparse(tested.args[1]) == var
|
||||
)
|
||||
if not (is_abs or is_rel) or (
|
||||
cascade.absolute is not None and cascade.absolute != is_abs
|
||||
):
|
||||
src.fail(f"line {node.lineno}: the cascade tests something else than {var}")
|
||||
cascade.absolute = is_abs
|
||||
value = _assigns(node.body[0], var)
|
||||
if value is None:
|
||||
src.fail(f"line {node.lineno}: cascade step does not set {var}")
|
||||
fallback = spell(value, env)
|
||||
if fallback is None:
|
||||
src.fail(f"line {node.lineno}: cascade step sets {var} to a path that is not read")
|
||||
cascade.fallbacks.append(fallback)
|
||||
inner = node.body[1:]
|
||||
node = inner[0] if len(inner) == 1 and isinstance(inner[0], ast.If) else None
|
||||
|
||||
|
||||
def _rom_override(src: Source, stmt: ast.If, var: str) -> tuple[str, ast.expr] | None:
|
||||
"""(marker, value) for `if "marker" in rom: var = value`."""
|
||||
if not (
|
||||
isinstance(stmt.test, ast.Compare)
|
||||
and isinstance(stmt.test.ops[0], ast.In)
|
||||
and ast.unparse(stmt.test.comparators[0]) in ("rom", "self.rom", "args.rom")
|
||||
and len(stmt.body) == 1
|
||||
):
|
||||
return None
|
||||
marker = string_constant(src, stmt.test.left, "rom path marker")
|
||||
value = _assigns(stmt.body[0], var)
|
||||
return None if marker is None or value is None else (marker, value)
|
||||
|
||||
|
||||
def _read_cascade(
|
||||
cg: Configgen, src: Source, env: Mapping[str, str], body: list[ast.stmt], index: int,
|
||||
setter_stmt: ast.stmt | None, var: str,
|
||||
) -> _Cascade:
|
||||
"""The machine choice, the existence cascade and the rom path override."""
|
||||
cascade = _Cascade(end=body[index])
|
||||
i = _skip_imports(body, index + 1)
|
||||
while i < len(body) and body[i] is not setter_stmt:
|
||||
stmt = body[i]
|
||||
if not isinstance(stmt, ast.If):
|
||||
src.fail(f"line {stmt.lineno}: unexpected statement in the TOS cascade")
|
||||
override = _rom_override(src, stmt, var)
|
||||
if _is_machine_branch(stmt):
|
||||
_machine_branches(src, env, stmt, var, cascade)
|
||||
elif _exists_arg(stmt.test) is not None:
|
||||
_existence_steps(cg, src, env, stmt, var, cascade)
|
||||
elif override is not None:
|
||||
value = spell(override[1], env)
|
||||
if value is None:
|
||||
src.fail(f"line {stmt.lineno}: rom path override sets {var} to a path that is not read")
|
||||
cascade.override = (override[0], value)
|
||||
else:
|
||||
src.fail(f"line {stmt.lineno}: unexpected branch in the TOS cascade")
|
||||
cascade.end = stmt
|
||||
i = _skip_imports(body, i + 1)
|
||||
return cascade
|
||||
|
||||
|
||||
def _machine_table(src: Source, scope: ast.FunctionDef) -> ast.stmt:
|
||||
"""The one dict display mapping rom paths to MACHINE_ constants."""
|
||||
dicts = [
|
||||
node for node in scope.body
|
||||
if isinstance(node, (ast.Assign, ast.AnnAssign)) and isinstance(node.value, ast.Dict)
|
||||
and all(isinstance(v, ast.Name) and v.id.startswith("MACHINE_") for v in node.value.values)
|
||||
]
|
||||
if len(dicts) != 1:
|
||||
src.fail(f"{scope.name}: no single rom path -> machine table")
|
||||
return dicts[0]
|
||||
|
||||
|
||||
def _machine_depends(src: Source, scope: ast.FunctionDef, table: ast.stmt) -> str:
|
||||
"""The machine comes from the rom path table, else from the config options read."""
|
||||
bound = {a.arg for a in scope.args.args} | {
|
||||
n for node in ast.walk(scope) if (n := _assigned_name(node))
|
||||
}
|
||||
options = [
|
||||
option for call in _calls(scope, attr="getInt")
|
||||
if call.args and (option := string_constant(src, call.args[0], "machine option")) is not None
|
||||
and isinstance(call.func, ast.Attribute)
|
||||
and isinstance(call.func.value, ast.Name) and call.func.value.id in bound
|
||||
]
|
||||
depends = f"machine read from the rom path through {_assigned_name(table)}"
|
||||
if options:
|
||||
depends += f", else option {', '.join(options)}"
|
||||
return depends
|
||||
|
||||
|
||||
def tos_cascade(cg: Configgen, src: Source, scope: ast.FunctionDef, emulator: str,
|
||||
build: str) -> list[Launcher]:
|
||||
"""A TOS path chosen per machine, then tried down an existence cascade."""
|
||||
env = cg.env(src, scope)
|
||||
setter, var, passes_to = _tos_setter(src, scope, env)
|
||||
|
||||
located = _locate(scope, lambda stmt: _assigns(stmt, var) is not None)
|
||||
if located is None:
|
||||
src.fail(f"{scope.name}: {var} is never assigned")
|
||||
body, index = located
|
||||
initial = spell(_assigns(body[index], var), env)
|
||||
setter_stmt = _outermost_stmt(body, setter)
|
||||
cascade = _read_cascade(cg, src, env, body, index, setter_stmt, var)
|
||||
machines = [
|
||||
(name, name.removeprefix("MACHINE_").replace("_", "").lower())
|
||||
for node in scope.body if (name := _assigned_name(node)) and name.startswith("MACHINE_")
|
||||
and name != "MACHINE_UNKNOWN"
|
||||
]
|
||||
absolute = cascade.absolute
|
||||
if (
|
||||
not cascade.chosen or not cascade.fallbacks or absolute is None or not machines
|
||||
or initial is None
|
||||
):
|
||||
src.fail(f"{scope.name}: no machine choice followed by an existence cascade")
|
||||
|
||||
def relative(value: str | None) -> str:
|
||||
name = cg.under_bios(value) if absolute else value
|
||||
if name is None:
|
||||
src.fail(f"{scope.name}: {value} is not under {cg.bios}")
|
||||
return name
|
||||
|
||||
tokens = [v for v in cascade.fallbacks if BUILTIN_TOKEN.fullmatch(posixpath.basename(v))]
|
||||
files = [relative(v) for v in cascade.fallbacks if v not in tokens]
|
||||
if tokens:
|
||||
passes_to += f" ({', '.join(tokens)} when none is found)"
|
||||
table = _machine_table(src, scope)
|
||||
depends = _machine_depends(src, scope, table)
|
||||
machine_lines = [n.lineno for n in scope.body if _assigned_name(n) in dict(machines)]
|
||||
if setter_stmt is None:
|
||||
src.fail(f"{scope.name}: the setting is not written in the block assigning {var}")
|
||||
read = {
|
||||
n.id for stmt in body[index:body.index(setter_stmt) + 1]
|
||||
for n in ast.walk(stmt) if isinstance(n, ast.Name)
|
||||
}
|
||||
helpers = [src.span(node) for node, name, value in assignments(scope.body)
|
||||
if name in read - {var} and spell(value, env) is not None]
|
||||
ref = src.ref([
|
||||
(min(machine_lines), max(machine_lines)),
|
||||
src.span(table),
|
||||
*helpers,
|
||||
(src.span(body[index])[0], max(end_line(cascade.end), end_line(setter))),
|
||||
])
|
||||
launchers = []
|
||||
for constant, slot in machines:
|
||||
first = relative(cascade.chosen.get(constant, initial))
|
||||
launchers.append(Launcher(
|
||||
emulator=emulator, build=build, kind="names_searched", slot=slot,
|
||||
names=list(dict.fromkeys([first, *files])), case_insensitive=False,
|
||||
search_dir=cg.bios, passes_to=passes_to, fails_when_missing=False,
|
||||
depends_on_option=depends, source_ref=ref,
|
||||
))
|
||||
override = cascade.override
|
||||
if override is not None and not BUILTIN_TOKEN.search(override[1]):
|
||||
launchers.append(Launcher(
|
||||
emulator=emulator, build=build, kind="fixed_name", slot=override[0],
|
||||
names=[relative(override[1])], case_insensitive=False, search_dir=cg.bios,
|
||||
passes_to=passes_to, fails_when_missing=False,
|
||||
depends_on_option=f'"{override[0]}" in the rom path', source_ref=ref,
|
||||
))
|
||||
return launchers
|
||||
|
||||
|
||||
def _outermost_stmt(body: list[ast.stmt], node: ast.AST) -> ast.stmt | None:
|
||||
for stmt in body:
|
||||
if any(child is node for child in ast.walk(stmt)):
|
||||
return stmt
|
||||
return None
|
||||
|
||||
|
||||
def hatari(cg: Configgen) -> list[Launcher]:
|
||||
src = cg.source(HATARI)
|
||||
return tos_cascade(cg, src, src.function("SetMachineAndBios"), cg.emulator(HATARI),
|
||||
"standalone")
|
||||
|
||||
|
||||
def hatari_libretro(cg: Configgen) -> list[Launcher]:
|
||||
src = cg.source(CORES)
|
||||
return [
|
||||
launcher for function in TOS_FUNCTIONS
|
||||
for launcher in tos_cascade(cg, src, src.function(function), cg.core(function), "libretro")
|
||||
]
|
||||
|
||||
|
||||
def _gsplus_tries(
|
||||
cg: Configgen, src: Source, env: Mapping[str, str], body: list[ast.stmt], index: int
|
||||
) -> tuple[list[str], str, ast.stmt]:
|
||||
"""The paths tried down the else chain, the key the found one is written to,
|
||||
and the last statement of the chain."""
|
||||
|
||||
def exists_of(test: ast.expr, var: str) -> bool:
|
||||
return (
|
||||
isinstance(test, ast.Call)
|
||||
and ast.unparse(test.func) == "os.path.exists"
|
||||
and ast.unparse(test.args[0]) == var
|
||||
)
|
||||
|
||||
names: list[str] = []
|
||||
key: str | None = None
|
||||
stmts, i = body, index
|
||||
while True:
|
||||
assigned = assigned_value(stmts[i])
|
||||
var = assigned[0] if assigned is not None else None
|
||||
name = cg.under_bios(spell(assigned[1], env)) if assigned is not None else None
|
||||
test = stmts[i + 1] if i + 1 < len(stmts) else None
|
||||
if name is None or not (
|
||||
isinstance(test, ast.If) and var is not None and exists_of(test.test, var)
|
||||
):
|
||||
src.fail(f"line {stmts[i].lineno}: path is not tried with os.path.exists")
|
||||
calls = [c for stmt in test.body if (c := expr_call(stmt))]
|
||||
for c in calls:
|
||||
if not isinstance(c.func, ast.Attribute):
|
||||
src.fail(f"line {c.lineno}: a call of the found branch is not a method call")
|
||||
written = [
|
||||
c for c in calls
|
||||
if isinstance(c.func, ast.Attribute) and c.func.attr == "setString"
|
||||
and ast.unparse(c.args[1]) == var
|
||||
]
|
||||
found = string(written[0].args[0]) if len(written) == 1 else None
|
||||
if found is None or (key is not None and found != key):
|
||||
src.fail(f"line {test.lineno}: the found path is not written to one key")
|
||||
key = found
|
||||
names.append(name)
|
||||
orelse = test.orelse
|
||||
if len(orelse) == 2 and isinstance(orelse[1], ast.If):
|
||||
stmts, i = orelse, 0
|
||||
continue
|
||||
removed = [
|
||||
c for stmt in orelse if (c := expr_call(stmt)) and is_setter_call(c, key, "removeOption")
|
||||
]
|
||||
if len(orelse) != 1 or not removed:
|
||||
src.fail(f"line {test.lineno}: the last miss does not remove {key}")
|
||||
return names, key, test
|
||||
|
||||
|
||||
def gsplus(cg: Configgen) -> list[Launcher]:
|
||||
"""A path tried with os.path.exists down an else chain, and the
|
||||
placeholders a per-game .gsplus file can name."""
|
||||
src = cg.source(GSPLUS)
|
||||
generate = src.function("generate")
|
||||
env = cg.env(src, generate)
|
||||
emulator = cg.emulator(GSPLUS)
|
||||
|
||||
located = _locate(generate, lambda stmt: (
|
||||
(assigned := assigned_value(stmt)) is not None
|
||||
and cg.under_bios(spell(assigned[1], env)) is not None
|
||||
))
|
||||
if located is None:
|
||||
src.fail("generate assigns no path under BIOS")
|
||||
body, index = located
|
||||
names, key, last = _gsplus_tries(cg, src, env, body, index)
|
||||
guard = next(
|
||||
node for node in ast.walk(generate)
|
||||
if isinstance(node, ast.If) and any(child is body[index] for child in node.orelse)
|
||||
)
|
||||
marker = string(guard.test.left) if isinstance(guard.test, ast.Compare) else None
|
||||
if marker is None:
|
||||
src.fail("the BIOS search is not the else of a rom path test")
|
||||
launchers = [Launcher(
|
||||
emulator=emulator, build="standalone", kind="names_searched", names=names,
|
||||
case_insensitive=False, search_dir=cg.bios, passes_to=key, fails_when_missing=False,
|
||||
depends_on_option=f'rom path without "{marker}"',
|
||||
source_ref=src.ref([(src.span(body[index])[0], end_line(last))]),
|
||||
)]
|
||||
for node in ast.walk(ast.Module(body=guard.body, type_ignores=[])):
|
||||
if not (
|
||||
isinstance(node, ast.If)
|
||||
and isinstance(node.test, ast.Compare)
|
||||
and isinstance(node.test.left, ast.Call)
|
||||
and is_setter_call(node.test.left, key, "getString")
|
||||
):
|
||||
continue
|
||||
placeholder = string_constant(src, node.test.comparators[0], "placeholder")
|
||||
if placeholder is None:
|
||||
continue
|
||||
written = [c for stmt in node.body if (c := expr_call(stmt)) and is_setter_call(c, key)]
|
||||
name = cg.under_bios(spell(written[0].args[1], env)) if len(written) == 1 else None
|
||||
if name is None:
|
||||
src.fail(f"line {node.lineno}: placeholder branch writes no BIOS path")
|
||||
launchers.append(Launcher(
|
||||
emulator=emulator, build="standalone", kind="fixed_name", slot=placeholder,
|
||||
names=[name], case_insensitive=False, search_dir=cg.bios, passes_to=key,
|
||||
fails_when_missing=False,
|
||||
depends_on_option=f'"{marker}" game file whose {key} is {placeholder}',
|
||||
source_ref=src.ref([(node.lineno, end_line(written[0]))]),
|
||||
))
|
||||
if len(launchers) == 1:
|
||||
src.fail("no placeholder of a .gsplus game file is replaced")
|
||||
return launchers
|
||||
@@ -0,0 +1,388 @@
|
||||
"""Recalbox's configgen at one tag, its string constants and the conditions of each setting write."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import ast
|
||||
import posixpath
|
||||
import re
|
||||
from collections.abc import Callable, Iterable, Iterator, Mapping
|
||||
from typing import Any
|
||||
|
||||
from .configgen import LauncherShapeError, Source, _calls, assigned_value
|
||||
from model.launcherrecords import join_emulators
|
||||
|
||||
|
||||
CONFIGGEN = "projects/configgen/configgen"
|
||||
GENERATORS = f"{CONFIGGEN}/generators"
|
||||
FILES_MODULE = f"{CONFIGGEN}/recalboxFiles.py"
|
||||
LAUNCHER = f"{CONFIGGEN}/emulatorlauncher.py"
|
||||
RETROARCH = f"{GENERATORS}/libretro/libretroRetroarch.py"
|
||||
CORES = f"{GENERATORS}/libretro/libretroCores.py"
|
||||
LIBRETRO_GENERATOR = f"{GENERATORS}/libretro/libretroGenerator.py"
|
||||
HATARI = f"{GENERATORS}/hatari/hatariGenerator.py"
|
||||
GSPLUS = f"{GENERATORS}/gsplus/gsplusGenerator.py"
|
||||
XROAR = f"{GENERATORS}/xroar/xroarGenerator.py"
|
||||
AMIBERRY_GENERATOR = f"{GENERATORS}/amiberry/amiberryGenerator.py"
|
||||
AMIBERRY_KICKSTARTS = f"{GENERATORS}/amiberry/amiberryKickstarts.py"
|
||||
AMIBERRY_SUBSYSTEMS = f"{GENERATORS}/amiberry/amiberrySubSystems.py"
|
||||
AMIBERRY_CONFIG = f"{GENERATORS}/amiberry/amiberryConfig.py"
|
||||
AMIBERRY_GLOBAL = f"{GENERATORS}/amiberry/amiberryGlobalConfig.py"
|
||||
PCSX2 = f"{GENERATORS}/pcsx2/pcsx2Generator.py"
|
||||
DOLPHIN = f"{GENERATORS}/dolphin/dolphinGenerator.py"
|
||||
XEMU = f"{GENERATORS}/xemu/xemuGenerator.py"
|
||||
MUPEN_GENERATOR = f"{GENERATORS}/mupen/mupenGenerator.py"
|
||||
MUPEN_CONFIG = f"{GENERATORS}/mupen/mupenConfig.py"
|
||||
|
||||
|
||||
# Recalbox's system.ini runs every libretro core as `emulator = libretro`:
|
||||
# the name a record carries when the code applies to any core.
|
||||
ALL_CORES = "libretro"
|
||||
SYSTEM_PLACEHOLDER = "<system>"
|
||||
SYSTEM_NAMES = ("self.system.Name", "system.Name")
|
||||
SYSTEM_DIRECTORY = "system_directory"
|
||||
CORE_ASSETS = "core_assets_directory"
|
||||
|
||||
# libretroCores functions that build a TOS path through a cascade.
|
||||
TOS_FUNCTIONS = ("configureAtariST", "configureAtariSTNew")
|
||||
# libretro core options whose value names the file the core opens.
|
||||
FILE_OPTIONS = {"o2em_bios": "o2em"}
|
||||
|
||||
# A name the core resolves itself, such as hatarib's <etos1024k>.
|
||||
BUILTIN_TOKEN = re.compile(r"<[^<>/]+>")
|
||||
|
||||
|
||||
def string(node: ast.AST | None) -> str | None:
|
||||
"""The value of a string constant."""
|
||||
if isinstance(node, ast.Constant) and isinstance(node.value, str):
|
||||
return node.value
|
||||
return None
|
||||
|
||||
|
||||
def string_constant(source: Source, node: ast.AST | None, what: str) -> str | None:
|
||||
"""The value of a string constant, None for any other node. A constant
|
||||
that is not a string is a shape the reader does not know."""
|
||||
if not isinstance(node, ast.Constant):
|
||||
return None
|
||||
if not isinstance(node.value, str):
|
||||
source.fail(f"line {node.lineno}: {what} is not a string: {node.value!r}")
|
||||
return node.value
|
||||
|
||||
|
||||
def assignments(
|
||||
nodes: Iterable[ast.AST],
|
||||
) -> Iterator[tuple[ast.Assign | ast.AnnAssign, str, ast.expr]]:
|
||||
"""Each single-name assignment among `nodes`, its name and its value."""
|
||||
for node in nodes:
|
||||
if isinstance(node, (ast.Assign, ast.AnnAssign)):
|
||||
assigned = assigned_value(node)
|
||||
if assigned is not None:
|
||||
yield node, assigned[0], assigned[1]
|
||||
|
||||
|
||||
def spell(node: ast.AST | None, env: Mapping[str, str]) -> str | None:
|
||||
"""The string an expression always evaluates to, if it can be read."""
|
||||
if isinstance(node, ast.Constant):
|
||||
return node.value if isinstance(node.value, str) else None
|
||||
if isinstance(node, (ast.Name, ast.Attribute)):
|
||||
return env.get(ast.unparse(node))
|
||||
if isinstance(node, ast.BinOp) and isinstance(node.op, ast.Add):
|
||||
left, right = spell(node.left, env), spell(node.right, env)
|
||||
return None if left is None or right is None else left + right
|
||||
if isinstance(node, ast.JoinedStr):
|
||||
parts = []
|
||||
for value in node.values:
|
||||
if isinstance(value, ast.FormattedValue):
|
||||
if value.conversion != -1 or value.format_spec is not None:
|
||||
return None
|
||||
value = value.value
|
||||
part = spell(value, env)
|
||||
if part is None:
|
||||
return None
|
||||
parts.append(part)
|
||||
return "".join(parts)
|
||||
if isinstance(node, ast.Call) and not node.keywords:
|
||||
spelled = [spell(arg, env) for arg in node.args]
|
||||
args = [arg for arg in spelled if arg is not None]
|
||||
if len(args) != len(spelled):
|
||||
return None
|
||||
func = ast.unparse(node.func)
|
||||
if func == "os.path.join" and args:
|
||||
return posixpath.join(*args)
|
||||
if func == "str" and len(args) == 1:
|
||||
return args[0]
|
||||
return None
|
||||
|
||||
|
||||
def module_strings(source: Source, prefix: str) -> dict[str, str]:
|
||||
"""Module-level string constants, keyed as `prefix.NAME`."""
|
||||
local: dict[str, str] = {}
|
||||
for _node, name, expr in assignments(source.tree.body):
|
||||
value = spell(expr, local)
|
||||
if value is not None:
|
||||
local[name] = value
|
||||
return {f"{prefix}.{name}": value for name, value in local.items()}
|
||||
|
||||
|
||||
def class_strings(source: Source, env: dict[str, str]) -> dict[str, Any]:
|
||||
"""Class attributes readable as strings or as tuples of strings."""
|
||||
found: dict[str, Any] = {}
|
||||
for cls in source.tree.body:
|
||||
if not isinstance(cls, ast.ClassDef):
|
||||
continue
|
||||
# The class body reads its own attributes by their bare names.
|
||||
bare: dict[str, str] = {}
|
||||
for _node, name, expr in assignments(cls.body):
|
||||
scope = {**env, **found, **bare}
|
||||
value: Any = spell(expr, scope)
|
||||
if value is None and isinstance(expr, ast.Tuple):
|
||||
items = [spell(e, scope) for e in expr.elts]
|
||||
value = items if all(isinstance(i, str) for i in items) else None
|
||||
if value is None:
|
||||
continue
|
||||
if isinstance(value, str):
|
||||
bare[name] = value
|
||||
for owner in ("self", cls.name):
|
||||
found[f"{owner}.{name}"] = value
|
||||
return found
|
||||
|
||||
|
||||
def _bound_once(scope: ast.AST, env: dict[str, str]) -> dict[str, str]:
|
||||
"""Names a function binds exactly once to a readable string."""
|
||||
counts: dict[str, int] = {}
|
||||
found = list(assignments(ast.walk(scope)))
|
||||
for _node, name, _expr in found:
|
||||
counts[name] = counts.get(name, 0) + 1
|
||||
local: dict[str, str] = {}
|
||||
for _node, name, expr in sorted(found, key=lambda item: item[0].lineno):
|
||||
if counts[name] == 1:
|
||||
value = spell(expr, {**env, **local})
|
||||
if value is not None:
|
||||
local[name] = value
|
||||
return local
|
||||
|
||||
|
||||
def launcher_names(source: Source) -> dict[str, list[str]]:
|
||||
"""Generator module -> the emulator names getGenerator loads it for."""
|
||||
names: dict[str, list[str]] = {}
|
||||
for node in ast.walk(source.function("getGenerator")):
|
||||
if not (
|
||||
isinstance(node, ast.If)
|
||||
and isinstance(node.test, ast.Compare)
|
||||
and isinstance(node.test.ops[0], ast.Eq)
|
||||
):
|
||||
continue
|
||||
emulator = string_constant(source, node.test.comparators[0], "emulator name")
|
||||
if emulator is None:
|
||||
continue
|
||||
for call in _calls(ast.Module(body=node.body, type_ignores=[]), name="__import__"):
|
||||
module = string_constant(source, call.args[0], "generator module") if call.args else None
|
||||
if module is not None:
|
||||
names.setdefault(module, []).append(emulator)
|
||||
if not names:
|
||||
source.fail("getGenerator imports no generator module")
|
||||
return names
|
||||
|
||||
|
||||
def handler_map(source: Source, function: str, table: str) -> dict[str, list[str]]:
|
||||
"""Function name -> the keys a dispatch table of `function` sends to it."""
|
||||
node = source.assignment(table, source.function(function)).value
|
||||
if not isinstance(node, ast.Dict):
|
||||
source.fail(f"{table} is not a dict display")
|
||||
handlers: dict[str, list[str]] = {}
|
||||
for key, value in zip(node.keys, node.values):
|
||||
name = string_constant(source, key, f"{table} key")
|
||||
if name is not None and isinstance(value, ast.Attribute):
|
||||
handlers.setdefault(value.attr, []).append(name)
|
||||
if not handlers:
|
||||
source.fail(f"{table} sends nothing to a handler")
|
||||
return handlers
|
||||
|
||||
|
||||
class Configgen:
|
||||
"""Recalbox's configgen at one tag, read through `read(path)`."""
|
||||
|
||||
def __init__(self, read: Callable[[str], str]) -> None:
|
||||
self._read = read
|
||||
self._sources: dict[str, Source] = {}
|
||||
files = self.source(FILES_MODULE)
|
||||
self.files = module_strings(files, "recalboxFiles")
|
||||
if "recalboxFiles.BIOS" not in self.files:
|
||||
files.fail("no BIOS path constant")
|
||||
self.bios = self.files["recalboxFiles.BIOS"]
|
||||
self._emulators = launcher_names(self.source(LAUNCHER))
|
||||
|
||||
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 emulator(self, path: str) -> str:
|
||||
"""The emulator names getGenerator loads the generator at `path` for."""
|
||||
module = "configgen." + path.removeprefix(f"{CONFIGGEN}/").removesuffix(".py")
|
||||
module = module.replace("/", ".")
|
||||
if module not in self._emulators:
|
||||
raise LauncherShapeError(f"{LAUNCHER}: no emulator loads {module}")
|
||||
return join_emulators(self._emulators[module])
|
||||
|
||||
def core(self, function: str) -> str:
|
||||
"""The libretro cores fillCoresConfiguration hands to `function`."""
|
||||
cores = handler_map(self.source(CORES), "fillCoresConfiguration", "specificCoreHandlers")
|
||||
if function not in cores:
|
||||
self.source(CORES).fail(f"no core is configured by {function}")
|
||||
return join_emulators(cores[function])
|
||||
|
||||
def env(self, source: Source, scope: ast.AST | None = None) -> dict[str, Any]:
|
||||
"""recalboxFiles, the module's class attributes and the strings
|
||||
`scope` binds once, with the system name left as a placeholder."""
|
||||
env: dict[str, Any] = dict(self.files)
|
||||
env.update(class_strings(source, env))
|
||||
env.update({name: SYSTEM_PLACEHOLDER for name in SYSTEM_NAMES})
|
||||
if scope is not None:
|
||||
env.update(_bound_once(scope, env))
|
||||
return env
|
||||
|
||||
def under_bios(self, value: str | None) -> str | None:
|
||||
"""`value` relative to the BIOS directory, or None outside it."""
|
||||
if value is None:
|
||||
return None
|
||||
value = value.strip("'\"")
|
||||
prefix = self.bios.rstrip("/") + "/"
|
||||
return value[len(prefix):] if value.startswith(prefix) else None
|
||||
|
||||
def bios_dir(self, value: str | None, source: Source, what: str) -> str:
|
||||
if value is None or not (value == self.bios or self.under_bios(value) is not None):
|
||||
source.fail(f"{what} is not a directory under {self.bios}")
|
||||
return value.rstrip("/")
|
||||
|
||||
|
||||
def is_setter_call(call: ast.Call, key: str, attr: str = "setString") -> bool:
|
||||
return (
|
||||
isinstance(call.func, ast.Attribute)
|
||||
and call.func.attr == attr
|
||||
and bool(call.args)
|
||||
and isinstance(call.args[0], ast.Constant)
|
||||
and call.args[0].value == key
|
||||
)
|
||||
|
||||
|
||||
def expr_call(stmt: ast.stmt) -> ast.Call | None:
|
||||
if isinstance(stmt, ast.Expr) and isinstance(stmt.value, ast.Call):
|
||||
return stmt.value
|
||||
return None
|
||||
|
||||
|
||||
def accepted_systems(
|
||||
source: Source, test: ast.expr, lists: Mapping[str, list[str]]
|
||||
) -> list[str] | None:
|
||||
"""The systems a `system.Name == x`, `or` or `in list` test accepts."""
|
||||
if isinstance(test, ast.BoolOp) and isinstance(test.op, ast.Or):
|
||||
parts = [accepted_systems(source, value, lists) for value in test.values]
|
||||
systems: list[str] = []
|
||||
for part in parts:
|
||||
if part is None:
|
||||
return None
|
||||
systems += part
|
||||
return systems
|
||||
if (
|
||||
isinstance(test, ast.Compare)
|
||||
and len(test.ops) == 1
|
||||
and ast.unparse(test.left) in SYSTEM_NAMES
|
||||
):
|
||||
right = test.comparators[0]
|
||||
system = string_constant(source, right, "system name")
|
||||
if isinstance(test.ops[0], ast.Eq) and system is not None:
|
||||
return [system]
|
||||
if isinstance(test.ops[0], ast.In) and isinstance(right, ast.Name) and right.id in lists:
|
||||
return list(lists[right.id])
|
||||
return None
|
||||
|
||||
|
||||
def _flag(test: ast.expr) -> str | None:
|
||||
"""X for a bare `self.system.X` test."""
|
||||
if isinstance(test, ast.Attribute) and ast.unparse(test.value) == "self.system":
|
||||
return test.attr
|
||||
return None
|
||||
|
||||
|
||||
def _condition(source: Source, tests: list[ast.expr], negated: bool,
|
||||
lists: Mapping[str, list[str]]) -> str:
|
||||
"""A branch condition in words, for the taken branch or the else."""
|
||||
systems: list[str] = []
|
||||
flags: list[str] = []
|
||||
for test in tests:
|
||||
found = accepted_systems(source, test, lists)
|
||||
flag = _flag(test)
|
||||
if found is not None:
|
||||
systems += found
|
||||
elif flag is not None:
|
||||
flags.append(flag)
|
||||
else:
|
||||
source.fail(f"line {test.lineno}: branch test {ast.unparse(test)} is not read")
|
||||
words = []
|
||||
if systems:
|
||||
words.append(("system other than " if negated else "system ") + ", ".join(systems))
|
||||
if flags:
|
||||
words.append(("without system flag " if negated else "system flag ") + ", ".join(flags))
|
||||
return ", ".join(words)
|
||||
|
||||
|
||||
def _is_elif(source: Source, node: ast.If) -> bool:
|
||||
return source.lines[node.lineno - 1].lstrip().startswith("elif")
|
||||
|
||||
|
||||
def _else_line(source: Source, first: ast.stmt) -> int:
|
||||
line = first.lineno - 1
|
||||
while line > 0 and source.lines[line - 1].strip() != "else:":
|
||||
line -= 1
|
||||
return line if line > 0 else first.lineno
|
||||
|
||||
|
||||
def setter_branches(
|
||||
source: Source, stmts: list[ast.stmt], key: str, lists: Mapping[str, list[str]]
|
||||
) -> list[tuple[str | None, ast.Call, int]]:
|
||||
"""(condition, setter call, first line) for each branch writing `key`."""
|
||||
found: list[tuple[str | None, ast.Call, int]] = []
|
||||
for stmt in stmts:
|
||||
call = expr_call(stmt)
|
||||
if call is not None and is_setter_call(call, key):
|
||||
found.append((None, call, stmt.lineno))
|
||||
continue
|
||||
if not isinstance(stmt, ast.If):
|
||||
if any(is_setter_call(c, key) for c in _calls(stmt, attr="setString")):
|
||||
source.fail(f"line {stmt.lineno}: {key} is written outside an if chain")
|
||||
continue
|
||||
node, tests = stmt, []
|
||||
while True:
|
||||
tests.append(node.test)
|
||||
found += _branch(source, node.body, key, _condition(source, [node.test], False, lists),
|
||||
node.lineno)
|
||||
orelse = node.orelse
|
||||
if len(orelse) == 1 and isinstance(orelse[0], ast.If) and _is_elif(source, orelse[0]):
|
||||
node = orelse[0]
|
||||
continue
|
||||
if orelse:
|
||||
found += _branch(source, orelse, key, _condition(source, tests, True, lists),
|
||||
_else_line(source, orelse[0]))
|
||||
break
|
||||
return found
|
||||
|
||||
|
||||
def _branch(
|
||||
source: Source, stmts: list[ast.stmt], key: str, condition: str, start: int
|
||||
) -> list[tuple[str | None, ast.Call, int]]:
|
||||
calls = [c for stmt in stmts if (c := expr_call(stmt)) is not None and is_setter_call(c, key)]
|
||||
nested = [c for stmt in stmts for c in _calls(stmt, attr="setString") if is_setter_call(c, key)]
|
||||
if len(calls) != len(nested) or len(calls) > 1:
|
||||
source.fail(f"line {start}: {key} is written in a nested branch")
|
||||
return [(condition, call, start) for call in calls]
|
||||
|
||||
|
||||
def local_string_lists(source: Source, scope: ast.AST) -> dict[str, tuple[list[str], ast.stmt]]:
|
||||
found: dict[str, tuple[list[str], ast.stmt]] = {}
|
||||
for node, name, value in assignments(ast.walk(scope)):
|
||||
if isinstance(value, ast.List):
|
||||
values = [text for e in value.elts
|
||||
if (text := string_constant(source, e, f"{name} item")) is not None]
|
||||
if len(values) == len(value.elts):
|
||||
found[name] = (values, node)
|
||||
return found
|
||||
@@ -0,0 +1,424 @@
|
||||
"""Recalbox standalone generators that search for or write a BIOS path, Amiberry to XRoar."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import ast
|
||||
from collections.abc import Mapping
|
||||
from functools import partial
|
||||
|
||||
from .configgen import (
|
||||
Launcher,
|
||||
LauncherShapeError,
|
||||
Source,
|
||||
_assigned_name,
|
||||
_calls,
|
||||
_enclosing_test,
|
||||
end_line,
|
||||
)
|
||||
from .recalbox_configgen import (
|
||||
AMIBERRY_CONFIG,
|
||||
AMIBERRY_GENERATOR,
|
||||
AMIBERRY_GLOBAL,
|
||||
AMIBERRY_KICKSTARTS,
|
||||
AMIBERRY_SUBSYSTEMS,
|
||||
CORES,
|
||||
Configgen,
|
||||
DOLPHIN,
|
||||
MUPEN_CONFIG,
|
||||
MUPEN_GENERATOR,
|
||||
PCSX2,
|
||||
SYSTEM_PLACEHOLDER,
|
||||
XEMU,
|
||||
XROAR,
|
||||
assignments,
|
||||
class_strings,
|
||||
expr_call,
|
||||
is_setter_call,
|
||||
string,
|
||||
accepted_systems,
|
||||
string_constant,
|
||||
spell,
|
||||
)
|
||||
|
||||
|
||||
def amiberry(cg: Configgen) -> list[Launcher]:
|
||||
"""BIOS_PER_SYSTEM tried in order, the AROS pair, then Amiberry's own."""
|
||||
kick = cg.source(AMIBERRY_KICKSTARTS)
|
||||
subsystems = class_strings(cg.source(AMIBERRY_SUBSYSTEMS), {})
|
||||
computers = subsystems.get("SubSystems.COMPUTERS")
|
||||
if not isinstance(computers, list):
|
||||
cg.source(AMIBERRY_SUBSYSTEMS).fail("SubSystems.COMPUTERS is not a tuple of systems")
|
||||
|
||||
helper = kick.function("AmigaBios")
|
||||
returned = helper.body[-1]
|
||||
if not (
|
||||
isinstance(returned, ast.Return)
|
||||
and isinstance(returned.value, ast.Call)
|
||||
and ast.unparse(returned.value.func) == "os.path.join"
|
||||
and ast.unparse(returned.value.args[-1]) == helper.args.args[0].arg
|
||||
):
|
||||
kick.fail("AmigaBios no longer joins a directory and the name")
|
||||
search_dir = cg.bios_dir(
|
||||
spell(ast.Call(func=returned.value.func, args=returned.value.args[:-1], keywords=[]),
|
||||
cg.env(kick)),
|
||||
kick, "AmigaBios",
|
||||
)
|
||||
|
||||
table = kick.assignment("BIOS_PER_SYSTEM")
|
||||
if not isinstance(table.value, ast.Dict):
|
||||
kick.fail("BIOS_PER_SYSTEM is not a dict display")
|
||||
chooser = kick.function("GetKickstartsFor")
|
||||
messages = [
|
||||
message for node in ast.walk(chooser)
|
||||
if isinstance(node, ast.Raise) and isinstance(node.exc, ast.Call)
|
||||
and node.exc.args
|
||||
and (message := string_constant(kick, node.exc.args[0], "failure message")) is not None
|
||||
]
|
||||
aros = [
|
||||
aros_name for call in _calls(chooser, name="AmigaBios")
|
||||
if call.args and (aros_name := string_constant(kick, call.args[0], "AROS name")) is not None
|
||||
]
|
||||
builtin = [
|
||||
rom for node in ast.walk(chooser)
|
||||
if isinstance(node, ast.Assign) and ast.unparse(node.targets[0]) == "self.rom"
|
||||
and (rom := string_constant(kick, node.value, "built-in rom")) is not None
|
||||
]
|
||||
if len(messages) != 2 or len(aros) != 2 or len(builtin) != 1:
|
||||
kick.fail("GetKickstartsFor no longer has two failures, the AROS pair and a built-in")
|
||||
config = cg.source(AMIBERRY_CONFIG)
|
||||
setter = config.function("SetKickstarts")
|
||||
keys = [setting for c in _calls(setter, attr="setString")
|
||||
if (setting := string_constant(config, c.args[0], "kickstart key")) is not None]
|
||||
if len(keys) != 2:
|
||||
config.fail("SetKickstarts no longer writes a kickstart and an extended ROM")
|
||||
rom_key, ext_key = keys
|
||||
tail = [(helper.lineno, end_line(helper)), (chooser.lineno, end_line(chooser))]
|
||||
config_ref = config.ref([(setter.lineno, end_line(setter))])
|
||||
|
||||
emulator = cg.emulator(AMIBERRY_GENERATOR)
|
||||
launchers = []
|
||||
for key, value in zip(table.value.keys, table.value.values):
|
||||
system = subsystems.get(ast.unparse(key)) if key is not None else None
|
||||
if not isinstance(system, str) or not isinstance(value, ast.List):
|
||||
kick.fail(f"line {table.lineno}: BIOS_PER_SYSTEM key is not a SubSystems name")
|
||||
for entry in value.elts:
|
||||
if not (isinstance(entry, ast.Tuple) and len(entry.elts) == 2
|
||||
and isinstance(entry.elts[0], ast.List)):
|
||||
kick.fail(f"line {entry.lineno}: entry is not (rom types, names)")
|
||||
types = ", ".join(ast.unparse(t).removeprefix("RomType.") for t in entry.elts[0].elts)
|
||||
names = kick.literal(entry.elts[1], "kickstart names")
|
||||
ref = f"{kick.ref([kick.span(entry), *tail])}, {config_ref}"
|
||||
make = partial(Launcher, emulator=emulator, build="standalone", slot=system,
|
||||
case_insensitive=False, search_dir=search_dir,
|
||||
depends_on_option=f"rom type {types}", source_ref=ref)
|
||||
if any("|" in name for name in names):
|
||||
if len(names) != 1:
|
||||
kick.fail(f"line {entry.lineno}: several kickstart pairs are not read")
|
||||
launchers.append(make(
|
||||
kind="fixed_name", names=names[0].split("|"),
|
||||
passes_to=f"{rom_key}, {ext_key}",
|
||||
fails_when_missing=", ".join(messages),
|
||||
))
|
||||
else:
|
||||
launchers.append(make(
|
||||
kind="names_searched", names=names, passes_to=rom_key,
|
||||
fails_when_missing=False if system in computers else messages[0],
|
||||
))
|
||||
launchers.append(Launcher(
|
||||
emulator=emulator, build="standalone", kind="fixed_name", slot=", ".join(computers),
|
||||
names=aros, case_insensitive=False, search_dir=search_dir,
|
||||
passes_to=f"{rom_key}, {ext_key} ({builtin[0]} built in when either is missing)",
|
||||
fails_when_missing=False, depends_on_option="none of the listed kickstarts found",
|
||||
source_ref=f"{kick.ref(tail)}, {config_ref}",
|
||||
))
|
||||
launchers.append(_amiberry_rom_path(cg, emulator))
|
||||
return launchers
|
||||
|
||||
|
||||
def _amiberry_rom_path(cg: Configgen, emulator: str) -> Launcher:
|
||||
"""amiberry.conf rom_path, the folder Amiberry scans for every ROM."""
|
||||
src = cg.source(AMIBERRY_GLOBAL)
|
||||
create = src.function("createGlobalSettings")
|
||||
found = [c for c in _calls(create, attr="setString") if is_setter_call(c, "rom_path")]
|
||||
if len(found) != 1 or len(found[0].args) != 2:
|
||||
src.fail(f"expected one rom_path setter, found {len(found)}")
|
||||
call = found[0]
|
||||
directory = cg.bios_dir(spell(call.args[1], cg.env(src, create)), src, "rom_path")
|
||||
return Launcher(
|
||||
emulator=emulator, build="standalone", kind="passes_path", names=[],
|
||||
search_dir=directory, passes_to="written: rom_path in amiberry.conf",
|
||||
source_ref=src.ref([(call.lineno, end_line(call))]),
|
||||
)
|
||||
|
||||
|
||||
def _ps2_exists_helper(
|
||||
cg: Configgen, src: Source, env: Mapping[str, str], chooser: ast.FunctionDef
|
||||
) -> tuple[str, str]:
|
||||
"""The directory the nested existence helper joins a name to, and its name."""
|
||||
exists = next((f for f in chooser.body if isinstance(f, ast.FunctionDef)), None)
|
||||
returned = exists.body[-1] if exists is not None else None
|
||||
joined = returned.value.args[0] if isinstance(returned, ast.Return) \
|
||||
and isinstance(returned.value, ast.Call) and returned.value.args else None
|
||||
if exists is None or not (
|
||||
isinstance(joined, ast.Call) and ast.unparse(joined.func) == "os.path.join"
|
||||
and ast.unparse(joined.args[-1]) == exists.args.args[0].arg
|
||||
):
|
||||
src.fail("__CheckPs2Bios has no existence helper joining a directory and a name")
|
||||
search_dir = cg.bios_dir(
|
||||
spell(ast.Call(func=joined.func, args=joined.args[:-1], keywords=[]), env), src, "Exists"
|
||||
)
|
||||
return search_dir, exists.name
|
||||
|
||||
|
||||
def _region_branch(node: ast.If, helper: str) -> tuple[str, ast.expr, ast.expr | None] | None:
|
||||
"""(token, name tested, name returned) for `if token in rom and Exists(name): return x`."""
|
||||
test = node.test
|
||||
if not (
|
||||
isinstance(test, ast.BoolOp) and isinstance(test.op, ast.And) and len(test.values) == 2
|
||||
):
|
||||
return None
|
||||
compare, call = test.values
|
||||
token = string(compare.left) if isinstance(compare, ast.Compare) else None
|
||||
if not (
|
||||
token is not None
|
||||
and isinstance(call, ast.Call)
|
||||
and ast.unparse(call.func) == helper
|
||||
and len(node.body) == 1 and isinstance(node.body[0], ast.Return)
|
||||
):
|
||||
return None
|
||||
return token, call.args[0], node.body[0].value
|
||||
|
||||
|
||||
def _ps2_region_groups(
|
||||
src: Source, env: Mapping[str, str], chooser: ast.FunctionDef, helper: str
|
||||
) -> dict[tuple[str, str], list[str]]:
|
||||
"""(name returned, name tested) -> the rom name tokens that pick it."""
|
||||
groups: dict[tuple[str, str], list[str]] = {}
|
||||
node = next((s for s in chooser.body if isinstance(s, ast.If)), None)
|
||||
while node is not None:
|
||||
branch = _region_branch(node, helper)
|
||||
if branch is None:
|
||||
src.fail(f"line {node.lineno}: region branch is not `token in rom and Exists(name)`")
|
||||
token, tested_node, given_node = branch
|
||||
tested = spell(tested_node, env)
|
||||
given = spell(given_node, env)
|
||||
if tested is None or given is None:
|
||||
src.fail(f"line {node.lineno}: region branch names no BIOS constant")
|
||||
groups.setdefault((given, tested), []).append(token)
|
||||
orelse = node.orelse
|
||||
node = orelse[0] if len(orelse) == 1 and isinstance(orelse[0], ast.If) else None
|
||||
return groups
|
||||
|
||||
|
||||
def pcsx2(cg: Configgen) -> list[Launcher]:
|
||||
"""A region token of the rom name picks a BIOS, then a fixed order."""
|
||||
src = cg.source(PCSX2)
|
||||
env = cg.env(src)
|
||||
chooser = src.function("__CheckPs2Bios")
|
||||
search_dir, helper = _ps2_exists_helper(cg, src, env, chooser)
|
||||
|
||||
groups = _ps2_region_groups(src, env, chooser, helper)
|
||||
loops = [
|
||||
(s, s.iter) for s in chooser.body
|
||||
if isinstance(s, ast.For) and isinstance(s.iter, ast.Tuple)
|
||||
]
|
||||
if not groups or len(loops) != 1:
|
||||
src.fail("__CheckPs2Bios no longer tries region tokens then a fixed order")
|
||||
loop, names = loops[0]
|
||||
fallback = [name for e in names.elts if (name := spell(e, env)) is not None]
|
||||
if len(fallback) != len(names.elts):
|
||||
src.fail(f"line {loop.lineno}: fallback names are not BIOS constants")
|
||||
|
||||
writes = [
|
||||
call for call in _calls(src.tree, attr="setString")
|
||||
if len(call.args) == 3 and isinstance(call.args[2], ast.Call)
|
||||
and isinstance(call.args[2].func, ast.Attribute)
|
||||
and call.args[2].func.attr == chooser.name
|
||||
]
|
||||
section = spell(writes[0].args[0], env) if len(writes) == 1 else None
|
||||
key = spell(writes[0].args[1], env) if len(writes) == 1 else None
|
||||
if section is None or key is None:
|
||||
src.fail("the chosen BIOS is not written to one config key")
|
||||
constants = {v: k.removeprefix("self.").removeprefix("Pcsx2Generator.")
|
||||
for k, v in env.items() if k.startswith("Pcsx2Generator.BIOS_")}
|
||||
names_lines = [node.lineno for node, name, _value in assignments(ast.walk(src.tree))
|
||||
if name in set(constants.values())]
|
||||
ref = src.ref([(min(names_lines), max(names_lines)), (chooser.lineno, end_line(chooser)),
|
||||
(writes[0].lineno, end_line(writes[0]))])
|
||||
make = partial(Launcher, emulator=cg.emulator(PCSX2), build="standalone",
|
||||
case_insensitive=False, search_dir=search_dir,
|
||||
passes_to=f"[{section}] {key}", fails_when_missing=False, source_ref=ref)
|
||||
launchers = []
|
||||
for (given, tested), tokens in groups.items():
|
||||
slot = constants.get(given, given).removeprefix("BIOS_")
|
||||
depends = f"rom name contains {', '.join(tokens)}"
|
||||
if tested == given:
|
||||
launchers.append(make(
|
||||
kind="names_searched", slot=slot,
|
||||
names=list(dict.fromkeys([given, *fallback])),
|
||||
depends_on_option=depends,
|
||||
))
|
||||
else:
|
||||
# The name written is not the one tested: no search, one name.
|
||||
launchers.append(make(
|
||||
kind="fixed_name", slot=slot, names=[given],
|
||||
depends_on_option=f"{depends} and {tested} is present",
|
||||
))
|
||||
launchers.append(make(
|
||||
kind="names_searched", slot="default", names=fallback,
|
||||
depends_on_option="rom name with no region token, or its BIOS absent",
|
||||
))
|
||||
return launchers
|
||||
|
||||
|
||||
def _presence(cg: Configgen, src: Source, scope: ast.FunctionDef) -> tuple[list[str], ast.If]:
|
||||
"""Paths tested with `os.path.exists(a) or os.path.exists(b) ...`."""
|
||||
env = cg.env(src, scope)
|
||||
for node in ast.walk(scope):
|
||||
if not (isinstance(node, ast.If) and isinstance(node.test, ast.BoolOp)
|
||||
and isinstance(node.test.op, ast.Or)):
|
||||
continue
|
||||
found = [
|
||||
cg.under_bios(spell(value.args[0], env)) for value in node.test.values
|
||||
if isinstance(value, ast.Call) and ast.unparse(value.func) == "os.path.exists"
|
||||
]
|
||||
names = [name for name in found if name is not None]
|
||||
if names and len(names) == len(node.test.values) and len(names) == len(found):
|
||||
return names, node
|
||||
raise LauncherShapeError(f"{src.path}: {scope.name}: no presence test of BIOS paths")
|
||||
|
||||
|
||||
def _returned(stmts: list[ast.stmt]) -> str | None:
|
||||
if len(stmts) == 1 and isinstance(stmts[0], ast.Return):
|
||||
return string(stmts[0].value)
|
||||
return None
|
||||
|
||||
|
||||
def dolphin(cg: Configgen) -> list[Launcher]:
|
||||
"""The IPL is only tested for presence, to decide whether to skip it."""
|
||||
src = cg.source(DOLPHIN)
|
||||
env = cg.env(src)
|
||||
checker = src.function("CheckGamecubeIpl")
|
||||
names, test = _presence(cg, src, checker)
|
||||
found, missing = _returned(test.body), _returned(test.orelse)
|
||||
calls = [
|
||||
(call, bound.id) for call in _calls(src.tree, attr="setString")
|
||||
if len(call.args) == 3 and isinstance(bound := call.args[2], ast.Name)
|
||||
and any(
|
||||
name == bound.id and isinstance(value, ast.Call)
|
||||
and isinstance(value.func, ast.Attribute) and value.func.attr == checker.name
|
||||
for _node, name, value in assignments(ast.walk(src.tree))
|
||||
)
|
||||
]
|
||||
if found is None or missing is None or len(calls) != 1:
|
||||
src.fail("CheckGamecubeIpl's answer is not written to one config key")
|
||||
call, answer = calls[0]
|
||||
section, key = spell(call.args[0], env), spell(call.args[1], env)
|
||||
binding = next(node for node, name, _value in assignments(ast.walk(src.tree))
|
||||
if name == answer)
|
||||
standalone = Launcher(
|
||||
emulator=cg.emulator(DOLPHIN), build="standalone", kind="fixed_name", names=names,
|
||||
case_insensitive=False, search_dir=cg.bios,
|
||||
passes_to=f"[{section}] {key} ({found} when one is present, else {missing})",
|
||||
fails_when_missing=False,
|
||||
source_ref=src.ref([(checker.lineno, end_line(checker)), src.span(binding),
|
||||
(call.lineno, end_line(call))]),
|
||||
)
|
||||
cores = cg.source(CORES)
|
||||
configure = cores.function("configureDolphin")
|
||||
names, test = _presence(cg, cores, configure)
|
||||
options = [(option, value) for branch in (test.body, test.orelse)
|
||||
for stmt in branch if (c := expr_call(stmt)) and len(c.args) == 2
|
||||
and (option := string_constant(cores, c.args[0], "core option")) is not None
|
||||
and (value := string_constant(cores, c.args[1], "core option value")) is not None]
|
||||
if len(options) != 2 or options[0][0] != options[1][0]:
|
||||
cores.fail("configureDolphin's presence test does not set one core option both ways")
|
||||
option = options[0][0]
|
||||
on, off = (value.strip('"') for _o, value in options)
|
||||
first = min(node.lineno for node, _name, value in assignments(ast.walk(configure))
|
||||
if cg.under_bios(spell(value, cg.env(cores, configure))) is not None)
|
||||
libretro = Launcher(
|
||||
emulator=cg.core("configureDolphin"), build="libretro", kind="fixed_name", names=names,
|
||||
case_insensitive=False, search_dir=cg.bios,
|
||||
passes_to=f"core option {option} ({on} when one is present, else {off})",
|
||||
fails_when_missing=False, source_ref=cores.ref([(first, end_line(test))]),
|
||||
)
|
||||
return [standalone, libretro]
|
||||
|
||||
|
||||
def _config_paths(cg: Configgen, path: str, emulator: str) -> Launcher:
|
||||
"""setString(section, key, <path under BIOS>) calls of one module."""
|
||||
src = cg.source(path)
|
||||
writes = []
|
||||
for function in (n for n in ast.walk(src.tree) if isinstance(n, ast.FunctionDef)):
|
||||
env = cg.env(src, function)
|
||||
for call in _calls(function, attr="setString"):
|
||||
if len(call.args) != 3:
|
||||
continue
|
||||
section, key = spell(call.args[0], env), spell(call.args[1], env)
|
||||
name = cg.under_bios(spell(call.args[2], env))
|
||||
if section is not None and key is not None and name is not None:
|
||||
writes.append((function, call, section, key, name))
|
||||
if not writes:
|
||||
src.fail("writes no BIOS path into its config")
|
||||
conditions: list[str] = []
|
||||
spans: list[tuple[int, int]] = []
|
||||
for function, call, *_rest in writes:
|
||||
spans.append((call.lineno, end_line(call)))
|
||||
test = next(
|
||||
(n for n in ast.walk(function) if isinstance(n, ast.If)
|
||||
and any(child is call for stmt in n.body for child in ast.walk(stmt))), None,
|
||||
)
|
||||
if test is not None:
|
||||
spans.append((test.lineno, test.lineno))
|
||||
systems = accepted_systems(src, test.test, {})
|
||||
words = f"system {', '.join(systems)}" if systems else _enclosing_test(function, call)
|
||||
if words is not None and words not in conditions:
|
||||
conditions.append(words)
|
||||
read = {ast.unparse(n) for arg in call.args for n in ast.walk(arg)
|
||||
if isinstance(n, (ast.Name, ast.Attribute))}
|
||||
spans += [src.span(n) for n in function.body
|
||||
if _assigned_name(n) is not None and _assigned_name(n) in read]
|
||||
spans += [src.span(n) for cls in src.tree.body if isinstance(cls, ast.ClassDef)
|
||||
for n in cls.body if _assigned_name(n) is not None
|
||||
and {f"self.{_assigned_name(n)}", f"{cls.name}.{_assigned_name(n)}"} & read]
|
||||
return Launcher(
|
||||
emulator=emulator, build="standalone", kind="fixed_name",
|
||||
names=list(dict.fromkeys(name for *_rest, name in writes)), case_insensitive=False,
|
||||
search_dir=cg.bios,
|
||||
passes_to=", ".join(dict.fromkeys(f"[{s}] {k}" for _f, _c, s, k, _n in writes)),
|
||||
fails_when_missing=False, depends_on_option=", ".join(conditions) or None,
|
||||
source_ref=src.ref(spans),
|
||||
)
|
||||
|
||||
|
||||
def xemu(cg: Configgen) -> list[Launcher]:
|
||||
return [_config_paths(cg, XEMU, cg.emulator(XEMU))]
|
||||
|
||||
|
||||
def mupen64plus(cg: Configgen) -> list[Launcher]:
|
||||
return [_config_paths(cg, MUPEN_CONFIG, cg.emulator(MUPEN_GENERATOR))]
|
||||
|
||||
|
||||
def xroar(cg: Configgen) -> list[Launcher]:
|
||||
"""-rompath os.path.join(recalboxFiles.BIOS, args.system) on the command line."""
|
||||
src = cg.source(XROAR)
|
||||
generate = src.function("generate")
|
||||
# args.system is the ES system name, as self.system.Name is elsewhere.
|
||||
env = {**cg.env(src, generate), "args.system": SYSTEM_PLACEHOLDER}
|
||||
found = [
|
||||
(flag, value)
|
||||
for node in ast.walk(generate)
|
||||
if isinstance(node, ast.List)
|
||||
for flag, value in zip(node.elts, node.elts[1:])
|
||||
if isinstance(flag, ast.Constant) and flag.value == "-rompath"
|
||||
]
|
||||
if len(found) != 1:
|
||||
src.fail(f"expected one -rompath on the command line, found {len(found)}")
|
||||
flag, value = found[0]
|
||||
directory = cg.bios_dir(spell(value, env), src, "-rompath")
|
||||
return [Launcher(
|
||||
emulator=cg.emulator(XROAR), build="standalone", kind="passes_path", names=[],
|
||||
search_dir=directory, passes_to="command line -rompath",
|
||||
source_ref=src.ref([(flag.lineno, value.end_lineno or value.lineno)]),
|
||||
)]
|
||||
@@ -0,0 +1,186 @@
|
||||
"""RetroBat's launcher layer, read from emulatorLauncher's C# generators.
|
||||
|
||||
emulatorLauncher decides, per emulator, which file names it looks for in the
|
||||
BIOS directory, in what order, and what it writes into the emulator's
|
||||
configuration. The C# is read as text, never compiled: each extractor targets
|
||||
one construct the generators use and raises LauncherPatternMissing when that
|
||||
construct is gone, so an upstream rewrite stops the scrape instead of
|
||||
publishing an empty list.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable
|
||||
|
||||
from resolve.launcherrefs import is_feature_ref, split_ref
|
||||
from .csharp_source import (
|
||||
LauncherPatternMissing,
|
||||
Record,
|
||||
Source,
|
||||
)
|
||||
from .retrobat_arguments import mame, pico8, portable_users, psxmame, xroar
|
||||
from .retrobat_computers import amiberry, hatari, hatari_libretro, openmsx, winuae
|
||||
from .retrobat_config_files import (
|
||||
ares,
|
||||
bizhawk_gb,
|
||||
blastem,
|
||||
desmume,
|
||||
dolphin,
|
||||
gsplus,
|
||||
jzintv,
|
||||
melonds_dsi,
|
||||
mesen,
|
||||
raine,
|
||||
rpcs3,
|
||||
)
|
||||
from .retrobat_config_folders import (
|
||||
arcadeduck,
|
||||
bsyndrome,
|
||||
capsimg,
|
||||
demul,
|
||||
dosbox_copies,
|
||||
eka2l1,
|
||||
fbneo,
|
||||
snes9x,
|
||||
tsugaru,
|
||||
value_folders,
|
||||
xm6pro,
|
||||
)
|
||||
from .retrobat_generators import FEATURES, GENERATORS, guarded_writes
|
||||
from .retrobat_playstation import duckstation, pcsx2, pcsx2_libretro, psx_cascades
|
||||
from .retrobat_render import option_paths
|
||||
from .retrobat_xbox import cxbx, xemu, xemu_saves
|
||||
|
||||
|
||||
SOURCE_FILES = (
|
||||
f"{GENERATORS}/Amiberry.Generator.cs",
|
||||
f"{GENERATORS}/ArcadeDuck.Database.cs",
|
||||
f"{GENERATORS}/ArcadeDuck.Generator.cs",
|
||||
f"{GENERATORS}/Ares.Generator.cs",
|
||||
f"{GENERATORS}/Bizhawk.CoreOptions.cs",
|
||||
f"{GENERATORS}/Bizhawk.Generator.cs",
|
||||
f"{GENERATORS}/Blastem.Generator.cs",
|
||||
f"{GENERATORS}/Citron.Generator.cs",
|
||||
f"{GENERATORS}/Cxbx.Generator.cs",
|
||||
f"{GENERATORS}/Demul.Generator.cs",
|
||||
f"{GENERATORS}/Desmume.Generator.cs",
|
||||
f"{GENERATORS}/Dolphin.Generator.cs",
|
||||
f"{GENERATORS}/DosBoxPure.Generator.cs",
|
||||
f"{GENERATORS}/DosBoxStaging.Generator.cs",
|
||||
f"{GENERATORS}/Duckstation.Generator.cs",
|
||||
f"{GENERATORS}/Eden.Generator.cs",
|
||||
f"{GENERATORS}/Eka2l1.Generator.cs",
|
||||
f"{GENERATORS}/Fbneo.Generator.cs",
|
||||
f"{GENERATORS}/Flycast.Generator.cs",
|
||||
f"{GENERATORS}/GsPlus.Generator.cs",
|
||||
f"{GENERATORS}/Hatari.Generator.cs",
|
||||
f"{GENERATORS}/Jgenesis.Generator.cs",
|
||||
f"{GENERATORS}/Jzintv.Generator.cs",
|
||||
f"{GENERATORS}/KegaFusion.Generator.cs",
|
||||
f"{GENERATORS}/Kronos.Generator.cs",
|
||||
f"{GENERATORS}/LibRetro.CoreOptions.cs",
|
||||
f"{GENERATORS}/LibRetro.Generator.cs",
|
||||
f"{GENERATORS}/Mame64.Generator.cs",
|
||||
f"{GENERATORS}/Mednafen.Generator.cs",
|
||||
f"{GENERATORS}/MelonDS.Generator.cs",
|
||||
f"{GENERATORS}/Mesen.Generator.cs",
|
||||
f"{GENERATORS}/MessSystem.cs",
|
||||
f"{GENERATORS}/Mupen64.Generator.cs",
|
||||
f"{GENERATORS}/OpenMSX.Generator.cs",
|
||||
f"{GENERATORS}/PSXMame.Generator.cs",
|
||||
f"{GENERATORS}/Pcsx2.Generator.cs",
|
||||
f"{GENERATORS}/Pico8.Generator.cs",
|
||||
f"{GENERATORS}/PortsLauncher.Configuration.cs",
|
||||
f"{GENERATORS}/Project64.Generator.cs",
|
||||
f"{GENERATORS}/Raine.Generator.cs",
|
||||
f"{GENERATORS}/Rpcs3.Generator.cs",
|
||||
f"{GENERATORS}/Ryujinx.Generator.cs",
|
||||
f"{GENERATORS}/SSF.Generator.cs",
|
||||
f"{GENERATORS}/ScummVm.Generator.cs",
|
||||
f"{GENERATORS}/ShadPS4.Generator.cs",
|
||||
f"{GENERATORS}/Snes9x.Generator.cs",
|
||||
f"{GENERATORS}/Sudachi.Generator.cs",
|
||||
f"{GENERATORS}/Tsugaru.Generator.cs",
|
||||
f"{GENERATORS}/Uae.Generator.cs",
|
||||
f"{GENERATORS}/Xemu.Generator.cs",
|
||||
f"{GENERATORS}/Xm6pro.Generator.cs",
|
||||
f"{GENERATORS}/Xroar.Generator.cs",
|
||||
f"{GENERATORS}/Yabasanshiro.Generator.cs",
|
||||
f"{GENERATORS}/Ymir.Generator.cs",
|
||||
f"{GENERATORS}/Yuzu.Generator.cs",
|
||||
f"{GENERATORS}/mGBA.Generator.cs",
|
||||
FEATURES,
|
||||
)
|
||||
|
||||
|
||||
EXTRACTORS: tuple[Callable[[dict[str, Source]], list[Record]], ...] = (
|
||||
amiberry,
|
||||
arcadeduck,
|
||||
ares,
|
||||
bizhawk_gb,
|
||||
blastem,
|
||||
bsyndrome,
|
||||
capsimg,
|
||||
cxbx,
|
||||
demul,
|
||||
desmume,
|
||||
dolphin,
|
||||
dosbox_copies,
|
||||
duckstation,
|
||||
eka2l1,
|
||||
fbneo,
|
||||
gsplus,
|
||||
guarded_writes,
|
||||
hatari,
|
||||
hatari_libretro,
|
||||
jzintv,
|
||||
mame,
|
||||
melonds_dsi,
|
||||
mesen,
|
||||
openmsx,
|
||||
option_paths,
|
||||
pcsx2,
|
||||
pcsx2_libretro,
|
||||
pico8,
|
||||
portable_users,
|
||||
psx_cascades,
|
||||
psxmame,
|
||||
raine,
|
||||
rpcs3,
|
||||
snes9x,
|
||||
tsugaru,
|
||||
value_folders,
|
||||
winuae,
|
||||
xemu,
|
||||
xemu_saves,
|
||||
xm6pro,
|
||||
xroar,
|
||||
)
|
||||
|
||||
|
||||
def extract_launchers(texts: dict[str, str]) -> list[Record]:
|
||||
"""Every launcher record the extractors find, in extractor order."""
|
||||
missing = [path for path in SOURCE_FILES if path not in texts]
|
||||
if missing:
|
||||
raise LauncherPatternMissing(missing[0], "source file")
|
||||
sources = {path: Source(path, text) for path, text in texts.items()}
|
||||
return [
|
||||
_choices_apart(record) for extractor in EXTRACTORS for record in extractor(sources)
|
||||
]
|
||||
|
||||
|
||||
def _choices_apart(record: Record) -> Record:
|
||||
"""The es_features.cfg part of a record's source_ref, moved to choices_from.
|
||||
|
||||
The feature file lists the values a menu option offers. The generator
|
||||
writing the choice is the record's evidence, never the list.
|
||||
"""
|
||||
parts = split_ref(str(record["source_ref"]))
|
||||
listed = [p for p in parts if is_feature_ref(p)]
|
||||
if not listed:
|
||||
return record
|
||||
code = [p for p in parts if not is_feature_ref(p)]
|
||||
if not code:
|
||||
raise LauncherPatternMissing(listed[0], "generator code beside the option list")
|
||||
moved = {k: v for k, v in record.items() if k != "source_ref"}
|
||||
return {**moved, "choices_from": ", ".join(listed), "source_ref": ", ".join(code)}
|
||||
@@ -0,0 +1,344 @@
|
||||
"""RetroBat generators that hand a BIOS path on the command line or a folder beside the binary."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
from .csharp_source import (
|
||||
LauncherPatternMissing,
|
||||
Record,
|
||||
STRING,
|
||||
Source,
|
||||
_call_args,
|
||||
_code,
|
||||
_method_of,
|
||||
_statement_start,
|
||||
_unescape,
|
||||
source_ref,
|
||||
)
|
||||
from .retrobat_generators import FEATURES, GENERATORS, launcher_record, system_feature_choices
|
||||
from .retrobat_render import covered_records, path_parts, render, when
|
||||
|
||||
|
||||
def _argument_paths(src: Source, emulator: str, build: str) -> list[tuple[Record, list[str]]]:
|
||||
"""commandArray.Add(<path under bios>) after its flag, with its conditions."""
|
||||
code = _code(src)
|
||||
found = []
|
||||
for add in re.finditer(r"commandArray\.Add\(", code):
|
||||
expr = _call_args(src, add.end() - 1)
|
||||
end = add.end() + len(expr) + 1
|
||||
if re.fullmatch(STRING, expr.strip()):
|
||||
continue
|
||||
method = _method_of(src, add.start())
|
||||
rendered = render(src, expr, method[0], add.start())
|
||||
if rendered is None or not rendered[0].startswith("bios"):
|
||||
continue
|
||||
flags = list(re.finditer(r'"(-[\w-]+)"', code[method[0] : add.start()]))
|
||||
if not flags:
|
||||
raise LauncherPatternMissing(src.path, f"flag before line {src.line(add.start())}")
|
||||
flag_at = method[0] + flags[-1].start()
|
||||
conditions, returns = when(src, add.start())
|
||||
found.append(
|
||||
(
|
||||
launcher_record(
|
||||
emulator,
|
||||
build,
|
||||
"passes_path",
|
||||
[],
|
||||
path_parts(
|
||||
src,
|
||||
*returns,
|
||||
*rendered[1],
|
||||
src.lines(flag_at, flag_at + 1),
|
||||
src.lines(_statement_start(src, add.start()), end),
|
||||
),
|
||||
search_dir=rendered[0],
|
||||
passes_to=f"command line {flags[-1].group(1)} {rendered[0]}",
|
||||
fails_when_missing=False,
|
||||
),
|
||||
conditions,
|
||||
)
|
||||
)
|
||||
return found
|
||||
|
||||
|
||||
def _with_conditions(record: Record, conditions: list[str]) -> Record:
|
||||
out = {key: value for key, value in record.items() if key != "source_ref"}
|
||||
if conditions:
|
||||
out["depends_on_option"] = ", ".join(conditions)
|
||||
out["source_ref"] = record["source_ref"]
|
||||
return out
|
||||
|
||||
|
||||
_BIOS_GUARD = r'string\.IsNullOrEmpty\(AppConfig\["bios"\]\)'
|
||||
|
||||
|
||||
def mame(sources: dict[str, Source]) -> list[Record]:
|
||||
"""MAME folders: the standalone build's own, and those of the MESS systems
|
||||
that the standalone build and the libretro core share."""
|
||||
own = sources[f"{GENERATORS}/Mame64.Generator.cs"]
|
||||
found = _argument_paths(own, "mame64", "standalone")
|
||||
if not found:
|
||||
raise LauncherPatternMissing(own.path, "MAME folder arguments")
|
||||
records = covered_records(
|
||||
own,
|
||||
[
|
||||
split
|
||||
for record, conditions in found
|
||||
for split in _per_emulator(own, _with_conditions(record, conditions))
|
||||
],
|
||||
# The bezel artwork folder is read by the launcher, not passed.
|
||||
skip=(_BIOS_GUARD, r"ConfigureBezels\("),
|
||||
)
|
||||
mess = sources[f"{GENERATORS}/MessSystem.cs"]
|
||||
found = _argument_paths(mess, "mame64", "standalone")
|
||||
if not found:
|
||||
raise LauncherPatternMissing(mess.path, "MESS folder arguments")
|
||||
shared = []
|
||||
for record, conditions in found:
|
||||
if "standalone" in conditions:
|
||||
shared.append(_with_conditions(record, [c for c in conditions if c != "standalone"]))
|
||||
continue
|
||||
shared.append(_with_conditions(record, conditions))
|
||||
libretro = dict(record, emulator="mame", build="libretro", names=[])
|
||||
shared.append(_with_conditions(libretro, conditions))
|
||||
return records + covered_records(
|
||||
mess,
|
||||
shared,
|
||||
# The softlist file and the Lua autoboot script are named after the game.
|
||||
skip=(
|
||||
_BIOS_GUARD,
|
||||
r'"hash", (?:SystemConfig\["force_softlist"\]|romMedia) \+ "\.xml"',
|
||||
r'"autoboot_scripts"',
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def psxmame(sources: dict[str, Source]) -> list[Record]:
|
||||
src = sources[f"{GENERATORS}/PSXMame.Generator.cs"]
|
||||
found = _argument_paths(src, "psxmame", "standalone")
|
||||
if not found:
|
||||
raise LauncherPatternMissing(src.path, "rompath argument")
|
||||
return covered_records(src, [_with_conditions(record, conditions) for record, conditions in found])
|
||||
|
||||
|
||||
def xroar(sources: dict[str, Source]) -> list[Record]:
|
||||
src = sources[f"{GENERATORS}/Xroar.Generator.cs"]
|
||||
found = _argument_paths(src, "xroar", "standalone")
|
||||
if not found:
|
||||
raise LauncherPatternMissing(src.path, "rompath argument")
|
||||
records = [
|
||||
split
|
||||
for record, conditions in found
|
||||
for split in _per_system(src, _with_conditions(record, conditions))
|
||||
]
|
||||
# The machines ES offers under a system the folder is chosen for: XRoar
|
||||
# runs a CoCo 3 for coco, so its ROMs are read from that system's folder.
|
||||
features = sources[FEATURES]
|
||||
for record in records:
|
||||
systems = record.get("systems")
|
||||
if not isinstance(systems, list) or not systems:
|
||||
continue
|
||||
machines: list[str] = []
|
||||
lines = []
|
||||
for system in systems:
|
||||
choices, span = system_feature_choices(features, "xroar", "xroar_machine", system)
|
||||
machines += [m for m in choices if m not in machines]
|
||||
lines.append(span)
|
||||
record["machines"] = machines
|
||||
ref = record.pop("source_ref")
|
||||
record["source_ref"] = f"{ref}, {source_ref((features.path, lines))}"
|
||||
line = src.find(r'string (\w+) = ("rompath (?:[^"\\\n]|\\.)*");', "config rompath line")
|
||||
written = _unescape(line.group(2)[1:-1])
|
||||
relative = re.fullmatch(r'rompath "(.*)"', written)
|
||||
method = _method_of(src, line.start())
|
||||
setup = src.find(r'string setupPath = Path\.Combine\(path, "([^"]+)"\);', "xroar config file")
|
||||
use = src.find(rf"lines\[i\] = {line.group(1)};", "rompath replacement", line.end(), method[1])
|
||||
parts = [p for p in re.split(r"\\+", relative.group(1) if relative else "") if p]
|
||||
if "bios" not in parts:
|
||||
raise LauncherPatternMissing(src.path, "bios in the config rompath")
|
||||
records.append(
|
||||
launcher_record(
|
||||
"xroar",
|
||||
"standalone",
|
||||
"passes_path",
|
||||
[],
|
||||
path_parts(
|
||||
src, src.lines(line.start(), line.end()), src.lines(use.start(), use.end())
|
||||
),
|
||||
search_dir="/".join(parts[parts.index("bios") :]),
|
||||
passes_to=f"{setup.group(1)} {written}",
|
||||
fails_when_missing=False,
|
||||
)
|
||||
)
|
||||
return covered_records(src, records)
|
||||
|
||||
|
||||
_EMULATOR_BRANCH = re.compile(r"([^\s;<>]+) when (\w+), else ([^\s;<>]+)")
|
||||
|
||||
|
||||
def _per_emulator(src: Source, record: Record) -> list[Record]:
|
||||
"""A directory chosen by the emulator the generator runs, one record each.
|
||||
|
||||
Mame64.Generator.cs sets `bool hbmame = emulator == "hbmame";` and passes
|
||||
`-sp bios/hbmame/samples` for it, bios/mame/samples for mame64. A choice
|
||||
on any other condition is left as it reads.
|
||||
"""
|
||||
rendered = str(record.get("search_dir", ""))
|
||||
branch = _EMULATOR_BRANCH.fullmatch(rendered)
|
||||
if branch is None:
|
||||
return [record]
|
||||
chosen, flag, default = branch.groups()
|
||||
declared = re.search(rf'bool {flag} = emulator == "([\w.-]+)";', _code(src))
|
||||
if declared is None:
|
||||
return [record]
|
||||
ref = str(record["source_ref"])
|
||||
if not ref.startswith(src.path + ":"):
|
||||
raise LauncherPatternMissing(src.path, f"source of the directory choice {rendered!r}")
|
||||
spans = [
|
||||
(int(first), int(last or first))
|
||||
for first, _, last in (s.partition("-") for s in ref[len(src.path) + 1:].split(", "))
|
||||
]
|
||||
spans.append(src.lines(declared.start(), declared.end()))
|
||||
prefix = str(record["passes_to"]).removesuffix(rendered).strip()
|
||||
out = []
|
||||
for emulator, directory in ((declared.group(1), chosen), (record["emulator"], default)):
|
||||
split = {k: v for k, v in record.items() if k != "source_ref"}
|
||||
split.update(emulator=emulator, search_dir=directory, passes_to=f"{prefix} {directory}")
|
||||
split["source_ref"] = path_parts(src, *spans)
|
||||
out.append(split)
|
||||
return out
|
||||
|
||||
|
||||
_SYSTEM_BRANCH = re.compile(r'(\S+), or (\S+) when system == "([\w.-]+)"')
|
||||
|
||||
|
||||
def _per_system(src: Source, record: Record) -> list[Record]:
|
||||
"""A directory chosen by the system, one record per choice.
|
||||
|
||||
`romPath = <a>; if (system == "coco") romPath = <b>;` renders as "<a>, or
|
||||
<b> when system == "coco"": <b> is passed for that system, <a> for every
|
||||
other one.
|
||||
"""
|
||||
rendered = str(record.get("search_dir", ""))
|
||||
branch = _SYSTEM_BRANCH.fullmatch(rendered)
|
||||
if branch is None:
|
||||
if " or " in rendered:
|
||||
raise LauncherPatternMissing(src.path, f"directory choice {rendered!r}")
|
||||
return [record]
|
||||
default, chosen, system = branch.groups()
|
||||
flag = str(record["passes_to"]).removesuffix(rendered).strip()
|
||||
names = record["names"]
|
||||
if not isinstance(names, list):
|
||||
raise LauncherPatternMissing(src.path, "names of a directory choice")
|
||||
out = []
|
||||
for directory, systems in ((default, None), (chosen, [system])):
|
||||
split = {k: v for k, v in record.items() if k != "source_ref"}
|
||||
split.update(
|
||||
names=list(names), search_dir=directory, passes_to=f"{flag} {directory}"
|
||||
)
|
||||
if systems:
|
||||
split["systems"] = systems
|
||||
split["source_ref"] = record["source_ref"]
|
||||
out.append(split)
|
||||
return out
|
||||
|
||||
|
||||
# Generators that start an emulator with a portable data folder beside its
|
||||
# binary: (generator, emulator key, binary, the code's name for the folder).
|
||||
PORTABLE_USERS = (
|
||||
("Citron.Generator.cs", "citron", "citron.exe", "PORTABLE_DIR"),
|
||||
("Eden.Generator.cs", "eden", "eden.exe", "PORTABLE_DIR"),
|
||||
("Ryujinx.Generator.cs", "ryujinx", "Ryujinx.exe", "DefaultPortableDir"),
|
||||
("ShadPS4.Generator.cs", "shadps4", "shadPS4.exe", "PORTABLE_DIR"),
|
||||
("Sudachi.Generator.cs", "sudachi", "sudachi.exe", "PORTABLE_DIR"),
|
||||
("Yuzu.Generator.cs", "yuzu", "yuzu.exe", "PORTABLE_DIR"),
|
||||
)
|
||||
_EMULATOR_FOLDER = (
|
||||
r"GetEmulatorPathAndExe\(emulator, out string path, out string exe, \"[^\"]+\"\)"
|
||||
r"|string path = AppConfig\.GetFullPath\((?:emulator(?:\.Replace\(\"-\", \" \"\))?"
|
||||
r"|\"\w+\")\);"
|
||||
)
|
||||
_PORTABLE_FOLDER = r'string (userFolder|setupPath) = Path\.Combine\(path, "(\w+)"\);'
|
||||
# Ryujinx's generator hands --root-data-dir saves/switch/ryujinx/portable
|
||||
# instead when that folder exists.
|
||||
_ALTERNATE_ROOT = (
|
||||
r'string portablePath = Path\.Combine\(AppConfig\.GetFullPath\("saves"\), "switch", '
|
||||
r'"ryujinx", "portable"\);'
|
||||
)
|
||||
|
||||
|
||||
def portable_users(sources: dict[str, Source]) -> list[Record]:
|
||||
"""The portable data folder a generator gives an emulator beside its binary.
|
||||
|
||||
The emulator folder comes from AppConfig.GetFullPath, and the generator
|
||||
creates or configures <folder>/user (<folder>/portable for Ryujinx)
|
||||
before launching: the emulator then keeps its data there (keys/,
|
||||
sys_modules/, system/) in place of %APPDATA%.
|
||||
"""
|
||||
records = []
|
||||
for name, emulator, binary, handle in PORTABLE_USERS:
|
||||
src = sources[f"{GENERATORS}/{name}"]
|
||||
found = src.find(_EMULATOR_FOLDER, f"{emulator} folder")
|
||||
folder = src.find(_PORTABLE_FOLDER, "portable folder")
|
||||
spans = [src.lines(found.start(), found.end()), src.lines(folder.start(), folder.end())]
|
||||
if folder.group(1) == "userFolder":
|
||||
create = src.find(
|
||||
r"Directory\.CreateDirectory\(userFolder\)", "user folder creation", folder.end()
|
||||
)
|
||||
spans[-1] = src.lines(folder.start(), create.end())
|
||||
depends = None
|
||||
alternate = re.search(_ALTERNATE_ROOT, src.text)
|
||||
if alternate:
|
||||
spans.append(src.lines(alternate.start(), alternate.end()))
|
||||
depends = "unless saves/switch/ryujinx/portable exists, passed with -r"
|
||||
records.append(launcher_record(
|
||||
emulator,
|
||||
"standalone",
|
||||
"passes_path",
|
||||
[],
|
||||
source_ref((src.path, spans)),
|
||||
search_dir=f'<AppConfig.GetFullPath("{emulator}")>/{folder.group(2)}',
|
||||
passes_to=f"{handle}, the portable folder beside {binary}",
|
||||
fails_when_missing=False,
|
||||
depends_on_option=depends,
|
||||
))
|
||||
return records
|
||||
|
||||
|
||||
def pico8(sources: dict[str, Source]) -> list[Record]:
|
||||
"""The PICO-8 binary the generator runs, from an emulator folder.
|
||||
|
||||
AppConfig.GetFullPath names a folder of the RetroBat install
|
||||
(emulatorLauncher.cfg, else emulators/<key>): the binary is never
|
||||
looked up in the BIOS tree.
|
||||
"""
|
||||
src = sources[f"{GENERATORS}/Pico8.Generator.cs"]
|
||||
folder = src.find(r'string path = AppConfig\.GetFullPath\("(\w+)"\);', "pico8 folder")
|
||||
exe = src.find(
|
||||
r'string exe = Path\.Combine\(path, "([^"]+)"\);', "binary path", folder.end()
|
||||
)
|
||||
check = src.find(r"if \(!File\.Exists\(exe\)\)\s*return null;", "binary check", exe.end())
|
||||
run = src.find(r"FileName = exe,\s*WorkingDirectory = path,", "binary run", check.end())
|
||||
return [
|
||||
launcher_record(
|
||||
"pico8",
|
||||
"standalone",
|
||||
"fixed_name",
|
||||
[exe.group(1)],
|
||||
source_ref(
|
||||
(
|
||||
src.path,
|
||||
[
|
||||
src.lines(folder.start(), folder.end()),
|
||||
src.lines(exe.start(), check.end()),
|
||||
src.lines(run.start(), run.end()),
|
||||
],
|
||||
)
|
||||
),
|
||||
case_insensitive=True,
|
||||
search_dir=f"<AppConfig.GetFullPath(\"{folder.group(1)}\")>",
|
||||
passes_to="exec",
|
||||
fails_when_missing="returns no process when the binary is absent",
|
||||
)
|
||||
]
|
||||
@@ -0,0 +1,555 @@
|
||||
"""RetroBat launcher records of Hatari, Amiberry, WinUAE and openMSX."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
from .csharp_source import (
|
||||
LauncherPatternMissing,
|
||||
Record,
|
||||
Source,
|
||||
_array_at,
|
||||
_strings,
|
||||
_throw_message,
|
||||
source_ref,
|
||||
)
|
||||
from .retrobat_generators import (
|
||||
BIOS,
|
||||
FEATURES,
|
||||
GENERATORS,
|
||||
TARGET_ABSENT,
|
||||
joined,
|
||||
launcher_record,
|
||||
feature_choices,
|
||||
)
|
||||
|
||||
|
||||
def hatari(sources: dict[str, Source]) -> list[Record]:
|
||||
"""tos.img in bios, a TOS chosen in bios/hatari/tos, and EmuTOS from there
|
||||
for a hard disk image, for a missing tos.img, or after a TOS too old for
|
||||
autostart or GEMDOS."""
|
||||
src = sources[f"{GENERATORS}/Hatari.Generator.cs"]
|
||||
features = sources[FEATURES]
|
||||
folder = src.find(
|
||||
rf'string (\w+) = Path\.Combine\({BIOS}, ((?:"[^"]+"(?:, )?)+)\);', "TOS folder"
|
||||
)
|
||||
tos_dir, folders = folder.group(1), _strings(folder.group(2))
|
||||
default = src.find(
|
||||
rf'string (\w+) = Path\.Combine\({BIOS}, "([^"]+)"\);', "default TOS path", folder.end()
|
||||
)
|
||||
var, name = default.group(1), default.group(2)
|
||||
emutos = src.find(
|
||||
rf'string (\w+) = Path\.Combine\({tos_dir}, "([^"]+)"\);', "EmuTOS path", default.end()
|
||||
)
|
||||
override = src.find(
|
||||
rf'isOptSet\("(\w+)"\)[^\n]*\n\s*{var} = Path\.Combine\({tos_dir}, SystemConfig\["\1"\]\);',
|
||||
"TOS option override",
|
||||
emutos.end(),
|
||||
)
|
||||
option = override.group(1)
|
||||
disk = src.find(
|
||||
rf"else if \(media\.HasHardDiskImage && File\.Exists\({emutos.group(1)}\)\)",
|
||||
"EmuTOS for a hard disk image",
|
||||
override.end(),
|
||||
)
|
||||
absent = src.find(
|
||||
rf"if \(!File\.Exists\({var}\) && File\.Exists\({emutos.group(1)}\)\)\s*{var} = {emutos.group(1)};",
|
||||
"EmuTOS without tos.img",
|
||||
disk.end(),
|
||||
)
|
||||
newer = src.find(
|
||||
r"new string\[\] \{ ((?:\"[^\"]+\"(?:, )?)+) \}\s*"
|
||||
rf"\.Select\(t => Path\.Combine\({tos_dir}, t\)\)\s*\.FirstOrDefault\(t => File\.Exists\(t\)\);",
|
||||
"TOS for autostart and GEMDOS",
|
||||
absent.end(),
|
||||
)
|
||||
write = src.find(
|
||||
rf'ini\.WriteValue\("(\w+)", "(\w+)", {var}\);', "TOS ini write", newer.end()
|
||||
)
|
||||
message, _ = _throw_message(src, newer.end(), write.start())
|
||||
passes = f"hatari.cfg [{write.group(1)}] {write.group(2)}"
|
||||
tos_folder = "/".join(["bios", *folders])
|
||||
choices, choice_lines = feature_choices(features, "hatari", option)
|
||||
head = src.lines(folder.start(), emutos.end())
|
||||
tail = src.lines(write.start(), write.end())
|
||||
return [
|
||||
launcher_record(
|
||||
"hatari",
|
||||
"standalone",
|
||||
"fixed_name",
|
||||
[name],
|
||||
source_ref((src.path, [head, src.lines(absent.start(), absent.end()), tail])),
|
||||
case_insensitive=True,
|
||||
search_dir="bios",
|
||||
passes_to=f"{passes}=<bios>/{name}",
|
||||
fails_when_missing=f"{tos_folder}/{emutos.group(2)} instead, else {message}",
|
||||
depends_on_option=f"{option} unset, no hard disk image",
|
||||
),
|
||||
launcher_record(
|
||||
"hatari",
|
||||
"standalone",
|
||||
"core_option",
|
||||
choices,
|
||||
source_ref(
|
||||
(src.path, [head, src.lines(override.start(), override.end()), tail]),
|
||||
(features.path, [choice_lines]),
|
||||
),
|
||||
case_insensitive=True,
|
||||
search_dir=tos_folder,
|
||||
passes_to=f"{passes}=<bios>/{'/'.join(folders)}/<value>",
|
||||
fails_when_missing=message,
|
||||
depends_on_option=option,
|
||||
),
|
||||
launcher_record(
|
||||
"hatari",
|
||||
"standalone",
|
||||
"fixed_name",
|
||||
[emutos.group(2)],
|
||||
source_ref((src.path, [head, src.lines(disk.start(), absent.end()), tail])),
|
||||
case_insensitive=True,
|
||||
search_dir=tos_folder,
|
||||
passes_to=f"{passes}=<bios>/{'/'.join(folders)}/{emutos.group(2)}",
|
||||
fails_when_missing=f"{name} is used, as without a hard disk image",
|
||||
depends_on_option=f"{option} unset, a hard disk image mounted or no {name}",
|
||||
),
|
||||
launcher_record(
|
||||
"hatari",
|
||||
"standalone",
|
||||
"names_searched",
|
||||
_strings(newer.group(1)),
|
||||
source_ref((src.path, [head, src.lines(newer.start(), newer.end()), tail])),
|
||||
case_insensitive=True,
|
||||
search_dir=tos_folder,
|
||||
passes_to=f"{passes}=<first found>",
|
||||
fails_when_missing="the TOS older than 1.04 is kept",
|
||||
depends_on_option=f"{option} unset, autostart or GEMDOS folder, TOS older than 1.04",
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
def hatari_libretro(sources: dict[str, Source]) -> list[Record]:
|
||||
src = sources[f"{GENERATORS}/LibRetro.CoreOptions.cs"]
|
||||
features = sources[FEATURES]
|
||||
records = []
|
||||
|
||||
tosimage = src.find(
|
||||
r'string (\w+) = SystemConfig\["(\w+)"\];\s*'
|
||||
rf'if \(!string\.IsNullOrEmpty\(\1\) && \1 != "(\w+)" && File\.Exists\(Path\.Combine\({BIOS}, '
|
||||
r'((?:"[^"]+", )+)\1\)\)\)\s*coreSettings\["(hatari_tosimage)"\] = \1;'
|
||||
r'\s*else\s*coreSettings\["\5"\] = "\3";',
|
||||
"hatari_tosimage",
|
||||
)
|
||||
guard = src.find(r'if \(core != "(hatari2014)"\)', "hatari2014 guard")
|
||||
folders = _strings(tosimage.group(4).rstrip(", "))
|
||||
choices, choice_lines = feature_choices(
|
||||
features, "libretro", tosimage.group(2), core=guard.group(1)
|
||||
)
|
||||
records.append(
|
||||
launcher_record(
|
||||
guard.group(1),
|
||||
"libretro",
|
||||
"core_option",
|
||||
choices,
|
||||
source_ref(
|
||||
(src.path, [src.lines(guard.start(), tosimage.end())]),
|
||||
(features.path, [choice_lines]),
|
||||
),
|
||||
search_dir="/".join(["bios", *folders]),
|
||||
passes_to=f"{tosimage.group(5)} = <value>, if the file is there | {tosimage.group(3)}",
|
||||
fails_when_missing=f"{tosimage.group(5)} = {tosimage.group(3)}",
|
||||
depends_on_option=tosimage.group(2),
|
||||
)
|
||||
)
|
||||
|
||||
guard = src.find(r'if \(core != "hatarib"\)', "hatarib guard")
|
||||
method = src.enclosing(guard.start())
|
||||
tos_img = src.find(
|
||||
r'string (\w+) = Path\.Combine\((\w+), "([^"]+)"\);', "hatarib tos.img path",
|
||||
method[0], method[1],
|
||||
)
|
||||
own = src.find(
|
||||
rf'string (\w+) = Path\.Combine\({tos_img.group(2)}, "([^"]+)"\);', "hatarib folder",
|
||||
tos_img.end(), method[1],
|
||||
)
|
||||
option = src.find(
|
||||
r'string (\w+) = SystemConfig\["(hatarib_tos)"\];', "hatarib option", own.end(), method[1]
|
||||
)
|
||||
tos_var, key = option.group(1), option.group(2)
|
||||
named = src.find(
|
||||
rf'if \({tos_var} == "(\w+)"\)\s*\{{\s*if \(File\.Exists\({tos_img.group(1)}\)\)\s*'
|
||||
r'(\w+) = "([^"]+)";',
|
||||
"tos.img choice", option.end(), method[1],
|
||||
)
|
||||
builtin = src.find(
|
||||
rf'else if \({tos_var}\.StartsWith\("(\w+)"\)\)', "EmuTOS choices", named.end(), method[1]
|
||||
)
|
||||
shared = src.find(
|
||||
rf'string (\w+) = Path\.Combine\({own.group(1)}, {tos_var}\);\s*'
|
||||
rf'string (\w+) = Path\.Combine\({tos_img.group(2)}, ((?:"[^"]+", )+){tos_var}\);',
|
||||
"shared TOS folder", builtin.end(), method[1],
|
||||
)
|
||||
copy = src.find(
|
||||
rf"if \(!File\.Exists\({shared.group(1)}\) && File\.Exists\({shared.group(2)}\)\)",
|
||||
"copy from the shared folder", shared.end(), method[1],
|
||||
)
|
||||
chosen = src.find(
|
||||
rf'if \(File\.Exists\({shared.group(1)}\)\)\s*{named.group(2)} = "([^"/]+)/" \+ {tos_var};',
|
||||
"chosen TOS write", copy.end(), method[1],
|
||||
)
|
||||
fallback = src.find(
|
||||
rf'if \({named.group(2)} == null\)\s*\{{\s*{named.group(2)} = "([^"]+)";\s*'
|
||||
rf'if \(File\.Exists\({tos_img.group(1)}\)\)\s*\{{\s*{named.group(2)} = "([^"]+)";',
|
||||
"default TOS", chosen.end(), method[1],
|
||||
)
|
||||
emutos = src.find(
|
||||
rf'{named.group(2)} = "{re.escape(fallback.group(1))}";', "EmuTOS for a disk", fallback.end(),
|
||||
method[1],
|
||||
)
|
||||
folders = _strings(shared.group(3).rstrip(", "))
|
||||
choices, choice_lines = feature_choices(features, "libretro", key, core="hatarib")
|
||||
files = [c for c in choices if c != named.group(1) and not c.startswith(builtin.group(1))]
|
||||
head = src.lines(tos_img.start(), own.end())
|
||||
records.append(
|
||||
launcher_record(
|
||||
"hatarib",
|
||||
"libretro",
|
||||
"fixed_name",
|
||||
[tos_img.group(3)],
|
||||
source_ref((src.path, [head, src.lines(named.start(), named.end()),
|
||||
src.lines(fallback.start(), emutos.end())])),
|
||||
case_insensitive=True,
|
||||
search_dir="bios",
|
||||
passes_to=f"{key} = {fallback.group(2)}",
|
||||
fails_when_missing=f"falls back to {key} = {fallback.group(1)}",
|
||||
depends_on_option=(
|
||||
f"{key} unset or {named.group(1)}; {fallback.group(1)} instead for a hard disk image "
|
||||
"under a TOS other than EmuTOS, or for autostart or GEMDOS under TOS older than 1.04"
|
||||
),
|
||||
)
|
||||
)
|
||||
records.append(
|
||||
launcher_record(
|
||||
"hatarib",
|
||||
"libretro",
|
||||
"core_option",
|
||||
files,
|
||||
source_ref(
|
||||
(src.path, [head, src.lines(shared.start(), chosen.end())]),
|
||||
(features.path, [choice_lines]),
|
||||
),
|
||||
case_insensitive=True,
|
||||
search_dir=f"bios/{own.group(2)}",
|
||||
passes_to=f"{key} = {chosen.group(1)}/<value>",
|
||||
fails_when_missing=f"{key} = {fallback.group(1)}, or {fallback.group(2)} when bios holds it",
|
||||
depends_on_option=key,
|
||||
)
|
||||
)
|
||||
records.append(
|
||||
launcher_record(
|
||||
"hatarib",
|
||||
"libretro",
|
||||
"copies",
|
||||
files,
|
||||
source_ref((src.path, [head, src.lines(shared.start(), copy.end())])),
|
||||
case_insensitive=True,
|
||||
search_dir="/".join(["bios", *folders]),
|
||||
passes_to=f"bios/{own.group(2)}/<value>",
|
||||
fails_when_missing=False,
|
||||
depends_on_option=joined(key, TARGET_ABSENT),
|
||||
)
|
||||
)
|
||||
return records
|
||||
|
||||
|
||||
def _kickstart_table(
|
||||
src: Source,
|
||||
entry: str,
|
||||
find_method: str,
|
||||
) -> tuple[list[tuple[str, list[str], list[tuple[int, int]]]], str, tuple[int, int]]:
|
||||
"""Kickstart candidate lists of an Amiga model table, identical lists merged."""
|
||||
lists: dict[tuple[str, tuple[str, ...]], list[tuple[int, int]]] = {}
|
||||
for model in src.find_all(rf'\{{\s*"[\w+]+",\s*new {entry}\s*\{{', f"{entry} table"):
|
||||
block = src.block_at(model.start())
|
||||
for field in re.finditer(
|
||||
r"\b(Kickstart|KickstartExt)\s*=\s*new\s*(?:string)?\[\]\s*\{",
|
||||
src.text[block[0] : block[1]],
|
||||
):
|
||||
names, (_, last) = _array_at(src, block[0] + field.end() - 1)
|
||||
lists.setdefault((field.group(1), tuple(names)), []).append(
|
||||
(src.line(model.start()), last)
|
||||
)
|
||||
method = src.find(find_method, "Kickstart lookup method")
|
||||
body = src.block_at(method.end())
|
||||
dirs = src.find(
|
||||
r'new\s*(?:List<string>\s*)?(?:\[\])?\s*\{\s*biosPath((?:, Path\.Combine\(biosPath, "[^"]+"\))+)\s*\}',
|
||||
"Kickstart search directories",
|
||||
body[0],
|
||||
body[1],
|
||||
)
|
||||
search = ", ".join(["bios", *(f"bios/{d}" for d in _strings(dirs.group(1)))])
|
||||
method_span = (src.line(method.start()), src.lines(*body)[1])
|
||||
return (
|
||||
[(field, list(names), spans) for (field, names), spans in lists.items()],
|
||||
search,
|
||||
method_span,
|
||||
)
|
||||
|
||||
|
||||
AMIBERRY_KEY = "amiberry"
|
||||
|
||||
|
||||
def amiberry(sources: dict[str, Source]) -> list[Record]:
|
||||
"""Kickstarts searched in bios and copied into the folders the generator
|
||||
writes to amiberry.conf, both below the amiberry emulator folder."""
|
||||
src = sources[f"{GENERATORS}/Amiberry.Generator.cs"]
|
||||
lists, search, method_span = _kickstart_table(
|
||||
src, "AmigaModel", r"private string FindBios\(string\[\] candidates\)"
|
||||
)
|
||||
warnings = {
|
||||
"Kickstart": src.find(
|
||||
r'Warning\("\[Amiberry\] No Kickstart ROM found', "Kickstart warning"
|
||||
),
|
||||
"KickstartExt": src.find(
|
||||
r'Warning\("\[Amiberry\] No extended ROM found', "extended ROM warning"
|
||||
),
|
||||
}
|
||||
keys = {"Kickstart": "kickstart_rom_file", "KickstartExt": "kickstart_ext_rom_file"}
|
||||
records = []
|
||||
for field, names, spans in lists:
|
||||
stage = src.find(rf"StageKickstart\(_model\.{field}\)", f"StageKickstart({field})")
|
||||
records.append(
|
||||
launcher_record(
|
||||
"amiberry",
|
||||
"standalone",
|
||||
"names_searched",
|
||||
names,
|
||||
source_ref(
|
||||
(
|
||||
src.path,
|
||||
[*spans, src.lines(stage.start(), warnings[field].end()), method_span],
|
||||
)
|
||||
),
|
||||
case_insensitive=True,
|
||||
search_dir=search,
|
||||
passes_to=f"copied to <amiberry roms>/{names[0]}, {keys[field]}",
|
||||
fails_when_missing=f"warning, {keys[field]} not written",
|
||||
)
|
||||
)
|
||||
folder = src.find(
|
||||
r'GetEmulatorPathAndExe\(emulator, out string path, out string exe(?:, "[^"]+")+\)',
|
||||
"amiberry folder",
|
||||
)
|
||||
home = f'<AppConfig.GetFullPath("{AMIBERRY_KEY}")>'
|
||||
roms = src.find(
|
||||
r'(\w+) = Path\.Combine\(path, "(\w+)"\);\s*'
|
||||
r'FileTools\.TryCreateDirectory\(\1\);\s*overrides\["rom_path"\] = \1;',
|
||||
"rom_path folder",
|
||||
)
|
||||
whdboot = src.find(
|
||||
r'overrides\["whdboot_path"\] = Path\.Combine\(path, "(\w+)"\);', "whdboot_path folder"
|
||||
)
|
||||
write = src.find(r"MergeConfLines\(confFile, overrides\);", "amiberry.conf write")
|
||||
head = src.lines(folder.start(), folder.end())
|
||||
written = src.lines(write.start(), write.end())
|
||||
for directory, match, key in ((roms.group(2), roms, "rom_path"),
|
||||
(whdboot.group(1), whdboot, "whdboot_path")):
|
||||
records.append(
|
||||
launcher_record(
|
||||
"amiberry",
|
||||
"standalone",
|
||||
"passes_path",
|
||||
[],
|
||||
source_ref((src.path, [head, src.lines(match.start(), match.end()), written])),
|
||||
search_dir=f"{home}/{directory}",
|
||||
passes_to=f"written: {key} in amiberry.conf",
|
||||
fails_when_missing=False,
|
||||
)
|
||||
)
|
||||
stage = src.find(r"private string StageKickstart\(string\[\] candidates\)", "StageKickstart")
|
||||
stage_body = src.block_at(stage.end())
|
||||
stage_text = src.text[stage_body[0]:stage_body[1]]
|
||||
if not re.search(r"Path\.Combine\(_amiberryRomsPath, candidates\[0\]\)", stage_text) or not re.search(
|
||||
r"!dst\.Exists \|\| dst\.Length != src\.Length \|\| dst\.LastWriteTimeUtc < src\.LastWriteTimeUtc",
|
||||
stage_text,
|
||||
):
|
||||
raise LauncherPatternMissing(src.path, "StageKickstart copy to candidates[0] when stale")
|
||||
stage_span = (src.line(stage.start()), src.lines(*stage_body)[1])
|
||||
for field, names, spans in lists:
|
||||
call = src.find(rf"StageKickstart\(_model\.{field}\)", f"StageKickstart({field})")
|
||||
records.append(
|
||||
launcher_record(
|
||||
"amiberry",
|
||||
"standalone",
|
||||
"copies",
|
||||
names,
|
||||
source_ref((src.path, [*spans, head, src.lines(roms.start(), roms.end()),
|
||||
src.lines(call.start(), call.end()),
|
||||
stage_span, method_span])),
|
||||
case_insensitive=True,
|
||||
search_dir=search,
|
||||
passes_to=f"{home}/{roms.group(2)}/{names[0]}",
|
||||
fails_when_missing=False,
|
||||
depends_on_option="first name found, the target is absent, smaller or older",
|
||||
)
|
||||
)
|
||||
stage_key = src.find(r"private void StageRomKey\(\)", "StageRomKey")
|
||||
key_body = src.block_at(stage_key.end())
|
||||
key_text = src.text[key_body[0]:key_body[1]]
|
||||
named = re.search(r'FindBios\(new\[\] \{ "([^"]+)" \}\)', key_text)
|
||||
if not named or not re.search(
|
||||
r"!File\.Exists\(dest\) \|\| new FileInfo\(dest\)\.Length != new FileInfo\(source\)\.Length",
|
||||
key_text,
|
||||
):
|
||||
raise LauncherPatternMissing(src.path, "StageRomKey copy when absent or resized")
|
||||
records.append(
|
||||
launcher_record(
|
||||
"amiberry",
|
||||
"standalone",
|
||||
"copies",
|
||||
[named.group(1)],
|
||||
source_ref((src.path, [head, src.lines(roms.start(), roms.end()),
|
||||
(src.line(stage_key.start()), src.lines(*key_body)[1]), method_span])),
|
||||
case_insensitive=True,
|
||||
search_dir=search,
|
||||
passes_to=f"{home}/{roms.group(2)}/{named.group(1)}",
|
||||
fails_when_missing=False,
|
||||
depends_on_option="the target is absent or its size differs",
|
||||
)
|
||||
)
|
||||
return records
|
||||
|
||||
|
||||
def winuae(sources: dict[str, Source]) -> list[Record]:
|
||||
src = sources[f"{GENERATORS}/Uae.Generator.cs"]
|
||||
lists, search, method_span = _kickstart_table(
|
||||
src, "Candidate", r"public static string Find\(string\[\] candidates\)"
|
||||
)
|
||||
writer = src.find(r"private void WriteKickstartRom\(", "WriteKickstartRom")
|
||||
body = src.block_at(writer.end())
|
||||
keys = {"Kickstart": "kickstart_rom_file", "KickstartExt": "kickstart_ext_rom_file"}
|
||||
records = []
|
||||
for field, names, spans in lists:
|
||||
lookup = src.find(
|
||||
rf"AmigaBios\.Find\(candidate\.{field}\)", f"Find({field})", body[0], body[1]
|
||||
)
|
||||
message, throw_line = _throw_message(src, lookup.end(), body[1])
|
||||
records.append(
|
||||
launcher_record(
|
||||
"winuae",
|
||||
"standalone",
|
||||
"names_searched",
|
||||
names,
|
||||
source_ref(
|
||||
(src.path, [*spans, (src.line(lookup.start()), throw_line + 1), method_span])
|
||||
),
|
||||
case_insensitive=True,
|
||||
search_dir=search,
|
||||
passes_to=f"game .uae {keys[field]}=<found path>",
|
||||
fails_when_missing=message,
|
||||
)
|
||||
)
|
||||
table = src.find(
|
||||
r"WhdBootKickstartEntry\[\] _whdBootKickstarts = new\[\]", "WHDBoot Kickstart table"
|
||||
)
|
||||
table_block = src.block_at(table.end())
|
||||
targets = re.findall(
|
||||
r'new WhdBootKickstartEntry\("([^"]+)", AmigaBios\.BySystem\["[^"]+"\]\.Kickstart\)',
|
||||
src.text[table_block[0] : table_block[1]],
|
||||
)
|
||||
loop = src.find(r"foreach \(var entry in _whdBootKickstarts\)", "WHDBoot copy loop")
|
||||
loop_block = src.block_at(loop.end())
|
||||
folder = src.find(
|
||||
r'Path\.Combine\(whdBoot, ((?:"[^"]+"(?:, )?)+)\)',
|
||||
"WHDBoot Kickstarts folder",
|
||||
0,
|
||||
loop.start(),
|
||||
)
|
||||
records.append(
|
||||
launcher_record(
|
||||
"winuae",
|
||||
"standalone",
|
||||
"copies",
|
||||
targets,
|
||||
source_ref(
|
||||
(
|
||||
src.path,
|
||||
[
|
||||
(src.line(loop.start()), src.lines(*loop_block)[1]),
|
||||
(src.line(table.start()), src.lines(*table_block)[1]),
|
||||
],
|
||||
)
|
||||
),
|
||||
case_insensitive=True,
|
||||
search_dir=search,
|
||||
passes_to=f"<WHDBoot>/{'/'.join(_strings(folder.group(1)))}/<name>",
|
||||
fails_when_missing=False,
|
||||
depends_on_option="the system's Kickstart candidates",
|
||||
)
|
||||
)
|
||||
return records
|
||||
|
||||
|
||||
def openmsx(sources: dict[str, Source]) -> list[Record]:
|
||||
src = sources[f"{GENERATORS}/OpenMSX.Generator.cs"]
|
||||
table = src.find(
|
||||
r"Dictionary<string, string\[\]> biosFiles = new Dictionary<string, string\[\]>\(\)\s*\{",
|
||||
"biosFiles table",
|
||||
)
|
||||
block = src.block_at(table.end() - 1)
|
||||
check = src.find(r"foreach \(var c in biosFileRequired\)", "per-file BIOS check")
|
||||
message, throw_line = _throw_message(src, check.end(), len(src.text))
|
||||
folder = re.search(r"in '([^']+)' folder", message)
|
||||
if folder is None:
|
||||
raise LauncherPatternMissing(src.path, "systemroms folder in the BIOS message")
|
||||
records = []
|
||||
for entry in re.finditer(
|
||||
r'\{ "([^"]+)", new string\[\] \{([^}]*)\} \}', src.text[block[0] : block[1]]
|
||||
):
|
||||
start = block[0] + entry.start()
|
||||
records.append(
|
||||
launcher_record(
|
||||
"openmsx",
|
||||
"standalone",
|
||||
"fixed_name",
|
||||
_strings(entry.group(2)),
|
||||
source_ref(
|
||||
(
|
||||
src.path,
|
||||
[
|
||||
src.lines(start, block[0] + entry.end()),
|
||||
(src.line(check.start()), throw_line),
|
||||
],
|
||||
)
|
||||
),
|
||||
case_insensitive=False,
|
||||
search_dir=folder.group(1).replace("\\", "/"),
|
||||
passes_to=f"-machine {entry.group(1)}",
|
||||
fails_when_missing=message,
|
||||
)
|
||||
)
|
||||
if not records:
|
||||
raise LauncherPatternMissing(src.path, "biosFiles entries")
|
||||
# OPENMSX_HOME is the user directory: openMSX reads share/systemroms below it.
|
||||
home = src.find(
|
||||
rf'string (\w+) = Path\.Combine\({BIOS}, "([^"]+)"\);', "OPENMSX_HOME folder"
|
||||
)
|
||||
handed = src.find(
|
||||
rf'ret\.EnvironmentVariables\["(OPENMSX_HOME)"\] = {home.group(1)};',
|
||||
"OPENMSX_HOME environment", home.end(),
|
||||
)
|
||||
records.append(
|
||||
launcher_record(
|
||||
"openmsx",
|
||||
"standalone",
|
||||
"passes_path",
|
||||
[],
|
||||
source_ref(
|
||||
(src.path, [src.lines(home.start(), home.end()),
|
||||
src.lines(handed.start(), handed.end())])
|
||||
),
|
||||
search_dir=f"bios/{home.group(2)}",
|
||||
passes_to=f"environment {handed.group(1)}",
|
||||
fails_when_missing=False,
|
||||
)
|
||||
)
|
||||
return records
|
||||
@@ -0,0 +1,778 @@
|
||||
"""RetroBat generators that write a BIOS file into the emulator's configuration."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
from .csharp_source import (
|
||||
LauncherPatternMissing,
|
||||
Record,
|
||||
STRING,
|
||||
Source,
|
||||
_call_args,
|
||||
_code,
|
||||
_method_of,
|
||||
_split_top,
|
||||
_statement_start,
|
||||
_strings,
|
||||
_throw_message,
|
||||
_unescape,
|
||||
source_ref,
|
||||
)
|
||||
from .retrobat_generators import (
|
||||
BIOS,
|
||||
FEATURES,
|
||||
GENERATORS,
|
||||
TARGET_ABSENT,
|
||||
BIOS_ROOT,
|
||||
joined,
|
||||
launcher_record,
|
||||
feature_choices,
|
||||
)
|
||||
from .retrobat_render import config_label, covered_records, path_parts, render, when
|
||||
|
||||
|
||||
# Each extractor takes the sources by path and returns its records.
|
||||
|
||||
|
||||
def ares(sources: dict[str, Source]) -> list[Record]:
|
||||
"""Fallback chains: x = Path.Combine(dir, a), then if (!File.Exists(x)) x = b."""
|
||||
src = sources[f"{GENERATORS}/Ares.Generator.cs"]
|
||||
records = []
|
||||
head = r'string (\w+) = Path\.Combine\((\w+), "([^"]+)"\);'
|
||||
for found in src.find_all(head, "Path.Combine fallback chain"):
|
||||
var, folder = found.group(1), found.group(2)
|
||||
names, end = [found.group(3)], found.end()
|
||||
step = re.compile(
|
||||
rf'\s*if \(!File\.Exists\({var}\)\)\s*{var} = Path\.Combine\({folder}, "([^"]+)"\);'
|
||||
)
|
||||
while more := step.match(src.text, end):
|
||||
names.append(more.group(1))
|
||||
end = more.end()
|
||||
if len(names) == 1:
|
||||
continue
|
||||
block = src.enclosing(found.start())
|
||||
target = src.find(
|
||||
rf'firmware\["([^"]+)"\] = {var}\.', f"firmware key for {var}", end, block[1]
|
||||
)
|
||||
container = list(
|
||||
re.compile(r'GetOrCreateContainer\("(\w+)"\)').finditer(
|
||||
src.text, block[0], found.start()
|
||||
)
|
||||
)
|
||||
folder_decl = src.find(
|
||||
rf'string {folder} = Path\.Combine\({BIOS}, "([^"]+)"\);',
|
||||
f"folder {folder}",
|
||||
block[0],
|
||||
found.start(),
|
||||
)
|
||||
sections = "/".join(m.group(1) for m in container)
|
||||
records.append(
|
||||
launcher_record(
|
||||
"ares",
|
||||
"standalone",
|
||||
"names_searched",
|
||||
names,
|
||||
source_ref((src.path, [(src.line(found.start()), src.line(target.end()))])),
|
||||
case_insensitive=True,
|
||||
search_dir=f"bios/{folder_decl.group(1)}",
|
||||
passes_to=f"settings.bml {sections}/{target.group(1)} (first found)",
|
||||
fails_when_missing=False,
|
||||
)
|
||||
)
|
||||
if not records:
|
||||
raise LauncherPatternMissing(src.path, "File.Exists fallback chain")
|
||||
return records
|
||||
|
||||
|
||||
def mesen(sources: dict[str, Source]) -> list[Record]:
|
||||
"""Files copied from bios into Mesen's Firmware folder, renamed on the way."""
|
||||
src = sources[f"{GENERATORS}/Mesen.Generator.cs"]
|
||||
records = []
|
||||
for folder in src.find_all(
|
||||
r'string targetFirmwarePath = Path\.Combine\(\w+, "Firmware"\);', "Firmware folder"
|
||||
):
|
||||
block = src.enclosing(folder.start())
|
||||
body = src.text[block[0] : block[1]]
|
||||
targets = dict(
|
||||
re.findall(
|
||||
r'string (targetFirmware\d+) = Path\.Combine\(targetFirmwarePath, "([^"]+)"\);',
|
||||
body,
|
||||
)
|
||||
)
|
||||
pairs = re.findall(
|
||||
rf'string (sourceFirmware\d+) = Path\.Combine\({BIOS}, "([^"]+)"\);', body
|
||||
)
|
||||
copies = re.findall(
|
||||
r"!File\.Exists\((targetFirmware\d+)\)[^\n]*\n\s*File\.Copy\((sourceFirmware\d+), \1\);",
|
||||
body,
|
||||
)
|
||||
if not pairs or len(copies) != len(pairs):
|
||||
raise LauncherPatternMissing(
|
||||
src.path, f"guarded File.Copy at line {src.line(folder.start())}"
|
||||
)
|
||||
by_source = {source: target for target, source in copies}
|
||||
names = [name for _, name in pairs]
|
||||
destinations = [targets[by_source[var]] for var, _ in pairs]
|
||||
try:
|
||||
fails: str | bool = _throw_message(src, folder.start(), block[1])[0]
|
||||
except LauncherPatternMissing:
|
||||
fails = False
|
||||
records.append(
|
||||
launcher_record(
|
||||
"mesen",
|
||||
"standalone",
|
||||
"copies",
|
||||
names,
|
||||
source_ref((src.path, [src.statement_span(block)])),
|
||||
case_insensitive=True,
|
||||
search_dir="bios",
|
||||
passes_to=", ".join(f"<mesen>/Firmware/{d}" for d in destinations),
|
||||
fails_when_missing=fails,
|
||||
depends_on_option=TARGET_ABSENT,
|
||||
)
|
||||
)
|
||||
return records
|
||||
|
||||
|
||||
def _name_of(src: Source, var: str, offset: int) -> tuple[str, str, list[tuple[int, int]]]:
|
||||
"""A variable holding bios/<folders>/<name>, as (folder, name, lines)."""
|
||||
method = _method_of(src, offset)
|
||||
rendered = render(src, var, method[0], offset)
|
||||
if rendered is None or not rendered[0].startswith("bios/") or ", " in rendered[0]:
|
||||
raise LauncherPatternMissing(
|
||||
src.path, f"bios path held by {var} at line {src.line(offset)}"
|
||||
)
|
||||
folder, _, name = rendered[0].rpartition("/")
|
||||
return folder, name, rendered[1]
|
||||
|
||||
|
||||
def desmume(sources: dict[str, Source]) -> list[Record]:
|
||||
src = sources[f"{GENERATORS}/Desmume.Generator.cs"]
|
||||
code = _code(src)
|
||||
pair = src.find(
|
||||
r"if \(File\.Exists\((\w+)\) && File\.Exists\((\w+)\)\)\s*\{", "BIOS pair check"
|
||||
)
|
||||
block = src.block_at(pair.end() - 1)
|
||||
keys = {
|
||||
value: key
|
||||
for key, value in re.findall(
|
||||
r'\w+\.WriteValue\("\w+", "(\w+)", (\w+)\);', code[block[0] : block[1]]
|
||||
)
|
||||
}
|
||||
flag = re.search(r'\w+\.WriteValue\("(\w+)", "(\w+)", "1"\);', code[block[0] : block[1]])
|
||||
if flag is None or any(var not in keys for var in pair.groups()):
|
||||
raise LauncherPatternMissing(src.path, "BIOS pair writes")
|
||||
names, spans = [], []
|
||||
for var in pair.groups():
|
||||
folder, name, lines = _name_of(src, var, pair.start())
|
||||
names.append(name)
|
||||
spans += lines
|
||||
conditions, returns = when(src, pair.start())
|
||||
config = config_label(src, pair.start(), "ini")
|
||||
records = [
|
||||
launcher_record(
|
||||
"desmume",
|
||||
"standalone",
|
||||
"fixed_name",
|
||||
names,
|
||||
path_parts(src, *returns, *spans, src.lines(pair.start(), block[1])),
|
||||
case_insensitive=True,
|
||||
search_dir=folder,
|
||||
passes_to=f"{config} [{flag.group(1)}] "
|
||||
+ ", ".join(keys[var] for var in pair.groups())
|
||||
+ ", only if every listed file exists",
|
||||
fails_when_missing=f"{flag.group(2)} left at 0",
|
||||
depends_on_option=", ".join(conditions) or None,
|
||||
)
|
||||
]
|
||||
firmware = src.find(
|
||||
rf'string (\w+) = Path\.Combine\({BIOS_ROOT}, "([^"]+)"\);\s*'
|
||||
r'if \(SystemConfig\.isOptSet\("(\w+)"\)[^\n]*\)\s*\{\s*'
|
||||
r'string (\w+) = SystemConfig\["\3"\];\s*if \(File\.Exists\(\4\)\)\s*\1 = \4;\s*\}\s*'
|
||||
r"if \(File\.Exists\(\1\)\)\s*\{",
|
||||
"firmware default and user file",
|
||||
)
|
||||
fw_block = src.block_at(firmware.end() - 1)
|
||||
fw_write = src.find(
|
||||
rf'\w+\.WriteValue\("(\w+)", "(\w+)", {firmware.group(1)}\);',
|
||||
"firmware write",
|
||||
fw_block[0],
|
||||
fw_block[1],
|
||||
)
|
||||
fw_flag = src.find(
|
||||
rf'\w+\.WriteValue\("{fw_write.group(1)}", "(\w+)", "1"\);',
|
||||
"firmware flag",
|
||||
fw_block[0],
|
||||
fw_block[1],
|
||||
)
|
||||
conditions, returns = when(src, firmware.start())
|
||||
records.append(
|
||||
launcher_record(
|
||||
"desmume",
|
||||
"standalone",
|
||||
"fixed_name",
|
||||
[firmware.group(2)],
|
||||
path_parts(src, *returns, src.lines(firmware.start(), fw_flag.end())),
|
||||
case_insensitive=True,
|
||||
search_dir="bios",
|
||||
passes_to=f"{config} [{fw_write.group(1)}] {fw_write.group(2)}, only if the file exists",
|
||||
fails_when_missing=f"{fw_flag.group(1)} left at 0",
|
||||
depends_on_option=", ".join(
|
||||
[*conditions, f"{firmware.group(3)} unset or not an existing file"]
|
||||
),
|
||||
)
|
||||
)
|
||||
return covered_records(src, records)
|
||||
|
||||
|
||||
def melonds_dsi(sources: dict[str, Source]) -> list[Record]:
|
||||
src = sources[f"{GENERATORS}/MelonDS.Generator.cs"]
|
||||
features = sources[FEATURES]
|
||||
code = _code(src)
|
||||
check = src.find(
|
||||
r"if \(((?:!File\.Exists\(\w+\)(?: \|\| )?)+)\)\s*throw new ApplicationException",
|
||||
"DSi files check",
|
||||
)
|
||||
message, throw_line = _throw_message(src, check.start(), len(src.text))
|
||||
method = _method_of(src, check.start())
|
||||
variables = re.findall(r"!File\.Exists\((\w+)\)", check.group(1))
|
||||
writes = {
|
||||
var: key
|
||||
for section, key, var in re.findall(
|
||||
r'\w+\.WriteValue\("(\w+)", "(\w+)", "\\"" \+ (\w+)\.Replace',
|
||||
code[check.end() : method[1]],
|
||||
)
|
||||
if section == "DSi"
|
||||
}
|
||||
if set(variables) - set(writes):
|
||||
raise LauncherPatternMissing(src.path, "DSi path writes")
|
||||
names, spans = [], []
|
||||
folders = set()
|
||||
for var in variables:
|
||||
decl = src.find(
|
||||
rf'string {var} = Path\.Combine\((\w+), "([^"]+)"\);',
|
||||
f"{var} declaration",
|
||||
method[0],
|
||||
check.start(),
|
||||
)
|
||||
root = render(src, decl.group(1), method[0], decl.start())
|
||||
if root is None or not root[0].startswith("bios"):
|
||||
raise LauncherPatternMissing(src.path, f"bios folder of {var}")
|
||||
folders.add(root[0])
|
||||
names.append(decl.group(2))
|
||||
spans += [*root[1], src.lines(decl.start(), decl.end())]
|
||||
if len(folders) != 1:
|
||||
raise LauncherPatternMissing(src.path, "one folder for the DSi files")
|
||||
folder = folders.pop()
|
||||
last_write = (
|
||||
max(
|
||||
m.end()
|
||||
for m in re.finditer(
|
||||
r'\w+\.WriteValue\("DSi", "\w+", [^;]+;', code[check.end() : method[1]]
|
||||
)
|
||||
)
|
||||
+ check.end()
|
||||
)
|
||||
dsi = src.find(
|
||||
r'bool (\w+) = SystemConfig\.isOptSet\("(\w+)"\) && SystemConfig\["\2"\] == "(\w+)";',
|
||||
"DSi console option",
|
||||
method[0],
|
||||
check.start(),
|
||||
)
|
||||
boot = src.find(
|
||||
r'bool (\w+) = Path\.GetExtension\(rom\)\.ToLowerInvariant\(\) == "([^"]+)";',
|
||||
"DSi NAND boot extension",
|
||||
)
|
||||
forced = src.find(
|
||||
rf"if \({boot.group(1)}\)\s*{dsi.group(1)} = true;", "NAND boot forces DSi", dsi.end()
|
||||
)
|
||||
mode = f'{dsi.group(2)} == "{dsi.group(3)}" || rom extension "{boot.group(2)}"'
|
||||
region = src.find(
|
||||
r'if \(SystemConfig\.isOptSet\("(\w+)"\)[^\n]*\)\s*\{\s*string (\w+) = SystemConfig\["\1"\];\s*'
|
||||
r'string (\w+) = Directory\.GetFiles\((\w+), "([^"]+)"\)\s*'
|
||||
r"\.FirstOrDefault\(f => Path\.GetFileNameWithoutExtension\(f\)\s*"
|
||||
r"\.IndexOf\(\2, StringComparison\.OrdinalIgnoreCase\) >= 0\);\s*"
|
||||
r"if \(\3 != null\)\s*(\w+) = \3;",
|
||||
"DSi NAND region match",
|
||||
method[0],
|
||||
check.start(),
|
||||
)
|
||||
region_block = src.block_at(region.start())
|
||||
choices, choice_lines = feature_choices(features, "melonds", region.group(1))
|
||||
stem, _, extension = region.group(5).rpartition(".")
|
||||
nand_name = names[variables.index(region.group(6))]
|
||||
config = config_label(src, check.start(), "ini")
|
||||
records = [
|
||||
launcher_record(
|
||||
"melonds",
|
||||
"standalone",
|
||||
"fixed_name",
|
||||
names,
|
||||
path_parts(
|
||||
src,
|
||||
src.lines(boot.start(), boot.end()),
|
||||
src.lines(dsi.start(), forced.end()),
|
||||
*spans,
|
||||
(src.line(check.start()), throw_line),
|
||||
src.lines(check.end(), last_write),
|
||||
),
|
||||
case_insensitive=True,
|
||||
search_dir=folder,
|
||||
passes_to=f"{config} [DSi] " + ", ".join(writes[v] for v in variables),
|
||||
fails_when_missing=message,
|
||||
depends_on_option=mode,
|
||||
),
|
||||
launcher_record(
|
||||
"melonds",
|
||||
"standalone",
|
||||
"scans_dir",
|
||||
[f"{stem}{{region}}*.{extension}"],
|
||||
source_ref(
|
||||
(src.path, [src.statement_span(region_block)]),
|
||||
(features.path, [choice_lines]),
|
||||
),
|
||||
expands={"region": choices},
|
||||
case_insensitive=True,
|
||||
search_dir=folder,
|
||||
passes_to=f"{config} [DSi] {writes[region.group(6)]}, first file whose name holds the region",
|
||||
fails_when_missing=f"falls back to {nand_name}",
|
||||
depends_on_option=(
|
||||
f'{dsi.group(2)} == "{dsi.group(3)}", {region.group(1)} set,'
|
||||
f' rom extension not "{boot.group(2)}"'
|
||||
),
|
||||
),
|
||||
]
|
||||
return records
|
||||
|
||||
|
||||
def jzintv(sources: dict[str, Source]) -> list[Record]:
|
||||
src = sources[f"{GENERATORS}/Jzintv.Generator.cs"]
|
||||
check = src.find(
|
||||
r"if \(!File\.Exists\((\w+)\) \|\| !File\.Exists\((\w+)\)\)\s*throw new ApplicationException",
|
||||
"exec and grom check",
|
||||
)
|
||||
message, throw_line = _throw_message(src, check.start(), len(src.text))
|
||||
passed = []
|
||||
for var in check.groups():
|
||||
add = src.find(
|
||||
rf'commandArray\.Add\("(-\w+)"\);\s*commandArray\.Add\("\\"" \+ {var} \+ "\\""\);',
|
||||
f"flag passing {var}",
|
||||
check.end(),
|
||||
)
|
||||
folder, name, lines = _name_of(src, var, check.start())
|
||||
passed.append((add.start(), add.group(1), name, lines, add.end()))
|
||||
passed.sort()
|
||||
records = [
|
||||
launcher_record(
|
||||
"jzintv",
|
||||
"standalone",
|
||||
"fixed_name",
|
||||
[name for _, _, name, _, _ in passed],
|
||||
path_parts(
|
||||
src,
|
||||
*[span for p in passed for span in p[3]],
|
||||
(src.line(check.start()), throw_line),
|
||||
src.lines(passed[0][0], passed[-1][4]),
|
||||
),
|
||||
case_insensitive=True,
|
||||
search_dir=folder,
|
||||
passes_to="command line "
|
||||
+ " ".join(f"{flag} <bios>/{name}" for _, flag, name, _, _ in passed),
|
||||
fails_when_missing=message,
|
||||
)
|
||||
]
|
||||
ecs = src.find(
|
||||
rf'string (\w+) = Path\.Combine\({BIOS_ROOT}, "([^"]+)"\);\s*if \(File\.Exists\(\1\)\)\s*\{{\s*'
|
||||
r'commandArray\.Add\("(-\w+)"\);',
|
||||
"ECS ROM",
|
||||
)
|
||||
warning = src.find(
|
||||
r'Warning\("([^"]+)"\);\s*commandArray\.Add\("(-\w+)"\);', "ECS warning", ecs.end()
|
||||
)
|
||||
option = src.find(
|
||||
r'if \(SystemConfig\.getOptBoolean\("(\w+)"\)\)\s*\{', "ECS option", 0, ecs.start()
|
||||
)
|
||||
commands = src.find(
|
||||
r'string commandFile = rom\.Replace\(Path\.GetExtension\(rom\), "([^"]+)"\);\s*'
|
||||
r'if \(!File\.Exists\(commandFile\)\)\s*commandFile = Path\.Combine\(AppConfig\.GetFullPath\("(\w+)"\),\s*"([^"]+)", "([^"]+)"\);\s*'
|
||||
r"if \(File\.Exists\(commandFile\)\)",
|
||||
"command file lookup",
|
||||
)
|
||||
records.append(
|
||||
launcher_record(
|
||||
"jzintv",
|
||||
"standalone",
|
||||
"fixed_name",
|
||||
[ecs.group(2)],
|
||||
path_parts(
|
||||
src,
|
||||
src.lines(commands.start(), commands.end()),
|
||||
src.lines(option.start(), warning.end()),
|
||||
),
|
||||
case_insensitive=True,
|
||||
search_dir="bios",
|
||||
passes_to=f"command line {ecs.group(3)} <bios>/{ecs.group(2)}, only if the file exists",
|
||||
fails_when_missing=f"warning '{warning.group(1)}', {warning.group(2)} passed",
|
||||
depends_on_option=(
|
||||
f"{option.group(1)} on, no <rom>{commands.group(1)} and no "
|
||||
f"{commands.group(2)}/{commands.group(3)}/{commands.group(4)}"
|
||||
),
|
||||
)
|
||||
)
|
||||
return covered_records(src, records)
|
||||
|
||||
|
||||
def blastem(sources: dict[str, Source]) -> list[Record]:
|
||||
src = sources[f"{GENERATORS}/Blastem.Generator.cs"]
|
||||
helper = src.find(
|
||||
r"private static void SetBiosPath\(\w+ (\w+), string (\w+), string (\w+), string (\w+)\)",
|
||||
"SetBiosPath",
|
||||
)
|
||||
body = src.block_at(helper.end())
|
||||
node, key, folder, name = helper.groups()
|
||||
src.find(
|
||||
rf"string (\w+) = Path\.Combine\({folder}, {name}\);\s*if \(File\.Exists\(\1\)\)\s*{node}\[{key}\] = \1;",
|
||||
"SetBiosPath guarded write",
|
||||
body[0],
|
||||
body[1],
|
||||
)
|
||||
section = src.find(r'var (\w+) = cfg\.GetOrCreateSection\("(system)"\);', "system section")
|
||||
config = src.find(
|
||||
r'string targetCfg = Path\.Combine\(path, "([^"]+)"\);', "BlastEm config file"
|
||||
)
|
||||
records = []
|
||||
for call in src.find_all(
|
||||
r'SetBiosPath\((\w+), "(\w+)", (\w+), "([^"]+)"\);', "SetBiosPath call"
|
||||
):
|
||||
root = render(src, call.group(3), _method_of(src, call.start())[0], call.start())
|
||||
if root is None or root[0] != "bios":
|
||||
raise LauncherPatternMissing(
|
||||
src.path, f"bios folder passed at line {src.line(call.start())}"
|
||||
)
|
||||
records.append(
|
||||
launcher_record(
|
||||
"blastem",
|
||||
"standalone",
|
||||
"fixed_name",
|
||||
[call.group(4)],
|
||||
path_parts(
|
||||
src,
|
||||
*root[1],
|
||||
src.lines(call.start(), call.end()),
|
||||
(src.line(helper.start()), src.lines(*body)[1]),
|
||||
),
|
||||
case_insensitive=True,
|
||||
search_dir="bios",
|
||||
passes_to=f"{config.group(1)} {section.group(2)}.{call.group(2)}, only if the file exists",
|
||||
fails_when_missing=f"info log, {call.group(2)} left as it is",
|
||||
)
|
||||
)
|
||||
return covered_records(src, records)
|
||||
|
||||
|
||||
def value_writes(
|
||||
src: Source, emulator: str, build: str, start: int = 0, end: int | None = None
|
||||
) -> list[Record]:
|
||||
"""Configuration values that resolve under the bios folder.
|
||||
|
||||
A directory becomes passes_path, a file fixed_name, guarded or not by a
|
||||
File.Exists on the variable it writes.
|
||||
"""
|
||||
code = _code(src)
|
||||
records = []
|
||||
for write in re.compile(r"(\w+)\.WriteValue\(").finditer(
|
||||
code, start, len(code) if end is None else end
|
||||
):
|
||||
args = _split_top(_call_args(src, write.end() - 1), ",")
|
||||
if len(args) != 3 or not re.fullmatch(rf"@?{STRING}|null", args[0]):
|
||||
continue
|
||||
key_literal = re.fullmatch(STRING, args[1])
|
||||
if key_literal is None:
|
||||
continue
|
||||
writer, section, value = write.group(1), args[0].lstrip("@"), args[2]
|
||||
key = _unescape(key_literal.group(1))
|
||||
method = _method_of(src, write.start())
|
||||
rendered = render(src, value, method[0], write.start())
|
||||
if rendered is None or not rendered[0].startswith("bios"):
|
||||
continue
|
||||
conditions, returns = when(src, write.start())
|
||||
section = _unescape(section[1:-1]) if section != "null" else ""
|
||||
target = f"{config_label(src, write.start(), writer)} " + (
|
||||
f"[{section}] {key}" if section else key
|
||||
)
|
||||
span = src.lines(
|
||||
_statement_start(src, write.start()),
|
||||
write.end() + len(_call_args(src, write.end() - 1)),
|
||||
)
|
||||
ref = path_parts(src, *returns, *rendered[1], span)
|
||||
depends = ", ".join(conditions) or None
|
||||
folder, _, name = rendered[0].rpartition("/")
|
||||
if "." not in name or ", " in rendered[0]:
|
||||
records.append(
|
||||
launcher_record(
|
||||
emulator,
|
||||
build,
|
||||
"passes_path",
|
||||
[],
|
||||
ref,
|
||||
search_dir=rendered[0],
|
||||
passes_to=f"{target} = {rendered[0]}",
|
||||
fails_when_missing=False,
|
||||
depends_on_option=depends,
|
||||
)
|
||||
)
|
||||
continue
|
||||
variable = value.strip()
|
||||
guarded = any(c == f"File.Exists({variable})" for c in conditions)
|
||||
if guarded:
|
||||
depends = ", ".join(c for c in conditions if c != f"File.Exists({variable})") or None
|
||||
records.append(
|
||||
launcher_record(
|
||||
emulator,
|
||||
build,
|
||||
"fixed_name",
|
||||
[name],
|
||||
ref,
|
||||
case_insensitive=True,
|
||||
search_dir=folder,
|
||||
passes_to=target
|
||||
+ (
|
||||
", only if the file exists"
|
||||
if guarded
|
||||
else ", written without an existence check"
|
||||
),
|
||||
fails_when_missing=f"{key} not written"
|
||||
if guarded
|
||||
else "path written without an existence check",
|
||||
depends_on_option=depends,
|
||||
)
|
||||
)
|
||||
return records
|
||||
|
||||
|
||||
def dolphin(sources: dict[str, Source]) -> list[Record]:
|
||||
src = sources[f"{GENERATORS}/Dolphin.Generator.cs"]
|
||||
records = value_writes(src, "dolphin", "standalone")
|
||||
if not records:
|
||||
raise LauncherPatternMissing(src.path, "GBA BIOS write")
|
||||
method = src.find(r"private void CopySegaBoot\(string path\)", "CopySegaBoot")
|
||||
body = src.block_at(method.end())
|
||||
target = src.find(
|
||||
r"string target = (Path\.Combine\(path, [^;]+\));", "segaboot target", body[0], body[1]
|
||||
)
|
||||
array = src.find(
|
||||
r"string\[\] candidates = new string\[\]\s*\{", "segaboot candidates", body[0], body[1]
|
||||
)
|
||||
block = src.block_at(array.end() - 1)
|
||||
names = []
|
||||
for item in _split_top(src.text[block[0] + 1 : block[1] - 1].strip(), ","):
|
||||
rendered = render(src, item, body[0], block[0])
|
||||
if rendered is None or not rendered[0].startswith("bios/"):
|
||||
raise LauncherPatternMissing(src.path, f"segaboot candidate {item}")
|
||||
names.append(rendered[0][len("bios/") :])
|
||||
src.find(
|
||||
r"candidates\.FirstOrDefault\(f => File\.Exists\(f\)\)",
|
||||
"first existing candidate",
|
||||
block[1],
|
||||
body[1],
|
||||
)
|
||||
warning = src.find(r'Warning\("([^"]+)"\);', "segaboot warning", block[1], body[1])
|
||||
src.find(
|
||||
r"if \(dst\.Exists && dst\.Length == src\.Length && dst\.LastWriteTimeUtc >= src\.LastWriteTimeUtc\)",
|
||||
"up-to-date check",
|
||||
block[1],
|
||||
body[1],
|
||||
)
|
||||
call = src.find(r"CopySegaBoot\(path\);", "CopySegaBoot call")
|
||||
conditions, returns = when(src, call.start())
|
||||
destination = render(src, target.group(1), body[0], target.start())
|
||||
records.append(
|
||||
launcher_record(
|
||||
"dolphin",
|
||||
"standalone",
|
||||
"copies",
|
||||
names,
|
||||
path_parts(
|
||||
src,
|
||||
*returns,
|
||||
src.lines(_statement_start(src, call.start()), call.end()),
|
||||
src.lines(method.start(), body[1]),
|
||||
),
|
||||
case_insensitive=True,
|
||||
search_dir="bios",
|
||||
passes_to=destination[0] if destination else target.group(1),
|
||||
fails_when_missing=f"warning '{_unescape(warning.group(1))}' when the target is absent too",
|
||||
depends_on_option=joined(
|
||||
*conditions, "first name found",
|
||||
"the target is absent, smaller or older",
|
||||
),
|
||||
)
|
||||
)
|
||||
return covered_records(src, records, skip=(r"DolphinTool\.exe",))
|
||||
|
||||
|
||||
def raine(sources: dict[str, Source]) -> list[Record]:
|
||||
src = sources[f"{GENERATORS}/Raine.Generator.cs"]
|
||||
records = value_writes(src, "raine", "standalone")
|
||||
if not any(r["kind"] == "fixed_name" for r in records):
|
||||
raise LauncherPatternMissing(src.path, "neocd_bios write")
|
||||
return covered_records(src, records)
|
||||
|
||||
|
||||
def gsplus(sources: dict[str, Source]) -> list[Record]:
|
||||
"""The first of the names GSplus accepts that the bios folder holds, written
|
||||
as its ROM path. Without one the key is left alone and GSplus searches
|
||||
beside its executable."""
|
||||
src = sources[f"{GENERATORS}/GsPlus.Generator.cs"]
|
||||
listed = src.find(
|
||||
r"static readonly string\[\] (\w+) = new string\[\] \{ ((?:\"[^\"]+\"(?:, )?)+) \};",
|
||||
"ROM names",
|
||||
)
|
||||
root = src.find(r"string (\w+) = AppConfig\.GetFullPath\(\"bios\"\);", "bios folder")
|
||||
first = src.find(
|
||||
rf"string (\w+) = {listed.group(1)}\s*\.Select\(n => Path\.Combine\({root.group(1)}, n\)\)"
|
||||
r"\s*\.FirstOrDefault\(File\.Exists\);",
|
||||
"first name present",
|
||||
)
|
||||
write = src.find(
|
||||
rf'(\w+)\.WriteValue\(null, "(\w+)", {first.group(1)}\);', "ROM path write"
|
||||
)
|
||||
conditions, returns = when(src, write.start())
|
||||
# The test on the name found is the selection itself, not a condition.
|
||||
conditions = [c for c in conditions if first.group(1) not in c]
|
||||
target = f"{config_label(src, write.start(), write.group(1))} {write.group(2)}"
|
||||
record = launcher_record(
|
||||
"gsplus",
|
||||
"standalone",
|
||||
"names_searched",
|
||||
_strings(listed.group(2)),
|
||||
path_parts(
|
||||
src,
|
||||
*returns,
|
||||
src.lines(listed.start(), listed.end()),
|
||||
src.lines(root.start(), root.end()),
|
||||
src.lines(first.start(), write.end()),
|
||||
),
|
||||
case_insensitive=True,
|
||||
search_dir="bios",
|
||||
passes_to=f"{target} = <first found>",
|
||||
fails_when_missing=False,
|
||||
depends_on_option=", ".join(conditions) or None,
|
||||
)
|
||||
return covered_records(src, [record])
|
||||
|
||||
|
||||
def rpcs3(sources: dict[str, Source]) -> list[Record]:
|
||||
src = sources[f"{GENERATORS}/Rpcs3.Generator.cs"]
|
||||
marker = src.find(
|
||||
rf"string (\w+) = (Path\.Combine\(path, [^;]+\));\s*string \w+ = {BIOS_ROOT};",
|
||||
"installed firmware marker",
|
||||
)
|
||||
pup = src.find(
|
||||
rf'string (\w+) = {BIOS_ROOT};\s*string (\w+) = Path\.Combine\(\1, "([^"]+)"\);',
|
||||
"PS3 update file",
|
||||
marker.start(),
|
||||
)
|
||||
method = _method_of(src, pup.start())
|
||||
check = src.find(
|
||||
rf"if \(!File\.Exists\({marker.group(1)}\) && !File\.Exists\({pup.group(2)}\)\)\s*throw",
|
||||
"firmware check",
|
||||
pup.end(),
|
||||
)
|
||||
message, _ = _throw_message(src, check.start(), method[1])
|
||||
install = src.find(
|
||||
rf'"(--\w+)",\s*StringExtensions\.QuoteString\({pup.group(2)}\)',
|
||||
"firmware install argument",
|
||||
check.end(),
|
||||
)
|
||||
returned = src.find(r"return new ProcessStartInfo\(\)", "install launch", install.end())
|
||||
installed = render(src, marker.group(2), method[0], marker.start())
|
||||
record = launcher_record(
|
||||
"rpcs3",
|
||||
"standalone",
|
||||
"fixed_name",
|
||||
[pup.group(3)],
|
||||
path_parts(src, src.lines(marker.start(), src.block_at(returned.end())[1])),
|
||||
case_insensitive=True,
|
||||
search_dir="bios",
|
||||
passes_to=(
|
||||
f"command line {install.group(1)} <bios>/{pup.group(3)}, launched instead of the game"
|
||||
),
|
||||
fails_when_missing=message,
|
||||
depends_on_option=f"{installed[0] if installed else marker.group(2)} absent",
|
||||
)
|
||||
return covered_records(src, [record])
|
||||
|
||||
|
||||
def bizhawk_gb(sources: dict[str, Source]) -> list[Record]:
|
||||
"""Game Boy BIOS switches: the core reads the file only when the launcher saw it."""
|
||||
src = sources[f"{GENERATORS}/Bizhawk.CoreOptions.cs"]
|
||||
config = sources[f"{GENERATORS}/Bizhawk.Generator.cs"].find(
|
||||
r'string configFile = Path\.Combine\(path, "([^"]+)"\);', "BizHawk config file"
|
||||
)
|
||||
code = _code(src)
|
||||
records = []
|
||||
for flag in src.find_all(
|
||||
r'if \(File\.Exists\((\w+)\) && SystemConfig\.getOptBoolean\("(\w+)"\)\)\s*'
|
||||
r'(\w+)\["(\w+)"\] = "(\w+)";\s*else\s*\3\["\4"\] = "(\w+)";',
|
||||
"GB BIOS switch",
|
||||
):
|
||||
var, option, node, key, on, off = flag.groups()
|
||||
method = _method_of(src, flag.start())
|
||||
core = src.find(r'if \(core != "(\w+)"\)\s*return;', "core guard", method[0], flag.start())
|
||||
container = src.find(
|
||||
rf'var {node} = \w+\.GetOrCreateContainer\("([^"]+)"\);',
|
||||
"sync settings container",
|
||||
method[0],
|
||||
flag.start(),
|
||||
)
|
||||
default = src.find(
|
||||
rf'string {var} = Path\.Combine\({BIOS_ROOT}, "([^"]+)"\);',
|
||||
"default GB BIOS",
|
||||
method[0],
|
||||
flag.start(),
|
||||
)
|
||||
chosen = list(
|
||||
re.compile(
|
||||
rf'(?:else )?if \(system == "(\w+)"\)\s*'
|
||||
rf'{var} = Path\.Combine\({BIOS_ROOT}, "([^"]+)"\);'
|
||||
).finditer(code, default.end(), flag.start())
|
||||
)
|
||||
if code[default.end() : flag.start()].count(f"{var} =") != len(chosen):
|
||||
raise LauncherPatternMissing(
|
||||
src.path, f"{var} choice at line {src.line(default.start())}"
|
||||
)
|
||||
ref = path_parts(
|
||||
src, src.lines(core.start(), core.end()), src.lines(default.start(), flag.end())
|
||||
)
|
||||
others = " && ".join(f'system != "{m.group(1)}"' for m in chosen)
|
||||
slots = [("other systems", default.group(1), others)]
|
||||
slots += [(m.group(1), m.group(2), f'system == "{m.group(1)}"') for m in chosen]
|
||||
for slot, name, system in slots:
|
||||
records.append(
|
||||
launcher_record(
|
||||
"bizhawk",
|
||||
"standalone",
|
||||
"fixed_name",
|
||||
[name],
|
||||
ref,
|
||||
slot=slot,
|
||||
case_insensitive=True,
|
||||
search_dir="bios",
|
||||
passes_to=(
|
||||
f"{config.group(1)} {container.group(1)} {key} = {on},"
|
||||
" only if the file exists, the path itself is not written"
|
||||
),
|
||||
fails_when_missing=f"{key} = {off}",
|
||||
depends_on_option=", ".join(
|
||||
c for c in (f'core == "{core.group(1)}"', f"{option} on", system) if c
|
||||
),
|
||||
)
|
||||
)
|
||||
return covered_records(
|
||||
src,
|
||||
records,
|
||||
# A DSi NAND boot copies the game itself to bios/dsi_nand.bin.
|
||||
skip=(r'string biosPath = AppConfig\.GetFullPath\("bios"\);',),
|
||||
)
|
||||
@@ -0,0 +1,448 @@
|
||||
"""RetroBat generators that copy BIOS files or write a folder under bios into a configuration."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
from .csharp_source import (
|
||||
LauncherPatternMissing,
|
||||
Record,
|
||||
Source,
|
||||
_array_at,
|
||||
_code,
|
||||
_method_of,
|
||||
_split_top,
|
||||
_strings,
|
||||
_throw_message,
|
||||
source_ref,
|
||||
)
|
||||
from .retrobat_config_files import value_writes
|
||||
from .retrobat_generators import GENERATORS, TARGET_ABSENT, BIOS_ROOT, joined, launcher_record
|
||||
from .retrobat_render import config_label, covered_records, path_parts, render, when
|
||||
from model.launcherrecords import join_emulators
|
||||
|
||||
|
||||
def _copies_if_absent(
|
||||
src: Source, emulator: str, build: str, within: tuple[int, int] | None = None
|
||||
) -> list[Record]:
|
||||
"""File.Copy(source, target) when the target is absent and the source exists,
|
||||
one record per method and target folder."""
|
||||
code = _code(src)
|
||||
start, end = within or (0, len(code))
|
||||
groups: dict[
|
||||
tuple[tuple[int, int], str], list[tuple[int, str, str, list[tuple[int, int]]]]
|
||||
] = {}
|
||||
for copy in re.compile(
|
||||
r"if \(!File\.Exists\((\w+)\) && File\.Exists\((\w+)\)\)\s*(?:\{\s*)?try \{ File\.Copy\(\2, \1\); \}"
|
||||
).finditer(code, start, end):
|
||||
target_var, source_var = copy.groups()
|
||||
method = _method_of(src, copy.start())
|
||||
source = render(src, source_var, method[0], copy.start())
|
||||
target = render(src, target_var, method[0], copy.start())
|
||||
if source is None or target is None or not source[0].startswith("bios/"):
|
||||
raise LauncherPatternMissing(src.path, f"copy at line {src.line(copy.start())}")
|
||||
folder, _, name = source[0].rpartition("/")
|
||||
destination = target[0].rpartition("/")[0]
|
||||
spans = [*source[1], *target[1], src.lines(copy.start(), copy.end())]
|
||||
groups.setdefault((method, destination), []).append((copy.start(), folder, name, spans))
|
||||
records = []
|
||||
for (_, destination), copies in groups.items():
|
||||
folders = {folder for _, folder, _, _ in copies}
|
||||
if len(folders) != 1:
|
||||
raise LauncherPatternMissing(src.path, f"one source folder for {destination}")
|
||||
conditions, returns = when(src, copies[0][0])
|
||||
records.append(
|
||||
launcher_record(
|
||||
emulator,
|
||||
build,
|
||||
"copies",
|
||||
[name for _, _, name, _ in copies],
|
||||
path_parts(src, *returns, *[s for c in copies for s in c[3]]),
|
||||
case_insensitive=True,
|
||||
search_dir=folders.pop(),
|
||||
passes_to=f"{destination}/<name>",
|
||||
fails_when_missing=False,
|
||||
depends_on_option=joined(*conditions, TARGET_ABSENT),
|
||||
)
|
||||
)
|
||||
if not records:
|
||||
raise LauncherPatternMissing(src.path, "copy when the target is absent")
|
||||
return records
|
||||
|
||||
|
||||
def dosbox_copies(sources: dict[str, Source]) -> list[Record]:
|
||||
"""MT-32 ROMs and SoundFonts copied from bios/scummvm/extra."""
|
||||
return [
|
||||
record
|
||||
for path, emulator in (
|
||||
(f"{GENERATORS}/DosBoxPure.Generator.cs", "dosbox-pure"),
|
||||
(f"{GENERATORS}/DosBoxStaging.Generator.cs", "dosbox-staging"),
|
||||
)
|
||||
for record in covered_records(
|
||||
sources[path], _copies_if_absent(sources[path], emulator, "standalone")
|
||||
)
|
||||
]
|
||||
|
||||
|
||||
def capsimg(sources: dict[str, Source]) -> list[Record]:
|
||||
"""capsimg.dll copied next to RetroArch for the cores that read .ipf images."""
|
||||
src = sources[f"{GENERATORS}/LibRetro.Generator.cs"]
|
||||
cores = src.find(
|
||||
r"static readonly List<string> (capsimgCore) = new List<string>\(\) \{", "capsimg core list"
|
||||
)
|
||||
names, core_lines = _array_at(src, cores.end() - 1)
|
||||
gate = src.find(
|
||||
rf"if \(core != null && rom != null && {cores.group(1)}\.Contains\(core\) && "
|
||||
r'Path\.GetExtension\(rom\)\.ToLowerInvariant\(\) == "([^"]+)"\)',
|
||||
"capsimg gate",
|
||||
)
|
||||
block = src.block_at(gate.end())
|
||||
[record] = _copies_if_absent(src, join_emulators(names), "libretro", block)
|
||||
record["source_ref"] = source_ref(
|
||||
(src.path, [(src.line(cores.start()), core_lines[1]), src.statement_span(block)])
|
||||
)
|
||||
record["depends_on_option"] = joined(
|
||||
f'core in {cores.group(1)}, rom extension "{gate.group(1)}"', TARGET_ABSENT
|
||||
)
|
||||
return [record]
|
||||
|
||||
|
||||
def tsugaru(sources: dict[str, Source]) -> list[Record]:
|
||||
"""The FM Towns ROM folder, chosen by where FMT_SYS.ROM is."""
|
||||
src = sources[f"{GENERATORS}/Tsugaru.Generator.cs"]
|
||||
code = _code(src)
|
||||
first = src.find(
|
||||
rf'if \(Directory\.Exists\((Path\.Combine\({BIOS_ROOT}, "[^"]+"\))\)\)\s*(\w+) = \1;',
|
||||
"first FM Towns folder",
|
||||
)
|
||||
var = first.group(2)
|
||||
method = _method_of(src, first.start())
|
||||
unset = src.find(rf"string {var} = null;", f"{var} declaration", method[0], first.start())
|
||||
folders = [render(src, first.group(1), method[0], first.start())]
|
||||
names, end = set(), first.end()
|
||||
step = re.compile(
|
||||
rf'\s*if \(!File\.Exists\(Path\.Combine\({var}, "([^"]+)"\)\)\)\s*{var} = ([^;]+);'
|
||||
)
|
||||
while more := step.match(code, end):
|
||||
names.add(more.group(1))
|
||||
folders.append(render(src, more.group(2), method[0], more.start()))
|
||||
end = more.end()
|
||||
final = re.compile(
|
||||
rf'\s*if \(!File\.Exists\(Path\.Combine\({var}, "([^"]+)"\)\)\)\s*\{{'
|
||||
).match(code, end)
|
||||
if final is None or any(folder is None for folder in folders):
|
||||
raise LauncherPatternMissing(src.path, "FMT_SYS.ROM folder chain")
|
||||
names.add(final.group(1))
|
||||
block = src.block_at(final.end() - 1)
|
||||
info = re.search(r'Info\("([^"]+)"\);\s*return null;', code[block[0] : block[1]])
|
||||
cmos = src.find(
|
||||
rf'commandArray\.Add\({var}\);\s*commandArray\.Add\("(-\w+)"\);\s*'
|
||||
rf'commandArray\.Add\(Path\.Combine\({var}, "([^"]+)"\)\);',
|
||||
"folder and CMOS arguments",
|
||||
block[1],
|
||||
method[1],
|
||||
)
|
||||
if info is None or len(names) != 1:
|
||||
raise LauncherPatternMissing(src.path, "FMT_SYS.ROM missing branch")
|
||||
record = launcher_record(
|
||||
"tsugaru",
|
||||
"standalone",
|
||||
"passes_path",
|
||||
sorted(names),
|
||||
path_parts(
|
||||
src, src.lines(unset.start(), unset.end()), src.lines(first.start(), cmos.end())
|
||||
),
|
||||
case_insensitive=True,
|
||||
search_dir=", then ".join(folder[0] for folder in folders if folder),
|
||||
passes_to=(
|
||||
"command line: first argument <folder found>,"
|
||||
f" {cmos.group(1)} <folder found>/{cmos.group(2)}"
|
||||
),
|
||||
fails_when_missing=f"info '{info.group(1)}', no launch",
|
||||
depends_on_option=(
|
||||
f"{folders[0][0] if folders[0] else ''} is a directory"
|
||||
f" ({var} stays null otherwise when {final.group(1)} is checked)"
|
||||
),
|
||||
)
|
||||
return covered_records(src, [record])
|
||||
|
||||
|
||||
def _indexer_writes(src: Source, emulator: str, writer: str) -> list[Record]:
|
||||
"""writer["key"] = value, for each value that resolves to a folder under bios."""
|
||||
code = _code(src)
|
||||
records = []
|
||||
for write in re.compile(rf'\b{writer}\["([^"]+)"\] = ([^;]+);').finditer(code):
|
||||
method = _method_of(src, write.start())
|
||||
rendered = render(src, src.text[write.start(2) : write.end(2)], method[0], write.start())
|
||||
if rendered is None or not rendered[0].startswith("bios"):
|
||||
continue
|
||||
conditions, returns = when(src, write.start())
|
||||
records.append(
|
||||
launcher_record(
|
||||
emulator,
|
||||
"standalone",
|
||||
"passes_path",
|
||||
[],
|
||||
path_parts(src, *returns, *rendered[1], src.lines(write.start(), write.end())),
|
||||
search_dir=rendered[0],
|
||||
passes_to=(
|
||||
f"{config_label(src, write.start(), writer)} {write.group(1)} = {rendered[0]}"
|
||||
),
|
||||
fails_when_missing=False,
|
||||
depends_on_option=", ".join(conditions) or None,
|
||||
)
|
||||
)
|
||||
if not records:
|
||||
raise LauncherPatternMissing(src.path, f"{writer}[...] write of a bios folder")
|
||||
return records
|
||||
|
||||
|
||||
def eka2l1(sources: dict[str, Source]) -> list[Record]:
|
||||
src = sources[f"{GENERATORS}/Eka2l1.Generator.cs"]
|
||||
return covered_records(src, _indexer_writes(src, "eka2l1", "yml"))
|
||||
|
||||
|
||||
def fbneo(sources: dict[str, Source]) -> list[Record]:
|
||||
src = sources[f"{GENERATORS}/Fbneo.Generator.cs"]
|
||||
return covered_records(src, _indexer_writes(src, "fbneo", "cfg"))
|
||||
|
||||
|
||||
def snes9x(sources: dict[str, Source]) -> list[Record]:
|
||||
src = sources[f"{GENERATORS}/Snes9x.Generator.cs"]
|
||||
entry = src.find(rf'\{{ "([^"]+)", (Path\.Combine\({BIOS_ROOT}\)) \}}', "bios folder entry")
|
||||
loop = src.find(
|
||||
r"foreach \(KeyValuePair<string, string> pair in (\w+)\)", "path loop", entry.end()
|
||||
)
|
||||
body = src.block_at(loop.end())
|
||||
write = src.find(
|
||||
r'(\w+)\.WriteValue\(@?"([^"]+)", pair\.Key, pair\.Value\);',
|
||||
"path write",
|
||||
body[0],
|
||||
body[1],
|
||||
)
|
||||
config = config_label(src, write.start(), write.group(1))
|
||||
record = launcher_record(
|
||||
"snes9x",
|
||||
"standalone",
|
||||
"passes_path",
|
||||
[],
|
||||
path_parts(src, src.lines(entry.start(), entry.end()), src.lines(loop.start(), body[1])),
|
||||
search_dir="bios",
|
||||
passes_to=f"{config} [{write.group(2)}] {entry.group(1)} = bios",
|
||||
fails_when_missing=False,
|
||||
)
|
||||
return covered_records(src, [record])
|
||||
|
||||
|
||||
def value_folders(sources: dict[str, Source]) -> list[Record]:
|
||||
"""Configuration keys given a folder under bios."""
|
||||
records = []
|
||||
for path, emulator, skip in (
|
||||
# VMU saves are synchronised with the libretro core's bios/dc.
|
||||
(f"{GENERATORS}/Flycast.Generator.cs", "flycast", (r"string libretroPath = ",)),
|
||||
(f"{GENERATORS}/ScummVm.Generator.cs", "scummvm", ()),
|
||||
):
|
||||
found = value_writes(sources[path], emulator, "standalone")
|
||||
if not found:
|
||||
raise LauncherPatternMissing(path, "bios folder write")
|
||||
records += covered_records(sources[path], found, skip=skip)
|
||||
return records
|
||||
|
||||
|
||||
def demul(sources: dict[str, Source]) -> list[Record]:
|
||||
src = sources[f"{GENERATORS}/Demul.Generator.cs"]
|
||||
listing = src.find(r"var (\w+) = new List<string>\s*\{", "rom paths list")
|
||||
block = src.block_at(listing.end() - 1)
|
||||
loop = src.find(
|
||||
rf"for \(int i = 0; i < {listing.group(1)}\.Count; i\+\+\)\s*"
|
||||
rf'(\w+)\.WriteValue\("(\w+)", "(\w+)" \+ i, {listing.group(1)}\[i\]\);',
|
||||
"rom paths write",
|
||||
block[1],
|
||||
)
|
||||
method = _method_of(src, listing.start())
|
||||
config = config_label(src, loop.start(), loop.group(1))
|
||||
records = []
|
||||
for index, item in enumerate(_split_top(src.text[block[0] + 1 : block[1] - 1].strip(), ",")):
|
||||
rendered = render(src, item, method[0], listing.start())
|
||||
if rendered is None:
|
||||
raise LauncherPatternMissing(src.path, f"rom path {item}")
|
||||
if not rendered[0].startswith("bios"):
|
||||
continue
|
||||
records.append(
|
||||
launcher_record(
|
||||
"demul",
|
||||
"standalone",
|
||||
"passes_path",
|
||||
[],
|
||||
path_parts(
|
||||
src,
|
||||
*rendered[1],
|
||||
src.lines(listing.start(), block[1]),
|
||||
src.lines(loop.start(), loop.end()),
|
||||
),
|
||||
search_dir=rendered[0],
|
||||
passes_to=f"{config} [{loop.group(2)}] {loop.group(3)}{index} = {rendered[0]}",
|
||||
fails_when_missing=False,
|
||||
)
|
||||
)
|
||||
return covered_records(src, records)
|
||||
|
||||
|
||||
def bsyndrome(sources: dict[str, Source]) -> list[Record]:
|
||||
src = sources[f"{GENERATORS}/PortsLauncher.Configuration.cs"]
|
||||
records = []
|
||||
for arg in src.find_all(
|
||||
r'string (\w+) = "(--\w+)=\\"" \+ (\w+) \+ "\\"";\s*commandArray\.Add\(\1\);',
|
||||
"path argument",
|
||||
):
|
||||
method = _method_of(src, arg.start())
|
||||
rendered = render(src, arg.group(3), method[0], arg.start())
|
||||
if rendered is None or not rendered[0].startswith("bios"):
|
||||
continue
|
||||
conditions, returns = when(src, arg.start())
|
||||
records.append(
|
||||
launcher_record(
|
||||
"bsyndrome",
|
||||
"standalone",
|
||||
"passes_path",
|
||||
[],
|
||||
path_parts(src, *returns, *rendered[1], src.lines(arg.start(), arg.end())),
|
||||
search_dir=rendered[0],
|
||||
passes_to=f"command line {arg.group(2)}={rendered[0]}",
|
||||
fails_when_missing=False,
|
||||
depends_on_option=", ".join(conditions) or None,
|
||||
)
|
||||
)
|
||||
if not records:
|
||||
raise LauncherPatternMissing(src.path, "bios folder argument")
|
||||
return covered_records(src, records)
|
||||
|
||||
|
||||
def xm6pro(sources: dict[str, Source]) -> list[Record]:
|
||||
src = sources[f"{GENERATORS}/Xm6pro.Generator.cs"]
|
||||
method = src.find(r"private void CopyBiosFiles\(string (\w+)\)", "CopyBiosFiles")
|
||||
body = src.block_at(method.end())
|
||||
loop = src.find(r"foreach \(string (\w+) in (\w+)\)", "copy loop", body[0], body[1])
|
||||
table = src.find(
|
||||
rf"static readonly string\[\] {loop.group(2)} = new string\[\] \{{", "X68000 BIOS list"
|
||||
)
|
||||
names, lines = _array_at(src, table.end() - 1)
|
||||
copy = src.find(
|
||||
rf"string (\w+) = Path\.Combine\((\w+), {loop.group(1)}\);\s*"
|
||||
rf"string (\w+) = Path\.Combine\({method.group(1)}, {loop.group(1)}\);\s*"
|
||||
r"if \(File\.Exists\(\1\) && !File\.Exists\(\3\)\)",
|
||||
"copy when the target is absent",
|
||||
loop.end(),
|
||||
body[1],
|
||||
)
|
||||
folder = render(src, copy.group(2), body[0], copy.start())
|
||||
if folder is None or not folder[0].startswith("bios/"):
|
||||
raise LauncherPatternMissing(src.path, "keropi folder")
|
||||
conditions, _ = when(src, loop.start())
|
||||
record = launcher_record(
|
||||
"xm6pro",
|
||||
"standalone",
|
||||
"copies",
|
||||
names,
|
||||
path_parts(src, (src.line(table.start()), lines[1]), src.lines(method.start(), body[1])),
|
||||
case_insensitive=True,
|
||||
search_dir=folder[0],
|
||||
passes_to="<emulator>/<name>",
|
||||
fails_when_missing=False,
|
||||
depends_on_option=joined(*conditions, TARGET_ABSENT),
|
||||
)
|
||||
return covered_records(src, [record])
|
||||
|
||||
|
||||
def arcadeduck(sources: dict[str, Source]) -> list[Record]:
|
||||
"""The BIOS archive ArcadeDuck's own database names for the game's system."""
|
||||
src = sources[f"{GENERATORS}/ArcadeDuck.Generator.cs"]
|
||||
db = sources[f"{GENERATORS}/ArcadeDuck.Database.cs"]
|
||||
database = db.find(
|
||||
r'string dbFile = Path\.Combine\(emulatorPath, ((?:"[^"]+"(?:, )?)+)\);', "database file"
|
||||
)
|
||||
lookup = db.find(r"public string GetBiosArchive\(string systemId\)", "GetBiosArchive")
|
||||
lookup_body = db.block_at(lookup.end())
|
||||
fixed = db.find(
|
||||
r'if \(systemId == "(\w+)"\)\s*return "([^"]+)";',
|
||||
"built-in archive",
|
||||
lookup_body[0],
|
||||
lookup_body[1],
|
||||
)
|
||||
method = src.find(
|
||||
r"private string GetBiosPath\(string rom, string biosRoot, bool isChd\)", "GetBiosPath"
|
||||
)
|
||||
body = src.block_at(method.end())
|
||||
src.find(
|
||||
r"string romDir = Path\.GetDirectoryName\(Path\.GetFullPath\(rom\)\);\s*"
|
||||
r"var candidates = new List<string> \{ romDir \};",
|
||||
"game folder first",
|
||||
body[0],
|
||||
body[1],
|
||||
)
|
||||
src.find(
|
||||
r"if \(isChd && Directory\.GetParent\(romDir\) != null\)\s*"
|
||||
r"candidates\.Add\(Directory\.GetParent\(romDir\)\.FullName\);",
|
||||
"folder above a CHD-only set second",
|
||||
body[0],
|
||||
body[1],
|
||||
)
|
||||
src.find(r"candidates\.Add\(biosRoot\);", "bios folder last", body[0], body[1])
|
||||
message, _ = _throw_message(src, body[0], body[1])
|
||||
root = src.find(rf"string biosPath = {BIOS_ROOT};", "bios root")
|
||||
write = src.find(r'ini\.WriteValue\("(\w+)", "(\w+)", biosPath\);', "SearchDirectory write")
|
||||
config = config_label(src, write.start(), "ini")
|
||||
target = f"{config} [{write.group(1)}] {write.group(2)}"
|
||||
database_file = "/".join(_strings(database.group(1)))
|
||||
ref = source_ref(
|
||||
(
|
||||
src.path,
|
||||
[
|
||||
src.lines(root.start(), root.end()),
|
||||
src.lines(method.start(), body[1]),
|
||||
src.lines(write.start(), write.end()),
|
||||
],
|
||||
),
|
||||
(
|
||||
db.path,
|
||||
[db.lines(database.start(), database.end()), db.lines(fixed.start(), fixed.end())],
|
||||
),
|
||||
)
|
||||
records = [
|
||||
launcher_record(
|
||||
"arcadeduck",
|
||||
"standalone",
|
||||
"names_searched",
|
||||
[f"<bios archive of the game's system in {database_file}>"],
|
||||
ref,
|
||||
case_insensitive=False,
|
||||
search_dir="<rom directory>, then the folder above it for a CHD-only set, then bios",
|
||||
passes_to=f"{target} = <folder found>",
|
||||
fails_when_missing=message,
|
||||
),
|
||||
launcher_record(
|
||||
"arcadeduck",
|
||||
"standalone",
|
||||
"names_searched",
|
||||
[fixed.group(2)],
|
||||
ref,
|
||||
slot=fixed.group(1),
|
||||
case_insensitive=False,
|
||||
search_dir="<rom directory>, then the folder above it for a CHD-only set, then bios",
|
||||
passes_to=f"{target} = <folder found>",
|
||||
fails_when_missing=message,
|
||||
depends_on_option=f"{database_file} names no archive for {fixed.group(1)}",
|
||||
),
|
||||
launcher_record(
|
||||
"arcadeduck",
|
||||
"standalone",
|
||||
"passes_path",
|
||||
[],
|
||||
ref,
|
||||
search_dir="bios",
|
||||
passes_to=f"{target} = bios",
|
||||
fails_when_missing=False,
|
||||
depends_on_option="no bios archive known for the game's system",
|
||||
),
|
||||
]
|
||||
return covered_records(src, records)
|
||||
@@ -0,0 +1,325 @@
|
||||
"""RetroBat generator paths, es_features.cfg choices, the record shape and the guarded BIOS writes."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
from .csharp_source import (
|
||||
LauncherPatternMissing,
|
||||
Record,
|
||||
STRING,
|
||||
Source,
|
||||
_METHOD,
|
||||
_call_args,
|
||||
_strings,
|
||||
source_ref,
|
||||
)
|
||||
|
||||
|
||||
GENERATORS = "emulatorLauncher/Generators"
|
||||
FEATURES = ".emulationstation/es_features.cfg"
|
||||
|
||||
|
||||
BIOS = r'AppConfig\.GetFullPath\("bios"\)'
|
||||
|
||||
|
||||
def system_feature_choices(
|
||||
src: Source, emulator: str, option: str, system: str
|
||||
) -> tuple[list[str], tuple[int, int]]:
|
||||
"""Values es_features.cfg offers for an option of an emulator under one system."""
|
||||
text = src.text
|
||||
for found in re.finditer(r'<emulator name="([^"]*)"', text):
|
||||
if emulator in [name.strip() for name in found.group(1).split(",")]:
|
||||
start, end = found.start(), text.find("</emulator>", found.start())
|
||||
break
|
||||
else:
|
||||
raise LauncherPatternMissing(src.path, f"emulator {emulator}")
|
||||
for block in re.finditer(r'<system name="([^"]*)">', text[start:end]):
|
||||
if system not in [name.strip() for name in block.group(1).split(",")]:
|
||||
continue
|
||||
scope = start + block.start()
|
||||
close = text.find("</system>", scope)
|
||||
feature = src.find(
|
||||
rf'<feature [^>]*value="{re.escape(option)}"', f"{option} of {system}", scope, close
|
||||
)
|
||||
stop = text.find("</feature>", feature.end())
|
||||
values = re.findall(r'<choice [^>]*value="([^"]*)"', text[feature.end():stop])
|
||||
if not values:
|
||||
raise LauncherPatternMissing(src.path, f"choices of {option} for {system}")
|
||||
return values, src.lines(feature.start(), stop + len("</feature>"))
|
||||
raise LauncherPatternMissing(src.path, f"system {system} of {emulator}")
|
||||
|
||||
|
||||
def feature_choices(
|
||||
src: Source, emulator: str, option: str, core: str | None = None
|
||||
) -> tuple[list[str], tuple[int, int]]:
|
||||
"""Values es_features.cfg offers for an option of one emulator or core."""
|
||||
text = src.text
|
||||
scope_start, scope_end = 0, len(text)
|
||||
for found in re.finditer(r'<emulator name="([^"]*)"', text):
|
||||
if emulator in [name.strip() for name in found.group(1).split(",")]:
|
||||
scope_start = found.start()
|
||||
scope_end = text.find("</emulator>", scope_start)
|
||||
break
|
||||
else:
|
||||
raise LauncherPatternMissing(src.path, f"emulator {emulator}")
|
||||
if core is not None:
|
||||
found = src.find(
|
||||
rf'<core name="{re.escape(core)}"', f"core {core} of {emulator}", scope_start, scope_end
|
||||
)
|
||||
scope_start, scope_end = found.start(), text.find("</core>", found.start())
|
||||
feature = src.find(
|
||||
rf'<feature [^>]*value="{re.escape(option)}"',
|
||||
f"feature {option} of {emulator}",
|
||||
scope_start,
|
||||
scope_end,
|
||||
)
|
||||
close = text.find("</feature>", feature.end())
|
||||
values = re.findall(r'<choice [^>]*value="([^"]*)"', text[feature.end() : close])
|
||||
if not values:
|
||||
raise LauncherPatternMissing(src.path, f"choices of {option}")
|
||||
return values, src.lines(feature.start(), close + len("</feature>"))
|
||||
|
||||
|
||||
# A copy record reads `names` from `search_dir` and hands them to the path in
|
||||
# `passes_to`. When the copy is skipped is a condition of the record.
|
||||
TARGET_ABSENT = "the target does not exist"
|
||||
|
||||
|
||||
def joined(*parts: str | None) -> str | None:
|
||||
"""Conditions of a record, joined, None when there are none."""
|
||||
return ", ".join(part for part in parts if part) or None
|
||||
|
||||
|
||||
def launcher_record(
|
||||
emulator: str, build: str, kind: str, names: list[str], ref: str, **fields: object
|
||||
) -> Record:
|
||||
record: Record = {"emulator": emulator, "build": build, "kind": kind, "names": names}
|
||||
record.update({key: value for key, value in fields.items() if value is not None})
|
||||
record["source_ref"] = ref
|
||||
return record
|
||||
|
||||
|
||||
# Generators that write each BIOS path into the emulator's configuration
|
||||
# only when the file exists: string x = Path.Combine(bios, ..., "name");
|
||||
# if (File.Exists(x)) ini.WriteValue("section", "key", x).
|
||||
GUARDED_WRITES = {
|
||||
f"{GENERATORS}/Jgenesis.Generator.cs": "jgenesis",
|
||||
f"{GENERATORS}/KegaFusion.Generator.cs": "kega-fusion",
|
||||
f"{GENERATORS}/MelonDS.Generator.cs": "melonds",
|
||||
f"{GENERATORS}/Mupen64.Generator.cs": "mupen64",
|
||||
f"{GENERATORS}/Project64.Generator.cs": "project64",
|
||||
f"{GENERATORS}/mGBA.Generator.cs": "mgba",
|
||||
}
|
||||
|
||||
TRANSPARENT = re.compile(r"(?:using\s*\(.*\)|try)")
|
||||
IF = re.compile(r"(?:else\s+)?if\s*\((.*)\)")
|
||||
_GUARD = re.compile(
|
||||
r'if \(File\.Exists\((\w+)\)\)\s*(\w+)\.WriteValue\("([^"]*)", "([^"]+)", ([^;\n]+)\);'
|
||||
)
|
||||
BIOS_ROOT = r'(?:Program\.)?AppConfig\.GetFullPath\("bios"\)'
|
||||
|
||||
|
||||
def negate(condition: str) -> str:
|
||||
"""The condition under which an early return is not taken.
|
||||
|
||||
A conjunction of inequalities becomes the disjunction of equalities,
|
||||
anything else is wrapped in not (...).
|
||||
"""
|
||||
tests = condition.split(" && ")
|
||||
compared = [m for t in tests if (m := re.fullmatch(rf"(\w+) != ({STRING})", t))]
|
||||
if len(compared) == len(tests):
|
||||
return " || ".join(f"{m.group(1)} == {m.group(2)}" for m in compared)
|
||||
return f"not ({condition})"
|
||||
|
||||
|
||||
Reach = tuple[tuple[int, int], list[str], list[tuple[int, int]]]
|
||||
|
||||
|
||||
def _conditions(src: Source, offset: int) -> Reach | None:
|
||||
"""The method holding offset, the conditions under which it is reached,
|
||||
and the lines of the early returns among them.
|
||||
|
||||
Each enclosing if adds its condition, and an early return at the top of
|
||||
the method adds the condition that does not return. None when a block in
|
||||
between is not an if, a using or a try: a loop or an else would need its
|
||||
own reading.
|
||||
"""
|
||||
enclosing: list[str] = []
|
||||
for block in sorted((b for b in src.blocks() if b[0] < offset < b[1]), reverse=True):
|
||||
header = src.header(block)
|
||||
if _METHOD.match(header):
|
||||
returns, spans = [], []
|
||||
for found in re.finditer(r"\bif \(", src.text[block[0] : offset]):
|
||||
paren = block[0] + found.end() - 1
|
||||
if src.enclosing(paren) != block:
|
||||
continue
|
||||
cond = _call_args(src, paren)
|
||||
tail = re.compile(r"\s*return\b[^;]*;").match(src.text, paren + len(cond) + 2)
|
||||
if tail:
|
||||
returns.append(negate(" ".join(cond.split())))
|
||||
spans.append(src.lines(block[0] + found.start(), tail.end()))
|
||||
return block, returns + enclosing[::-1], spans
|
||||
condition = IF.fullmatch(header)
|
||||
if condition:
|
||||
text = " ".join(condition.group(1).split())
|
||||
switch = re.fullmatch(
|
||||
r'SystemConfig\.isOptSet\("(\w+)"\) && SystemConfig\.getOptBoolean\("\1"\)', text
|
||||
)
|
||||
enclosing.append(f"{switch.group(1)} on" if switch else text)
|
||||
elif not TRANSPARENT.fullmatch(header):
|
||||
return None
|
||||
return None
|
||||
|
||||
|
||||
def _config_name(src: Source, method: tuple[int, int], writer: str) -> str:
|
||||
"""The file the writer variable opens, read in its method or else in the file."""
|
||||
opener = r"(\w+)\s*=\s*(?:\w+\.FromFile|new \w+)\((\w+)"
|
||||
declared = {
|
||||
m.group(1): "/".join(_strings(m.group(2)))
|
||||
for m in re.finditer(
|
||||
r'string (\w+) = Path\.Combine\(path, ((?:"[^"]+"(?:, )?)+)\);', src.text
|
||||
)
|
||||
}
|
||||
local = [
|
||||
m.group(2)
|
||||
for m in re.finditer(opener, src.text[method[0] : method[1]])
|
||||
if m.group(1) == writer and m.group(2) in declared
|
||||
]
|
||||
if local:
|
||||
return declared[local[0]]
|
||||
files = {declared[m.group(2)] for m in re.finditer(opener, src.text) if m.group(2) in declared}
|
||||
if len(files) != 1:
|
||||
raise LauncherPatternMissing(src.path, f"configuration file opened as {writer}")
|
||||
return files.pop()
|
||||
|
||||
|
||||
def root_writes(src: Source, emulator: str) -> list[Record]:
|
||||
"""Configuration keys that receive the bios folder itself."""
|
||||
records = []
|
||||
for root in re.finditer(rf"string (\w+) = {BIOS_ROOT};", src.text):
|
||||
root_reach = _conditions(src, root.start())
|
||||
if root_reach is None:
|
||||
continue
|
||||
method = root_reach[0]
|
||||
# A folder below the root, `string x = Path.Combine(root, "cdb")`
|
||||
# that the method creates or tests as a directory. A file below it
|
||||
# is a guarded write's, read by _guarded_write.
|
||||
folders = {root.group(1): ("bios", root)}
|
||||
for sub in re.compile(
|
||||
rf"string (\w+) = Path\.Combine\({root.group(1)}, ((?:{STRING}, )*{STRING})\);"
|
||||
).finditer(src.text, root.end(), method[1]):
|
||||
if re.search(
|
||||
rf"\b(?:\w*CreateDirectory|Directory\.Exists)\({sub.group(1)}\)",
|
||||
src.text[sub.end() : method[1]],
|
||||
):
|
||||
folders[sub.group(1)] = ("/".join(["bios", *_strings(sub.group(2))]), sub)
|
||||
names = "|".join(map(re.escape, folders))
|
||||
for write in re.compile(
|
||||
rf'(\w+)\.WriteValue\("([^"]*)", "([^"]+)", (?:"\'" \+ )?({names})(?: \+ "\'")?\);'
|
||||
).finditer(src.text, root.end(), method[1]):
|
||||
reached = _conditions(src, write.start())
|
||||
if reached is None:
|
||||
continue
|
||||
writer, section, key, held = write.groups()
|
||||
folder, declared = folders[held]
|
||||
target = f"[{section}] {key}" if section else key
|
||||
records.append(
|
||||
launcher_record(
|
||||
emulator,
|
||||
"standalone",
|
||||
"passes_path",
|
||||
[],
|
||||
source_ref(
|
||||
(
|
||||
src.path,
|
||||
[
|
||||
*reached[2],
|
||||
src.lines(root.start(), root.end()),
|
||||
*([src.lines(declared.start(), declared.end())]
|
||||
if declared is not root else []),
|
||||
src.lines(write.start(), write.end()),
|
||||
],
|
||||
)
|
||||
),
|
||||
search_dir=folder,
|
||||
passes_to=f"{_config_name(src, method, writer)} {target} = {folder}",
|
||||
fails_when_missing=False,
|
||||
depends_on_option=", ".join(reached[1]) or None,
|
||||
)
|
||||
)
|
||||
return records
|
||||
|
||||
|
||||
def _guarded_write(src: Source, emulator: str, guard: re.Match[str]) -> Record | None:
|
||||
"""The record of one guarded write, None when its shape is another one.
|
||||
|
||||
The written value must be the checked path itself (quoted or with its
|
||||
separators replaced), the path a literal under the bios folder that
|
||||
nothing reassigns before the check, and every block around the write an
|
||||
if, a using or a try.
|
||||
"""
|
||||
var, writer, section, key, value = guard.groups()
|
||||
if not re.fullmatch(
|
||||
rf"(?:{STRING} \+ )?{var}(?:\.Replace\({STRING}, {STRING}\))?(?: \+ {STRING})?",
|
||||
value.strip(),
|
||||
):
|
||||
return None
|
||||
reached = _conditions(src, guard.start())
|
||||
if reached is None:
|
||||
return None
|
||||
method, conditions, returns = reached
|
||||
decls = list(
|
||||
re.compile(
|
||||
rf"string {var} = Path\.Combine\((\w+|{BIOS_ROOT}), ((?:{STRING}, )*{STRING})\);"
|
||||
).finditer(src.text, method[0], guard.start())
|
||||
)
|
||||
if not decls or re.search(rf"\b{var}\s*=[^=]", src.text[decls[-1].end() : guard.start()]):
|
||||
return None
|
||||
decl = decls[-1]
|
||||
root = decl.group(1)
|
||||
if not re.fullmatch(BIOS_ROOT, root) and not re.search(
|
||||
rf"string {root} = {BIOS_ROOT};", src.text[method[0] : decl.start()]
|
||||
):
|
||||
return None
|
||||
*folders, name = _strings(decl.group(2))
|
||||
target = f"[{section}] {key}" if section else key
|
||||
return launcher_record(
|
||||
emulator,
|
||||
"standalone",
|
||||
"fixed_name",
|
||||
[name],
|
||||
source_ref(
|
||||
(
|
||||
src.path,
|
||||
[
|
||||
*returns,
|
||||
src.lines(decl.start(), decl.end()),
|
||||
src.lines(guard.start(), guard.end()),
|
||||
],
|
||||
)
|
||||
),
|
||||
case_insensitive=True,
|
||||
search_dir="/".join(["bios", *folders]),
|
||||
passes_to=f"{_config_name(src, method, writer)} {target}, only if the file exists",
|
||||
fails_when_missing=f"{key} not written",
|
||||
depends_on_option=", ".join(conditions) or None,
|
||||
)
|
||||
|
||||
|
||||
def guarded_writes_in(src: Source, emulator: str) -> list[Record]:
|
||||
"""Every guarded write of one generator, then the keys given the bios folder."""
|
||||
found = [_guarded_write(src, emulator, guard) for guard in _GUARD.finditer(src.text)]
|
||||
records = [record for record in found if record is not None]
|
||||
if not records:
|
||||
raise LauncherPatternMissing(src.path, "File.Exists guarded WriteValue")
|
||||
return records + root_writes(src, emulator)
|
||||
|
||||
|
||||
def guarded_writes(sources: dict[str, Source]) -> list[Record]:
|
||||
"""One fixed name per configuration key, written only when the file exists."""
|
||||
return [
|
||||
record
|
||||
for path, emulator in GUARDED_WRITES.items()
|
||||
for record in guarded_writes_in(sources[path], emulator)
|
||||
]
|
||||
@@ -0,0 +1,344 @@
|
||||
"""RetroBat launcher records of PCSX2, the PS1 BIOS cascades and DuckStation."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
from .csharp_source import (
|
||||
LauncherPatternMissing,
|
||||
Record,
|
||||
Source,
|
||||
_array_at,
|
||||
_code_chars,
|
||||
_strings,
|
||||
_throw_message,
|
||||
_unique,
|
||||
source_ref,
|
||||
)
|
||||
from .retrobat_generators import (
|
||||
BIOS,
|
||||
FEATURES,
|
||||
GENERATORS,
|
||||
launcher_record,
|
||||
feature_choices,
|
||||
)
|
||||
|
||||
|
||||
def pcsx2(sources: dict[str, Source]) -> list[Record]:
|
||||
src = sources[f"{GENERATORS}/Pcsx2.Generator.cs"]
|
||||
records = []
|
||||
|
||||
qt = src.find(r"private void SetupConfigurationQT\(", "SetupConfigurationQT")
|
||||
qt_body = src.block_at(qt.end())
|
||||
folder = src.find(
|
||||
rf'string biosPath = Path\.Combine\({BIOS}, ((?:"[^"]+"(?:, )?)+)\);',
|
||||
"Qt BIOS folder",
|
||||
qt_body[0],
|
||||
qt_body[1],
|
||||
)
|
||||
src.find(
|
||||
r"Directory\.GetFiles\(biosPath\)\.Length == 0\)[^\n]*\n\s*biosPath = " + BIOS,
|
||||
"empty folder fallback",
|
||||
folder.end(),
|
||||
qt_body[1],
|
||||
)
|
||||
write = src.find(
|
||||
r'ini\.WriteValue\("Filenames", "BIOS", biosFile\);',
|
||||
"Qt BIOS write",
|
||||
folder.end(),
|
||||
qt_body[1],
|
||||
)
|
||||
message, _ = _throw_message(src, folder.end(), write.start())
|
||||
src.find(r'SystemConfig\["pcsx2_forcebios"\]', "pcsx2_forcebios", folder.end(), write.start())
|
||||
sub = "/".join(_strings(folder.group(1)))
|
||||
for var in ("biosList", "arcadeBiosList"):
|
||||
decl = src.find(rf"var {var} = new string\[\] \{{", f"Qt {var}", qt_body[0], qt_body[1])
|
||||
names, lines = _array_at(src, decl.end() - 1)
|
||||
records.append(
|
||||
launcher_record(
|
||||
"pcsx2",
|
||||
"standalone",
|
||||
"names_searched",
|
||||
names,
|
||||
source_ref(
|
||||
(
|
||||
src.path,
|
||||
[
|
||||
(src.line(decl.start()), lines[1]),
|
||||
src.lines(folder.start(), write.end()),
|
||||
],
|
||||
)
|
||||
),
|
||||
case_insensitive=True,
|
||||
search_dir=f"bios/{sub} (bios when bios/{sub} holds no file)",
|
||||
passes_to="inis/PCSX2.ini [Folders] Bios, [Filenames] BIOS",
|
||||
fails_when_missing=message,
|
||||
depends_on_option="pcsx2_forcebios",
|
||||
)
|
||||
)
|
||||
|
||||
legacy = src.find(r"private void SetupPaths\(", "SetupPaths")
|
||||
legacy_body = src.block_at(legacy.end())
|
||||
decl = src.find(
|
||||
r"var biosList = new string\[\] \{", "1.6 biosList", legacy_body[0], legacy_body[1]
|
||||
)
|
||||
names, lines = _array_at(src, decl.end() - 1)
|
||||
case = src.find(r'case "BIOS":', "1.6 BIOS case", legacy_body[0], legacy_body[1])
|
||||
default = src.find(
|
||||
r'value = "([^"]+)";\s*break;', "1.6 default BIOS", case.end(), legacy_body[1]
|
||||
)
|
||||
folder = src.find(
|
||||
r'File\.Exists\(Path\.Combine\(biosPath, ((?:"[^"]+", )+)b\)\)',
|
||||
"1.6 BIOS folder",
|
||||
legacy_body[0],
|
||||
legacy_body[1],
|
||||
)
|
||||
sub = "/".join(_strings(folder.group(1)))
|
||||
records.append(
|
||||
launcher_record(
|
||||
"pcsx2",
|
||||
"standalone",
|
||||
"names_searched",
|
||||
names,
|
||||
source_ref(
|
||||
(
|
||||
src.path,
|
||||
[(src.line(decl.start()), lines[1]), src.lines(case.start(), default.end())],
|
||||
)
|
||||
),
|
||||
case_insensitive=True,
|
||||
search_dir=f"bios/{sub} if any listed name is there, else bios",
|
||||
passes_to="inis/PCSX2_ui.ini [Folders] Bios, [Filenames] BIOS",
|
||||
fails_when_missing=f"no error: BIOS name defaults to {default.group(1)}",
|
||||
depends_on_option="pcsx2_forcebios",
|
||||
)
|
||||
)
|
||||
return records
|
||||
|
||||
|
||||
def pcsx2_libretro(sources: dict[str, Source]) -> list[Record]:
|
||||
src = sources[f"{GENERATORS}/LibRetro.CoreOptions.cs"]
|
||||
features = sources[FEATURES]
|
||||
guard = src.find(r'if \(core != "pcsx2"\)', "pcsx2 guard")
|
||||
method = src.enclosing(guard.start())
|
||||
folder = src.find(
|
||||
r'string ps2BiosFolder = Path\.Combine\(biosRoot, ((?:"[^"]+"(?:, )?)+)\);',
|
||||
"LRPS2 folder",
|
||||
method[0],
|
||||
method[1],
|
||||
)
|
||||
option = src.find(r'isOptSet\("(lrps2_bios)"\)', "lrps2_bios", folder.end(), method[1])
|
||||
write = src.find(
|
||||
r'coreSettings\["(pcsx2_bios)"\] = \w+;', "pcsx2_bios write", option.end(), method[1]
|
||||
)
|
||||
message, _ = _throw_message(src, option.end(), write.start())
|
||||
choices, choice_lines = feature_choices(features, "libretro", option.group(1), core="pcsx2")
|
||||
sub = "/".join(_strings(folder.group(1)))
|
||||
records = [
|
||||
launcher_record(
|
||||
"pcsx2",
|
||||
"libretro",
|
||||
"core_option",
|
||||
choices,
|
||||
source_ref(
|
||||
(src.path, [src.lines(folder.start(), write.end())]),
|
||||
(features.path, [choice_lines]),
|
||||
),
|
||||
case_insensitive=True,
|
||||
search_dir=f"<system_directory>/{sub}",
|
||||
passes_to=f"{write.group(1)} = <value>",
|
||||
fails_when_missing=message,
|
||||
depends_on_option=option.group(1),
|
||||
)
|
||||
]
|
||||
|
||||
scan = src.find(
|
||||
r"private static string GetFirstPS2Bios\(string biosFolder\)", "GetFirstPS2Bios"
|
||||
)
|
||||
scan_body = src.block_at(scan.end())
|
||||
preferred = src.find(
|
||||
r'n\.Equals\("([^"]+)", StringComparison\.OrdinalIgnoreCase\)',
|
||||
"preferred PS2 BIOS",
|
||||
scan_body[0],
|
||||
scan_body[1],
|
||||
)
|
||||
sizes = src.find(
|
||||
r"MIN_BIOS_SIZE = (\d+) \* 1024 \* 1024;\s*const long MAX_BIOS_SIZE = (\d+) \* 1024 \* 1024;",
|
||||
"BIOS size bounds",
|
||||
scan_body[0],
|
||||
scan_body[1],
|
||||
)
|
||||
auto = src.find(
|
||||
r"string autoBios = GetFirstPS2Bios\(ps2BiosFolder\);",
|
||||
"GetFirstPS2Bios call",
|
||||
write.end(),
|
||||
method[1],
|
||||
)
|
||||
auto_write = src.find(
|
||||
r'coreSettings\["pcsx2_bios"\] = autoBios;', "autoBios write", auto.end(), method[1]
|
||||
)
|
||||
auto_message, _ = _throw_message(src, auto.end(), auto_write.start())
|
||||
records.append(
|
||||
launcher_record(
|
||||
"pcsx2",
|
||||
"libretro",
|
||||
"scans_dir",
|
||||
[
|
||||
preferred.group(1),
|
||||
f"<first file {sizes.group(1)}-{sizes.group(2)} MiB, ordinal-ignore-case>",
|
||||
],
|
||||
source_ref(
|
||||
(
|
||||
src.path,
|
||||
[
|
||||
(src.line(scan.start()), src.lines(*scan_body)[1]),
|
||||
src.lines(auto.start(), auto_write.end()),
|
||||
],
|
||||
)
|
||||
),
|
||||
case_insensitive=True,
|
||||
search_dir=f"<system_directory>/{sub}",
|
||||
passes_to="pcsx2_bios = <chosen name>",
|
||||
fails_when_missing=auto_message,
|
||||
depends_on_option=f"{option.group(1)} unset",
|
||||
)
|
||||
)
|
||||
return records
|
||||
|
||||
|
||||
PSX_CASCADES = {
|
||||
f"{GENERATORS}/Bizhawk.Generator.cs": ("bizhawk", "standalone"),
|
||||
f"{GENERATORS}/Mednafen.Generator.cs": ("mednafen", "standalone"),
|
||||
f"{GENERATORS}/LibRetro.CoreOptions.cs": (None, "libretro"),
|
||||
}
|
||||
|
||||
|
||||
def _top_level_else(src: Source, block: tuple[int, int]) -> int | None:
|
||||
"""Offset of the last else of an if chain at the top of a block, not an else if."""
|
||||
depth, last = 0, None
|
||||
for offset, char in _code_chars(src.text[block[0] + 1 : block[1] - 1]):
|
||||
absolute = block[0] + 1 + offset
|
||||
if char in "{(":
|
||||
depth += 1
|
||||
elif char in "})":
|
||||
depth -= 1
|
||||
elif (
|
||||
depth == 0
|
||||
and src.text.startswith("else", absolute)
|
||||
and not re.match(r"else\s+if\b", src.text[absolute:])
|
||||
):
|
||||
last = absolute
|
||||
return last
|
||||
|
||||
|
||||
def psx_cascades(sources: dict[str, Source]) -> list[Record]:
|
||||
"""psxonpsp660.bin, then ps1_rom.bin, then one file per region."""
|
||||
records = []
|
||||
for path, (fixed_emulator, build) in PSX_CASCADES.items():
|
||||
src = sources[path]
|
||||
for cascade in src.find_all(
|
||||
r'if \(!SystemConfig\.getOptBoolean\("(\w+_original_bios)"\)\)', "PSX BIOS cascade"
|
||||
):
|
||||
emulator = fixed_emulator
|
||||
if emulator is None:
|
||||
guards = re.findall(r'if \(core != "([^"]+)"\)', src.text[: cascade.start()])
|
||||
if not guards:
|
||||
raise LauncherPatternMissing(path, "core guard before the PSX cascade")
|
||||
emulator = guards[-1]
|
||||
branch = src.block_at(cascade.end())
|
||||
after = re.compile(r"\s*else\s*(\{|[^;]*;)").match(src.text, branch[1])
|
||||
if after is None:
|
||||
raise LauncherPatternMissing(
|
||||
path, f"else after the PSX cascade at line {src.line(cascade.start())}"
|
||||
)
|
||||
original_end = src.block_at(after.start(1))[1] if after.group(1) == "{" else after.end()
|
||||
final_else = _top_level_else(src, branch)
|
||||
if final_else is None:
|
||||
raise LauncherPatternMissing(
|
||||
path, f"final else of the PSX cascade at line {src.line(cascade.start())}"
|
||||
)
|
||||
searched = _unique(
|
||||
re.findall(rf'Path\.Combine\({BIOS}, "([^"]+)"\)', src.text[branch[0] : final_else])
|
||||
)
|
||||
if not searched:
|
||||
raise LauncherPatternMissing(path, "searched PSX BIOS names")
|
||||
keys = _unique(re.findall(r'\w+\["([^"]+)"\]\s*=', src.text[branch[0] : branch[1]]))
|
||||
ref = source_ref((path, [src.lines(cascade.start(), original_end)]))
|
||||
records.append(
|
||||
launcher_record(
|
||||
emulator,
|
||||
build,
|
||||
"names_searched",
|
||||
searched,
|
||||
ref,
|
||||
case_insensitive=True,
|
||||
search_dir="bios",
|
||||
passes_to=", ".join(keys),
|
||||
fails_when_missing=False,
|
||||
depends_on_option=f"{cascade.group(1)} off",
|
||||
)
|
||||
)
|
||||
fallback_text = src.text[final_else : branch[1]]
|
||||
fallback = _unique([n for n in _strings(fallback_text) if n.lower().endswith(".bin")])
|
||||
if fallback:
|
||||
checked = "File.Exists" in fallback_text
|
||||
records.append(
|
||||
launcher_record(
|
||||
emulator,
|
||||
build,
|
||||
"fixed_name",
|
||||
fallback,
|
||||
ref,
|
||||
case_insensitive=True,
|
||||
search_dir="bios",
|
||||
passes_to=", ".join(keys),
|
||||
fails_when_missing=(
|
||||
False if checked else "names written without an existence check"
|
||||
),
|
||||
)
|
||||
)
|
||||
return records
|
||||
|
||||
|
||||
def duckstation(sources: dict[str, Source]) -> list[Record]:
|
||||
src = sources[f"{GENERATORS}/Duckstation.Generator.cs"]
|
||||
features = sources[FEATURES]
|
||||
search = src.find(
|
||||
r'ini\.WriteValue\("BIOS", "SearchDirectory", biosPath\);', "SearchDirectory write"
|
||||
)
|
||||
option = src.find(r'isOptSet\("(duck_bios)"\)', "duck_bios", search.end())
|
||||
block = src.block_at(option.end())
|
||||
keys = re.findall(
|
||||
r'ini\.WriteValue\("BIOS", "(\w+)", SystemConfig\["duck_bios"\]\);',
|
||||
src.text[block[0] : block[1]],
|
||||
)
|
||||
if not keys:
|
||||
raise LauncherPatternMissing(src.path, "duck_bios writes")
|
||||
cleared = src.block_at(block[1])
|
||||
choices, choice_lines = feature_choices(features, "duckstation", option.group(1))
|
||||
return [
|
||||
launcher_record(
|
||||
"duckstation",
|
||||
"standalone",
|
||||
"passes_path",
|
||||
[],
|
||||
source_ref((src.path, [src.lines(search.start(), search.end()), src.lines(*cleared)])),
|
||||
search_dir="bios",
|
||||
passes_to="settings.ini [BIOS] SearchDirectory = bios",
|
||||
fails_when_missing=False,
|
||||
depends_on_option=f"{option.group(1)} unset",
|
||||
),
|
||||
launcher_record(
|
||||
"duckstation",
|
||||
"standalone",
|
||||
"core_option",
|
||||
choices,
|
||||
source_ref(
|
||||
(src.path, [src.lines(option.start(), block[1])]), (features.path, [choice_lines])
|
||||
),
|
||||
search_dir="bios",
|
||||
passes_to="settings.ini [BIOS] " + " = ".join(keys) + " = <value>",
|
||||
fails_when_missing="not checked by the launcher",
|
||||
depends_on_option=option.group(1),
|
||||
),
|
||||
]
|
||||
@@ -0,0 +1,497 @@
|
||||
"""RetroBat C# path expressions rendered as text, with the conditions a write runs under."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
from .csharp_source import (
|
||||
LauncherPatternMissing,
|
||||
Record,
|
||||
STRING,
|
||||
Source,
|
||||
_METHOD,
|
||||
_call_args,
|
||||
_code,
|
||||
_method_of,
|
||||
_split_top,
|
||||
_statement_end,
|
||||
_statement_start,
|
||||
_strings,
|
||||
_unescape,
|
||||
_wrapped,
|
||||
source_ref,
|
||||
)
|
||||
from .retrobat_generators import (
|
||||
FEATURES,
|
||||
GENERATORS,
|
||||
BIOS_ROOT,
|
||||
IF,
|
||||
TRANSPARENT,
|
||||
negate,
|
||||
launcher_record,
|
||||
root_writes,
|
||||
feature_choices,
|
||||
)
|
||||
|
||||
|
||||
# Expression rendering for the generators below: a path expression becomes
|
||||
# bios/<folders>/<name>, <x> for AppConfig.GetFullPath("x"), <emulator> for
|
||||
# the emulator's own folder, and None when it is built from anything else.
|
||||
|
||||
_PATH_PARAMS = {"path": "<emulator>", "emulatorPath": "<emulator>", "_path": "<emulator>"}
|
||||
_KNOWN = {
|
||||
"Path.GetDirectoryName(rom)": "<rom directory>",
|
||||
"Path.GetDirectoryName(Path.GetFullPath(rom))": "<rom directory>",
|
||||
"rom": "<rom>",
|
||||
}
|
||||
_WRAPPERS = ("EnsureDirectoryExists",)
|
||||
|
||||
Rendered = tuple[str, list[tuple[int, int]]]
|
||||
|
||||
|
||||
_ATOM = r"!?[\w.]+(?:\((?:[^()]|\([^()]*\))*\))?"
|
||||
|
||||
|
||||
def _negated(condition: str) -> str:
|
||||
"""not condition, written as a C# reader would."""
|
||||
if re.fullmatch(_ATOM, condition):
|
||||
return condition[1:] if condition.startswith("!") else f"!{condition}"
|
||||
return negate(condition)
|
||||
|
||||
|
||||
def _owner_condition(src: Source, start: int) -> str | None:
|
||||
"""Condition of the if whose statement or block ends just before start."""
|
||||
code = _code(src)
|
||||
before = code[:start].rstrip()
|
||||
if before.endswith("}"):
|
||||
block = max(b for b in src.blocks() if b[1] == len(before))
|
||||
owner = IF.fullmatch(src.header(block))
|
||||
return owner.group(1) if owner else None
|
||||
if not before.endswith(";"):
|
||||
return None
|
||||
owner_start = _statement_start(src, len(before) - 1)
|
||||
head = re.match(r"(?:else\s+)?if\s*\(", code[owner_start:])
|
||||
if head is None:
|
||||
return None
|
||||
return " ".join(_call_args(src, owner_start + head.end() - 1).split())
|
||||
|
||||
|
||||
def _braceless_if(src: Source, offset: int) -> str | None:
|
||||
"""Condition of an if or else without braces that owns the statement at offset."""
|
||||
code = _code(src)
|
||||
start = _statement_start(src, offset)
|
||||
if re.fullmatch(r"else\s*", code[start:offset]):
|
||||
owner = _owner_condition(src, start)
|
||||
return _negated(owner) if owner else None
|
||||
head = re.search(r"(?:else\s+)?if\s*\(", code[start:offset])
|
||||
if head is None or head.start() != 0:
|
||||
return None
|
||||
paren = start + head.end() - 1
|
||||
condition = _call_args(src, paren)
|
||||
rest = code[paren + len(condition) + 2 : offset]
|
||||
if rest.strip():
|
||||
return None
|
||||
return " ".join(condition.split())
|
||||
|
||||
|
||||
def render(src: Source, expr: str, scope: int, before: int) -> Rendered | None:
|
||||
"""A path expression as text, with the lines of the declarations it read."""
|
||||
expr = " ".join(expr.split())
|
||||
fixed = _render_fixed(expr)
|
||||
if fixed is not None:
|
||||
return fixed
|
||||
replaced = re.fullmatch(rf"(.+)\.Replace\({STRING}, {STRING}\)", expr)
|
||||
if replaced:
|
||||
return render(src, replaced.group(1), scope, before)
|
||||
for wrapper in _WRAPPERS:
|
||||
inner = _wrapped(expr, wrapper)
|
||||
if inner is not None:
|
||||
return render(src, inner, scope, before)
|
||||
ternary = _split_top(expr, "?")
|
||||
if len(ternary) == 2:
|
||||
branches = _split_top(ternary[1], ":")
|
||||
if len(branches) == 2:
|
||||
return _render_choice(src, ternary[0], branches, scope, before)
|
||||
terms = _split_top(expr, " + ")
|
||||
if len(terms) > 1:
|
||||
return _render_terms(src, terms, scope, before)
|
||||
combine = _wrapped(expr, "Path.Combine")
|
||||
if combine is not None:
|
||||
base, *rest = _split_top(combine, ",")
|
||||
root = render(src, base, scope, before)
|
||||
literals = [re.fullmatch(STRING, part) for part in rest]
|
||||
if root is None or not all(literals):
|
||||
return None
|
||||
return "/".join([root[0], *(_unescape(m.group(1)) for m in literals if m)]), root[1]
|
||||
if expr in _PATH_PARAMS:
|
||||
return _PATH_PARAMS[expr], []
|
||||
if re.fullmatch(r"\w+", expr):
|
||||
return _render_variable(src, expr, scope, before)
|
||||
return None
|
||||
|
||||
|
||||
def _render_fixed(expr: str) -> Rendered | None:
|
||||
"""The expressions that name one known folder or file."""
|
||||
if re.fullmatch(BIOS_ROOT, expr):
|
||||
return "bios", []
|
||||
changed = re.fullmatch(r'Path\.ChangeExtension\(exe, "(\.\w+)"\)', expr)
|
||||
if changed:
|
||||
return f"<exe>{changed.group(1)}", []
|
||||
named = re.fullmatch(r'(?:Program\.)?AppConfig\.GetFullPath\("([\w.-]+)"\)', expr)
|
||||
if named:
|
||||
return f"<{named.group(1)}>", []
|
||||
if expr in _KNOWN:
|
||||
return _KNOWN[expr], []
|
||||
return None
|
||||
|
||||
|
||||
def _render_choice(
|
||||
src: Source, condition: str, branches: list[str], scope: int, before: int
|
||||
) -> Rendered | None:
|
||||
"""A `condition ? a : b` expression."""
|
||||
first = render(src, branches[0], scope, before)
|
||||
second = render(src, branches[1], scope, before)
|
||||
if first is None or second is None:
|
||||
return None
|
||||
return f"{first[0]} when {condition}, else {second[0]}", first[1] + second[1]
|
||||
|
||||
|
||||
def _render_terms(src: Source, terms: list[str], scope: int, before: int) -> Rendered | None:
|
||||
"""A concatenation, the quotes wrapped around it dropped."""
|
||||
while terms and terms[0] == '"\\""':
|
||||
terms = terms[1:]
|
||||
while terms and terms[-1] in ('"\\""', '"\\\\"'):
|
||||
terms = terms[:-1]
|
||||
pieces, spans = [], []
|
||||
for term in terms:
|
||||
if term == '";"':
|
||||
pieces.append(";")
|
||||
continue
|
||||
done = render(src, term, scope, before)
|
||||
if done is None:
|
||||
return None
|
||||
pieces.append(done[0])
|
||||
spans += done[1]
|
||||
return "".join(pieces), spans
|
||||
|
||||
|
||||
def _render_variable(src: Source, expr: str, scope: int, before: int) -> Rendered | None:
|
||||
"""A local variable, from its declaration and every later assignment before use."""
|
||||
code = _code(src)
|
||||
decls = list(re.compile(rf"(?:string|var)\s+{expr}\s*=\s*").finditer(code, scope, before))
|
||||
if not decls:
|
||||
return (_PATH_PARAMS[expr], []) if expr in _PATH_PARAMS else None
|
||||
decl = decls[-1]
|
||||
decl_end = _statement_end(src, decl.end())
|
||||
declared = render(src, src.text[decl.end() : decl_end], scope, decl.start())
|
||||
if declared is None:
|
||||
return None
|
||||
text, spans = declared[0], [*declared[1], src.lines(decl.start(), decl_end)]
|
||||
for again in re.compile(rf"(?<![\w.]){expr}\s*=(?!=)\s*").finditer(code, decl_end, before):
|
||||
again_end = _statement_end(src, again.end())
|
||||
value = render(src, src.text[again.end() : again_end], scope, again.start())
|
||||
if value is None:
|
||||
return None
|
||||
condition = _braceless_if(src, again.start())
|
||||
text += f", or {value[0]}" + (f" when {_readable(condition)}" if condition else "")
|
||||
spans += [*value[1], src.lines(_statement_start(src, again.start()), again_end)]
|
||||
return text, spans
|
||||
|
||||
|
||||
_OPTION_FORMS = (
|
||||
(r'SystemConfig\.isOptSet\("(\w+)"\) && SystemConfig\.getOptBoolean\("\1"\)', r"\1 on"),
|
||||
(
|
||||
r'SystemConfig\.isOptSet\("(\w+)"\) && !string\.IsNullOrEmpty\(SystemConfig\["\1"\]\)',
|
||||
r"\1 set",
|
||||
),
|
||||
(r'SystemConfig\.getOptBoolean\("(\w+)"\)', r"\1 on"),
|
||||
(r'SystemConfig\["(\w+)"\]', r"\1"),
|
||||
)
|
||||
|
||||
|
||||
def _readable(condition: str) -> str:
|
||||
text = " ".join(condition.split())
|
||||
for pattern, replacement in _OPTION_FORMS:
|
||||
text = re.sub(pattern, replacement, text)
|
||||
return text
|
||||
|
||||
|
||||
# Early returns taken when the emulator itself is not installed.
|
||||
_EMULATOR_MISSING = (
|
||||
r"!File\.Exists\(exe\)|!Directory\.Exists\(path\)|string\.IsNullOrEmpty\((?:path|exe)\)"
|
||||
)
|
||||
|
||||
|
||||
def when(src: Source, offset: int) -> tuple[list[str], list[tuple[int, int]]]:
|
||||
"""Conditions under which the statement at offset runs, outermost first,
|
||||
with the lines of the early returns among them.
|
||||
|
||||
A braceless if, every enclosing if, else and loop up to the method, and
|
||||
the early returns at the top of the method.
|
||||
"""
|
||||
found: list[str] = []
|
||||
own = _braceless_if(src, offset)
|
||||
if own:
|
||||
found.append(_readable(own))
|
||||
for block in sorted((b for b in src.blocks() if b[0] < offset < b[1]), reverse=True):
|
||||
header = src.header(block)
|
||||
if _METHOD.match(header):
|
||||
returns, spans = [], []
|
||||
code = _code(src)
|
||||
for early in re.finditer(r"\bif \(", code[block[0] : offset]):
|
||||
paren = block[0] + early.end() - 1
|
||||
if src.enclosing(paren) != block:
|
||||
continue
|
||||
cond = _call_args(src, paren)
|
||||
tail = re.compile(r"\s*return\b[^;]*;").match(code, paren + len(cond) + 2)
|
||||
cond = " ".join(cond.split())
|
||||
if tail and not re.fullmatch(_EMULATOR_MISSING, cond):
|
||||
returns.append(_readable(_negated(cond)))
|
||||
spans.append(src.lines(block[0] + early.start(), tail.end()))
|
||||
return returns + found[::-1], spans
|
||||
condition = IF.fullmatch(header)
|
||||
if condition:
|
||||
found.append(_readable(condition.group(1)))
|
||||
elif header == "else":
|
||||
previous = max(b for b in src.blocks() if b[1] <= block[0])
|
||||
owner = IF.fullmatch(src.header(previous))
|
||||
found.append(f"not ({_readable(owner.group(1))})" if owner else "else")
|
||||
elif not TRANSPARENT.fullmatch(header) and not header.startswith(("catch", "lock")):
|
||||
found.append(header)
|
||||
raise LauncherPatternMissing(src.path, f"method around line {src.line(offset)}")
|
||||
|
||||
|
||||
def _argument_of(src: Source, method: tuple[int, int], parameter: str) -> Rendered | None:
|
||||
"""A parameter of method, rendered from the argument its one caller passes."""
|
||||
header = src.header(method)
|
||||
signature = re.search(r"(\w+)\s*\((.*)\)\s*$", header)
|
||||
if signature is None:
|
||||
return None
|
||||
names = [part.split("=")[0].split()[-1] for part in _split_top(signature.group(2), ",")]
|
||||
if parameter not in names:
|
||||
return None
|
||||
code = _code(src)
|
||||
calls = [
|
||||
call
|
||||
for call in re.finditer(rf"(?<![\w.]){signature.group(1)}\(", code)
|
||||
if not _statement_start(src, method[0]) <= call.start() < method[1]
|
||||
]
|
||||
if len(calls) != 1:
|
||||
return None
|
||||
arguments = _split_top(_call_args(src, calls[0].end() - 1), ",")
|
||||
caller = _method_of(src, calls[0].start())
|
||||
return render(src, arguments[names.index(parameter)], caller[0], calls[0].start())
|
||||
|
||||
|
||||
def config_label(src: Source, offset: int, writer: str) -> str:
|
||||
"""The file the writer variable opens, as a path under the emulator folder."""
|
||||
method = _method_of(src, offset)
|
||||
code = _code(src)
|
||||
for scope in (method, (0, len(code))):
|
||||
for opened in re.finditer(
|
||||
rf"\b{writer}\s*=\s*(?:\w+\.FromFile|\w+\.Load|new \w+)\(", code[scope[0] : scope[1]]
|
||||
):
|
||||
paren = scope[0] + opened.end() - 1
|
||||
target = _split_top(_call_args(src, paren), ",")[0]
|
||||
rendered = render(src, target, _method_of(src, paren)[0], paren)
|
||||
if rendered is None:
|
||||
rendered = _argument_of(src, _method_of(src, paren), target)
|
||||
if rendered is not None:
|
||||
return rendered[0].replace("<emulator>/", "")
|
||||
raise LauncherPatternMissing(src.path, f"configuration file opened as {writer}")
|
||||
|
||||
|
||||
def _bios_lines(src: Source) -> list[int]:
|
||||
code = _code(src)
|
||||
return sorted(
|
||||
{
|
||||
src.line(m.start())
|
||||
for m in re.finditer(r'AppConfig\.GetFullPath\("bios"\)|AppConfig\["bios"\]', code)
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def covered_records(src: Source, records: list[Record], skip: tuple[str, ...] = ()) -> list[Record]:
|
||||
"""records, once every line of src that names the bios folder is in one.
|
||||
|
||||
A line no record cites and no skip pattern describes is a construct the
|
||||
extractors do not read, and stops the scrape.
|
||||
"""
|
||||
covered: set[int] = set()
|
||||
for record in records:
|
||||
for part in str(record["source_ref"]).split(", "):
|
||||
path, _, span = part.rpartition(":") if ":" in part else (src.path, "", part)
|
||||
if path and path != src.path:
|
||||
continue
|
||||
first, _, last = span.partition("-")
|
||||
covered.update(range(int(first), int(last or first) + 1))
|
||||
lines = src.text.split("\n")
|
||||
for line in _bios_lines(src):
|
||||
if line in covered or any(re.search(p, lines[line - 1]) for p in skip):
|
||||
continue
|
||||
raise LauncherPatternMissing(src.path, f"reader for the bios reference at line {line}")
|
||||
return records
|
||||
|
||||
|
||||
def path_parts(src: Source, *spans: tuple[int, int]) -> str:
|
||||
return source_ref((src.path, list(spans)))
|
||||
|
||||
|
||||
def _option_path_in(src: Source, features: Source, emulator: str) -> list[Record]:
|
||||
"""A default name under bios that an option replaces before it is written."""
|
||||
code = _code(src)
|
||||
override = src.find(
|
||||
rf"(?:string )?(\w+) = Path\.Combine\({BIOS_ROOT}, SystemConfig\[\"(\w+)\"\]\);",
|
||||
"path taken from an option",
|
||||
)
|
||||
var, option = override.groups()
|
||||
method = _method_of(src, override.start())
|
||||
gate = src.find(
|
||||
rf'if \(SystemConfig\.isOptSet\("{option}"\)', f"{option} gate", method[0], override.start()
|
||||
)
|
||||
gate_block = _gate_span(src, gate, override)
|
||||
write = re.compile(
|
||||
rf'(\w+)\.WriteValue\("([^"]*)", "([^"]+)", ([^;\n]*\b{var}\b[^;\n]*)\);'
|
||||
).search(code, override.end(), method[1])
|
||||
if write is None:
|
||||
raise LauncherPatternMissing(src.path, f"write of {var}")
|
||||
writer, section, key = write.group(1), _unescape(write.group(2)), _unescape(write.group(3))
|
||||
guarded = re.compile(rf"if \(File\.Exists\({var}\)[^\n]*\)\s*$").search(
|
||||
code, method[0], write.start()
|
||||
)
|
||||
flag = None if guarded else _flag_guard(code, var, method[0], write.start())
|
||||
guarded = guarded or flag
|
||||
skipped = re.findall(
|
||||
rf'SystemConfig\["{option}"\] != "(\w+)"', code[gate.start() : write.end()]
|
||||
)
|
||||
config = config_label(src, write.start(), writer)
|
||||
target = f"{config} [{section}] {key}" if section else f"{config} {key}"
|
||||
suffix = ", only if the file exists" if guarded else ", written without an existence check"
|
||||
fails = f"{key} not written" if guarded else "path written without an existence check"
|
||||
write_span = src.lines(
|
||||
flag.start() if flag else _statement_start(src, write.start()), write.end()
|
||||
)
|
||||
choices, choice_lines = feature_choices(features, emulator, option)
|
||||
fallback = _fallback_names(src, var, gate_block[1], write.start())
|
||||
if fallback is not None:
|
||||
fails = f"{', then '.join(fallback[0])}, instead, else {fails}"
|
||||
records = []
|
||||
default = list(
|
||||
re.compile(rf'string {var} = Path\.Combine\({BIOS_ROOT}, "([^"]+)"\);').finditer(
|
||||
code, method[0], gate.start()
|
||||
)
|
||||
)
|
||||
if default:
|
||||
records.append(
|
||||
launcher_record(
|
||||
emulator,
|
||||
"standalone",
|
||||
"fixed_name",
|
||||
[default[-1].group(1)],
|
||||
path_parts(src, src.lines(default[-1].start(), default[-1].end()), write_span),
|
||||
case_insensitive=True,
|
||||
search_dir="bios",
|
||||
passes_to=target + suffix,
|
||||
fails_when_missing=fails,
|
||||
depends_on_option=f"{option} unset",
|
||||
)
|
||||
)
|
||||
records.append(
|
||||
launcher_record(
|
||||
emulator,
|
||||
"standalone",
|
||||
"core_option",
|
||||
[c for c in choices if c not in skipped],
|
||||
source_ref(
|
||||
(src.path, [src.lines(gate.start(), gate_block[1]), write_span]),
|
||||
(features.path, [choice_lines]),
|
||||
),
|
||||
case_insensitive=True,
|
||||
search_dir="bios",
|
||||
passes_to=f"{target} = <bios>/<value>{suffix}",
|
||||
fails_when_missing=fails,
|
||||
depends_on_option=option,
|
||||
)
|
||||
)
|
||||
if fallback is not None:
|
||||
names, span = fallback
|
||||
unset = f"{default[-1].group(1)} absent with {option} unset" if default else None
|
||||
chosen = f"the {option} file absent" + (
|
||||
f", {option} not {' or '.join(skipped)}" if skipped else ""
|
||||
)
|
||||
records.append(
|
||||
launcher_record(
|
||||
emulator,
|
||||
"standalone",
|
||||
"names_searched",
|
||||
names,
|
||||
path_parts(src, span, write_span),
|
||||
case_insensitive=True,
|
||||
search_dir="bios",
|
||||
passes_to=f"{target} = <first found>{suffix}",
|
||||
fails_when_missing=f"{key} not written" if guarded else fails,
|
||||
depends_on_option=" or ".join(c for c in (unset, chosen) if c),
|
||||
)
|
||||
)
|
||||
return records + root_writes(src, emulator)
|
||||
|
||||
|
||||
def _gate_span(src: Source, gate: re.Match[str], override: re.Match[str]) -> tuple[int, int]:
|
||||
"""The span an option gate governs: its block, or the one statement a
|
||||
braceless if runs, which must be the override."""
|
||||
paren = gate.start() + len("if ")
|
||||
after = paren + len(_call_args(src, paren)) + 2
|
||||
if re.match(r"\s*\{", src.text[after:]):
|
||||
block = src.block_at(after)
|
||||
else:
|
||||
block = (after, _statement_end(src, after))
|
||||
if not block[0] < override.start() < block[1]:
|
||||
raise LauncherPatternMissing(
|
||||
src.path, f"option block around line {src.line(override.start())}"
|
||||
)
|
||||
return block
|
||||
|
||||
|
||||
def _flag_guard(code: str, var: str, start: int, end: int) -> re.Match[str] | None:
|
||||
"""A write under `if (flag)` where flag holds File.Exists of the path."""
|
||||
flag = re.compile(rf"bool (\w+) = [^;\n]*\bFile\.Exists\({var}\)[^;\n]*;").search(
|
||||
code, start, end
|
||||
)
|
||||
if flag is None or not re.compile(rf"if \({flag.group(1)}\)\s*$", re.M).search(
|
||||
code, flag.end(), end
|
||||
):
|
||||
return None
|
||||
return flag
|
||||
|
||||
|
||||
def _fallback_names(
|
||||
src: Source, var: str, start: int, end: int
|
||||
) -> tuple[list[str], tuple[int, int]] | None:
|
||||
"""Names tried in bios, first existing one kept, when the chosen file is absent."""
|
||||
found = re.compile(
|
||||
rf"if \(([^\n]*!File\.Exists\({var}\)[^\n]*)\)\s*"
|
||||
rf"{var} = new\[\] \{{ (?P<names>(?:{STRING}(?:, )?)+) \}}\.Select\((?P<arg>\w+) => "
|
||||
rf"Path\.Combine\({BIOS_ROOT}, (?P=arg)\)\)\.FirstOrDefault\(File\.Exists\) \?\? {var};"
|
||||
).search(_code(src), start, end)
|
||||
if found is None:
|
||||
return None
|
||||
return _strings(found.group("names")), src.lines(found.start(), found.end())
|
||||
|
||||
|
||||
OPTION_PATHS = {
|
||||
f"{GENERATORS}/Kronos.Generator.cs": "kronos",
|
||||
f"{GENERATORS}/SSF.Generator.cs": "ssf",
|
||||
f"{GENERATORS}/Yabasanshiro.Generator.cs": "yabasanshiro",
|
||||
f"{GENERATORS}/Ymir.Generator.cs": "ymir",
|
||||
}
|
||||
|
||||
|
||||
def option_paths(sources: dict[str, Source]) -> list[Record]:
|
||||
"""Saturn emulators: a default BIOS name an option replaces before the write."""
|
||||
return [
|
||||
record
|
||||
for path, emulator in OPTION_PATHS.items()
|
||||
for record in covered_records(
|
||||
sources[path], _option_path_in(sources[path], sources[FEATURES], emulator)
|
||||
)
|
||||
]
|
||||
@@ -0,0 +1,445 @@
|
||||
"""RetroBat launcher records of the Xbox emulators: xemu and Cxbx-Reloaded."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
from .csharp_source import Record, Source, _array_at, _strings, _unique, source_ref
|
||||
from .retrobat_generators import (
|
||||
BIOS,
|
||||
FEATURES,
|
||||
GENERATORS,
|
||||
joined,
|
||||
launcher_record,
|
||||
feature_choices,
|
||||
)
|
||||
from model.launcherrecords import join_emulators
|
||||
|
||||
|
||||
def xemu(sources: dict[str, Source]) -> list[Record]:
|
||||
src = sources[f"{GENERATORS}/Xemu.Generator.cs"]
|
||||
features = sources[FEATURES]
|
||||
records = []
|
||||
|
||||
mcpx = src.find(
|
||||
rf'if \(File\.Exists\(Path\.Combine\({BIOS}, "([^"]+)"\)\)\)\s*(\w+) = Path\.Combine',
|
||||
"MCPX boot ROM",
|
||||
)
|
||||
bootrom = src.find(
|
||||
rf'ini\.WriteValue\("([\w.]+)", "(bootrom_path)", "\'" \+ {mcpx.group(2)}',
|
||||
"bootrom_path write",
|
||||
)
|
||||
records.append(
|
||||
launcher_record(
|
||||
"xemu",
|
||||
"standalone",
|
||||
"fixed_name",
|
||||
[mcpx.group(1)],
|
||||
source_ref(
|
||||
(
|
||||
src.path,
|
||||
[
|
||||
src.lines(mcpx.start(), mcpx.end()),
|
||||
src.lines(bootrom.start(), bootrom.end()),
|
||||
],
|
||||
)
|
||||
),
|
||||
case_insensitive=True,
|
||||
search_dir="bios",
|
||||
passes_to=f"xemu.toml [{bootrom.group(1)}] {bootrom.group(2)}, only if the file exists",
|
||||
fails_when_missing=f"{bootrom.group(2)} not written",
|
||||
)
|
||||
)
|
||||
|
||||
flash = src.find(r'isOptSet\("(xemu_flashrom)"\)', "xemu_flashrom")
|
||||
# The flashrom is written outside a Chihiro launch only.
|
||||
chihiro_set = src.find(r"(_chihiro) = \(([^;]+)\);", "Chihiro test")
|
||||
chihiro_guard = src.find_all(
|
||||
rf"if \(!{chihiro_set.group(1)}\)", "flashrom guard", end=flash.start()
|
||||
)[-1]
|
||||
flash_default = src.find(
|
||||
r'ini\.WriteValue\("([\w.]+)", "(flashrom_path)", "\'" \+ Path\.Combine\(flashromPath, "([^"]+)"\)',
|
||||
"flashrom default",
|
||||
flash.end(),
|
||||
)
|
||||
choices, choice_lines = feature_choices(features, "xemu", flash.group(1))
|
||||
records.append(
|
||||
launcher_record(
|
||||
"xemu",
|
||||
"standalone",
|
||||
"core_option",
|
||||
_unique([flash_default.group(3), *choices]),
|
||||
source_ref(
|
||||
(src.path, [
|
||||
src.lines(chihiro_set.start(), chihiro_set.end()),
|
||||
src.lines(chihiro_guard.start(), flash_default.end()),
|
||||
]),
|
||||
(features.path, [choice_lines]),
|
||||
),
|
||||
case_insensitive=True,
|
||||
search_dir="bios",
|
||||
passes_to=(
|
||||
f"xemu.toml [{flash_default.group(1)}] {flash_default.group(2)}=<bios>/<value>,"
|
||||
f" default {flash_default.group(3)}"
|
||||
),
|
||||
fails_when_missing="path written without an existence check",
|
||||
depends_on_option=f"{flash.group(1)}, not ({chihiro_set.group(2)})",
|
||||
)
|
||||
)
|
||||
|
||||
setup = src.find(r"private void SetupChihiroConfiguration\(", "SetupChihiroConfiguration")
|
||||
body = src.block_at(setup.end())
|
||||
chain = src.find(
|
||||
r'string (\w+) = Path\.Combine\(biosPath, ((?:"[^"]+", )*)"([^"]+)"\);\s*'
|
||||
r'if \(!File\.Exists\(\1\)\)\s*\1 = Path\.Combine\(biosPath, ((?:"[^"]+", )*)"([^"]+)"\);',
|
||||
"Chihiro BIOS chain",
|
||||
body[0],
|
||||
body[1],
|
||||
)
|
||||
dirs = [
|
||||
"/".join(["bios", *_strings(chain.group(2))]),
|
||||
"/".join(["bios", *_strings(chain.group(4))]),
|
||||
]
|
||||
bios_write = src.find(
|
||||
r'ini\.WriteValue\("([\w.]+)", "(bios_path)"', "Chihiro bios_path", chain.end(), body[1]
|
||||
)
|
||||
warning = src.find(
|
||||
r'else\s*SimpleLogger\.Instance\.Warning\("([^"]+)"\);',
|
||||
"Chihiro missing warning",
|
||||
bios_write.end(),
|
||||
body[1],
|
||||
)
|
||||
records.append(
|
||||
launcher_record(
|
||||
"xemu",
|
||||
"standalone",
|
||||
"names_searched",
|
||||
_unique([chain.group(3), chain.group(5)]),
|
||||
source_ref((src.path, [src.lines(chain.start(), warning.end())])),
|
||||
case_insensitive=True,
|
||||
search_dir=", then ".join(dirs),
|
||||
passes_to=f"xemu.toml [{bios_write.group(1)}] {bios_write.group(2)}",
|
||||
fails_when_missing=f"warning '{warning.group(1)}', {bios_write.group(2)} not written",
|
||||
)
|
||||
)
|
||||
|
||||
companions = src.find(
|
||||
r"foreach \(var f in new\[\] \{", "Chihiro companion files", chain.end(), body[1]
|
||||
)
|
||||
names, _ = _array_at(src, companions.end() - 1)
|
||||
loop = src.block_at(src.block_at(companions.end() - 1)[1])
|
||||
records.append(
|
||||
launcher_record(
|
||||
"xemu",
|
||||
"standalone",
|
||||
"fixed_name",
|
||||
names,
|
||||
source_ref((src.path, [(src.line(companions.start()), src.lines(*loop)[1])])),
|
||||
case_insensitive=True,
|
||||
search_dir="directory of the Chihiro BIOS found",
|
||||
passes_to="nothing passed: existence checked only",
|
||||
fails_when_missing="warning per missing file",
|
||||
)
|
||||
)
|
||||
|
||||
board = src.find(
|
||||
r'if \((!File\.Exists\(Path\.Combine\(biosDir, "[^"]+"\)\)(?:\s*&&\s*)?)+\)\s*'
|
||||
r'SimpleLogger\.Instance\.Warning\("([^"]+)"\);',
|
||||
"media board flash names",
|
||||
companions.end(),
|
||||
body[1],
|
||||
)
|
||||
records.append(
|
||||
launcher_record(
|
||||
"xemu",
|
||||
"standalone",
|
||||
"names_searched",
|
||||
re.findall(r'Path\.Combine\(biosDir, "([^"]+)"\)', board.group(0)),
|
||||
source_ref((src.path, [src.lines(board.start(), board.end())])),
|
||||
case_insensitive=True,
|
||||
search_dir="directory of the Chihiro BIOS found",
|
||||
passes_to="nothing passed: warning if none exists",
|
||||
fails_when_missing=f"warning '{board.group(2)}'",
|
||||
)
|
||||
)
|
||||
return records
|
||||
|
||||
|
||||
def xemu_saves(sources: dict[str, Source]) -> list[Record]:
|
||||
"""The files the xemu generator keeps below the saves folder.
|
||||
|
||||
An Xbox gets eeprom.bin and xbox_hdd.qcow2 in saves/<system>, written
|
||||
from the launcher's own resources when absent, and their paths in
|
||||
xemu.toml. A Chihiro keeps chihiro_eeprom.bin there, copied into the
|
||||
emulator folder before the run and back after it, and its snapshot
|
||||
store.
|
||||
"""
|
||||
src = sources[f"{GENERATORS}/Xemu.Generator.cs"]
|
||||
chihiro = src.find(r'(_chihiro) = \(emulator == "([\w-]+)" \|\| system == "(\w+)"\);', "Chihiro switch")
|
||||
chihiro_when = f'emulator == "{chihiro.group(2)}" or system == "{chihiro.group(3)}"'
|
||||
saves = src.find(
|
||||
r'if \(!string\.IsNullOrEmpty\(AppConfig\["saves"\]\) && Directory\.Exists\(AppConfig\.GetFullPath\("saves"\)\)\)'
|
||||
r'\s*\{\s*string savePath = Path\.Combine\(AppConfig\.GetFullPath\("saves"\), system\);',
|
||||
"Xbox save folder",
|
||||
)
|
||||
eeprom = src.find(
|
||||
r'if \(!File\.Exists\(Path\.Combine\(savePath, "([^"]+)"\)\)\)\s*\{[^{}]*?'
|
||||
r'File\.WriteAllBytes\(Path\.Combine\(savePath, "\1"\), Properties\.Resources\.(\w+)\);\s*\}',
|
||||
"EEPROM written from resources",
|
||||
saves.end(),
|
||||
)
|
||||
hdd = src.find(
|
||||
r'if \(!File\.Exists\(Path\.Combine\(savePath, "([^"]+)"\)\)\)\s*\{[^{}]*?'
|
||||
r'File\.WriteAllBytes\(zipFile, Properties\.Resources\.(\w+)\);[^{}]*?Zip\.Extract\(zipFile, savePath\);[^{}]*?\}',
|
||||
"hard disk image written from resources",
|
||||
eeprom.end(),
|
||||
)
|
||||
eeprom_key = src.find(
|
||||
r'ini\.WriteValue\("([\w.]+)", "(eeprom_path)", "\'" \+ eepromPath', "eeprom_path write"
|
||||
)
|
||||
hdd_key = src.find(r'ini\.WriteValue\("([\w.]+)", "(hdd_path)", "\'" \+ hddPath', "hdd_path write")
|
||||
records = [
|
||||
launcher_record(
|
||||
"xemu",
|
||||
"standalone",
|
||||
"fixed_name",
|
||||
[eeprom.group(1), hdd.group(1)],
|
||||
source_ref(
|
||||
(
|
||||
src.path,
|
||||
[
|
||||
src.lines(chihiro.start(), chihiro.end()),
|
||||
src.lines(saves.start(), hdd.end()),
|
||||
src.lines(eeprom_key.start(), eeprom_key.end()),
|
||||
src.lines(hdd_key.start(), hdd_key.end()),
|
||||
],
|
||||
)
|
||||
),
|
||||
case_insensitive=True,
|
||||
search_dir="saves/<system>",
|
||||
passes_to=(
|
||||
f"xemu.toml [{eeprom_key.group(1)}] {eeprom_key.group(2)}, {hdd_key.group(2)};"
|
||||
f" written from the launcher's {eeprom.group(2)} and {hdd.group(2)} resources"
|
||||
" when absent, the disk image unzipped"
|
||||
),
|
||||
fails_when_missing="never missing: the launcher writes both",
|
||||
depends_on_option=joined("the saves folder is set and exists", f"not ({chihiro_when})"),
|
||||
)
|
||||
]
|
||||
|
||||
setup = src.find(r"private void SetupChihiroEeprom\(string path\)", "SetupChihiroEeprom")
|
||||
body = src.block_at(setup.end())
|
||||
folder = src.find(
|
||||
r'string savePath = Path\.Combine\(AppConfig\.GetFullPath\("saves"\), "(\w+)"\);',
|
||||
"Chihiro save folder",
|
||||
body[0],
|
||||
body[1],
|
||||
)
|
||||
pair = src.find(
|
||||
r'_chihiroEeprom = Path\.Combine\(path, "([^"]+)"\);\s*'
|
||||
r'_chihiroEepromSave = Path\.Combine\(savePath, "\1"\);',
|
||||
"Chihiro EEPROM pair",
|
||||
folder.end(),
|
||||
body[1],
|
||||
)
|
||||
save = src.find(r"private void SaveChihiroEeprom\(\)", "SaveChihiroEeprom")
|
||||
save_body = src.block_at(save.end())
|
||||
records.append(
|
||||
launcher_record(
|
||||
"xemu, xemu-chihiro",
|
||||
"standalone",
|
||||
"copies",
|
||||
[pair.group(1)],
|
||||
source_ref(
|
||||
(
|
||||
src.path,
|
||||
[
|
||||
src.lines(chihiro.start(), chihiro.end()),
|
||||
src.statement_span(body),
|
||||
src.statement_span(save_body),
|
||||
],
|
||||
)
|
||||
),
|
||||
case_insensitive=True,
|
||||
search_dir=f"saves/{folder.group(1)}",
|
||||
passes_to=(
|
||||
f"<emulator>/{pair.group(1)}, restored when the saved copy is newer or the"
|
||||
" emulator folder holds none, copied back after the run"
|
||||
),
|
||||
fails_when_missing=False,
|
||||
depends_on_option=chihiro_when,
|
||||
)
|
||||
)
|
||||
|
||||
store = src.find(
|
||||
r'string savePath = Path\.Combine\(AppConfig\.GetFullPath\("saves"\), "(\w+)"\);\s*'
|
||||
r'if \(!Directory\.Exists\(savePath\)\) try \{ Directory\.CreateDirectory\(savePath\); \} catch \{ \}\s*'
|
||||
r'if \(Directory\.Exists\(savePath\)\)\s*'
|
||||
r'ini\.WriteValue\("([\w.]+)", "(\w+)", "\'" \+ Path\.Combine\(savePath, "([^"]+)"\)',
|
||||
"Chihiro snapshot store",
|
||||
)
|
||||
records.append(
|
||||
launcher_record(
|
||||
"xemu, xemu-chihiro",
|
||||
"standalone",
|
||||
"fixed_name",
|
||||
[store.group(4)],
|
||||
source_ref((src.path, [src.lines(chihiro.start(), chihiro.end()),
|
||||
src.lines(store.start(), store.end())])),
|
||||
case_insensitive=True,
|
||||
search_dir=f"saves/{store.group(1)}",
|
||||
passes_to=f"xemu.toml [{store.group(2)}] {store.group(3)}, created by the emulator",
|
||||
fails_when_missing=False,
|
||||
depends_on_option=chihiro_when,
|
||||
)
|
||||
)
|
||||
return records
|
||||
|
||||
|
||||
# What the Cxbx generator hands each build: the data folder is the one its
|
||||
# settings.ini sits in (Cxbx-Reloaded Settings::FindSettingsLocation), which
|
||||
# the launcher writes beside the binary.
|
||||
CXBX_DATA_FOLDER = "Settings::GetDataLocation"
|
||||
|
||||
|
||||
def cxbx(sources: dict[str, Source]) -> list[Record]:
|
||||
"""The folder each Cxbx build runs from, and the EEPROM written there.
|
||||
|
||||
The generator picks the emulator folder by core or emulator name, opens
|
||||
settings.ini in it, and for an Xbox writes EEPROM.bin into the
|
||||
cxbx-reloaded folder from its own resource when absent.
|
||||
"""
|
||||
src = sources[f"{GENERATORS}/Cxbx.Generator.cs"]
|
||||
named = src.find_all(
|
||||
r'(?:else )?if \(\(core != null && core == "([\w-]+)"\) \|\| '
|
||||
r'\(emulator != null && emulator == "\1"\)\)\s*\{\s*path = AppConfig\.GetFullPath\("([\w-]+)"\);',
|
||||
"emulator folder by name",
|
||||
)
|
||||
fallbacks = src.find_all(
|
||||
r'if \(string\.IsNullOrEmpty\(path\)\)\s*path = AppConfig\.GetFullPath\("([\w-]+)"\);',
|
||||
"default emulator folder",
|
||||
)
|
||||
settings = src.find(
|
||||
r'IniFile\.FromFile\(Path\.Combine\(path, "(settings\.ini)"\)', "settings.ini beside the binary"
|
||||
)
|
||||
settings_span = src.lines(settings.start(), settings.end())
|
||||
passes_to = (
|
||||
f"{CXBX_DATA_FOLDER}, the folder holding {settings.group(1)},"
|
||||
" which the launcher writes beside the binary"
|
||||
)
|
||||
records = [
|
||||
launcher_record(
|
||||
match.group(1),
|
||||
"standalone",
|
||||
"passes_path",
|
||||
[],
|
||||
source_ref((src.path, [src.lines(match.start(), match.end()), settings_span])),
|
||||
search_dir=f'<AppConfig.GetFullPath("{match.group(2)}")>',
|
||||
passes_to=passes_to,
|
||||
fails_when_missing=False,
|
||||
)
|
||||
for match in named
|
||||
]
|
||||
first, *rest = fallbacks
|
||||
others = "neither core nor emulator is " + " or ".join(f'"{m.group(1)}"' for m in named)
|
||||
records.append(
|
||||
launcher_record(
|
||||
first.group(1),
|
||||
"standalone",
|
||||
"passes_path",
|
||||
[],
|
||||
source_ref(
|
||||
(
|
||||
src.path,
|
||||
[src.lines(first.start(), first.end()),
|
||||
*(src.lines(m.start(), m.end()) for m in rest), settings_span],
|
||||
)
|
||||
),
|
||||
search_dir=f'<AppConfig.GetFullPath("{first.group(1)}")>',
|
||||
passes_to=passes_to,
|
||||
fails_when_missing=False,
|
||||
depends_on_option=joined(
|
||||
others,
|
||||
*(f'<AppConfig.GetFullPath("{m.group(1)}")> when "{first.group(1)}" is not set'
|
||||
for m in rest),
|
||||
),
|
||||
)
|
||||
)
|
||||
records.extend(_cxbx_mount(src, [*(m.group(1) for m in named), first.group(1)]))
|
||||
eeprom = src.find(
|
||||
r'if \(system == "(\w+)"\)\s*\{\s*string (\w+) = Path\.Combine\(AppConfig\.GetFullPath\("([\w-]+)"\), "([^"]+)"\);'
|
||||
r'\s*if \(!File\.Exists\(\2\)\)\s*File\.WriteAllBytes\(\2, Properties\.Resources\.(\w+)\);'
|
||||
r'\s*WriteXboxEEPROM\(\2\);\s*\}',
|
||||
"EEPROM written from resources",
|
||||
)
|
||||
records.append(
|
||||
launcher_record(
|
||||
eeprom.group(3),
|
||||
"standalone",
|
||||
"fixed_name",
|
||||
[eeprom.group(4)],
|
||||
source_ref((src.path, [src.lines(eeprom.start(), eeprom.end())])),
|
||||
case_insensitive=True,
|
||||
search_dir=f'<AppConfig.GetFullPath("{eeprom.group(3)}")>',
|
||||
passes_to=(
|
||||
f"written from the launcher's {eeprom.group(5)} resource when absent,"
|
||||
" then its language set: the emulator reads it from its data folder"
|
||||
),
|
||||
fails_when_missing="never missing: the launcher writes it",
|
||||
depends_on_option=f'system == "{eeprom.group(1)}"',
|
||||
)
|
||||
)
|
||||
return records
|
||||
|
||||
|
||||
def _cxbx_mount(src: Source, emulators: list[str]) -> list[Record]:
|
||||
"""What the generator needs to mount an .iso before Cxbx opens it: its
|
||||
own xbox-iso-vfs.exe, run from the launcher's folder, and the Dokan 2
|
||||
runtime installed on the system."""
|
||||
iso = src.find(
|
||||
r'if \(Path\.GetExtension\(rom\)\.ToLowerInvariant\(\) != "(\.\w+)"\)\s*return rom;',
|
||||
"mount for disc images only",
|
||||
)
|
||||
vfs = src.find(
|
||||
r'string (\w+) = Path\.Combine\(Path\.GetDirectoryName\(typeof\(\w+\)\.Assembly\.Location\), "([^"]+)"\);'
|
||||
r'\s*if \(!File\.Exists\(\1\)\)\s*throw new ApplicationException\("([^"]+)"\);',
|
||||
"mount tool beside the launcher",
|
||||
iso.end(),
|
||||
)
|
||||
dokan = src.find(
|
||||
r'string (\w+) = Environment\.GetEnvironmentVariable\("(\w+)"\);.*?'
|
||||
r'\1 = Path\.Combine\(\1, "([^"]+)"\);\s*if \(!File\.Exists\(\1\)\)\s*\{[^{}]*?'
|
||||
r'throw new ApplicationException\("([^"]+)"\);\s*\}',
|
||||
"Dokan runtime check",
|
||||
vfs.end(),
|
||||
flags=re.S,
|
||||
)
|
||||
iso_span = src.lines(iso.start(), iso.end())
|
||||
when = f'rom extension "{iso.group(1)}"'
|
||||
emulator = join_emulators(emulators)
|
||||
return [
|
||||
launcher_record(
|
||||
emulator,
|
||||
"standalone",
|
||||
"fixed_name",
|
||||
[vfs.group(2)],
|
||||
source_ref((src.path, [iso_span, src.lines(vfs.start(), vfs.end())])),
|
||||
case_insensitive=True,
|
||||
search_dir="<emulatorLauncher folder>",
|
||||
passes_to="exec",
|
||||
fails_when_missing=vfs.group(3),
|
||||
depends_on_option=when,
|
||||
),
|
||||
launcher_record(
|
||||
emulator,
|
||||
"standalone",
|
||||
"fixed_name",
|
||||
[dokan.group(3)],
|
||||
source_ref((src.path, [iso_span, src.lines(dokan.start(), dokan.end())])),
|
||||
case_insensitive=True,
|
||||
search_dir=f"%{dokan.group(2)}%",
|
||||
passes_to=f"nothing passed: checked before {vfs.group(2)} mounts the image",
|
||||
fails_when_missing=dokan.group(4),
|
||||
depends_on_option=when,
|
||||
),
|
||||
]
|
||||
@@ -0,0 +1,550 @@
|
||||
"""RetroDECK's launcher layer, read from each component's scripts.
|
||||
|
||||
A component's `component_prepare.sh` writes the emulator's config on reset:
|
||||
melonDS gets seven fixed paths under $bios_path, xemu three, DuckStation and
|
||||
PCSX2 a directory to search. It links folders the emulator reads into or out
|
||||
of bios/ (LRPS2's pcsx2/bios points back at bios/, Dolphin's GC/<region>
|
||||
folders live under saves/), and copies package-provided trees into bios/.
|
||||
The presets it copies carry the rest: RetroArch core options that name a
|
||||
BIOS file, XRoar's ROM search lists. RPCS3's firmware is downloaded by
|
||||
RetroDECK itself and PICO-8 is started from a binary the user drops in bios/.
|
||||
|
||||
The shell is read as text, never run. Every line of a prepare or launcher
|
||||
script that names $bios_path must match a known construct, else the scrape
|
||||
stops with LauncherPatternMissing: an unclassified use would vanish from the
|
||||
platform file without a word.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from collections.abc import Callable
|
||||
from pathlib import PurePosixPath
|
||||
from typing import Any
|
||||
|
||||
from .retropie_scripts import Launcher, LauncherPatternMissing, split, merge_records, source_ref
|
||||
from .retropie_reader import split_path
|
||||
|
||||
BIOS = "$bios_path"
|
||||
PLACEHOLDER = "RETRODECKBIOSDIR"
|
||||
# The roms folder in the same presets: GZDoom's IWADSearch.Directories holds
|
||||
# RETRODECKROMSDIR/doom (gzdoom/rd_assets/rd_config/gzdoom.ini:9), which
|
||||
# gzdoom/component_prepare.sh:27 rewrites to $roms_path.
|
||||
ROMS_PLACEHOLDER = "RETRODECKROMSDIR"
|
||||
CORE_OPTIONS = "retroarch/rd_assets/rd_config/retroarch-core-options.cfg"
|
||||
# XRoar ROM lists RetroDECK's xroar.conf defines that no machine looks up.
|
||||
UNREAD_ROMLISTS = frozenset({"coco1", "coco1e", "coco1e_ext", "coco2", "coco2_ext", "coco2b"})
|
||||
# The component that runs libretro cores.
|
||||
LIBRETRO_COMPONENT = "retroarch"
|
||||
# Values of a core option that name a file rather than a setting.
|
||||
_FILE_VALUE = re.compile(r"\.(bin|rom|img|zip|bios)$", re.IGNORECASE)
|
||||
_EXTENSION = re.compile(r"\.[A-Za-z0-9]{1,6}$")
|
||||
_ASSIGN = re.compile(r'^([A-Za-z_]\w*)="([^"]*)"$')
|
||||
_GC_REGION = re.compile(r"/GC/(EUR|USA|JAP)$")
|
||||
|
||||
# Commands whose $bios_path argument creates or backs up a folder, logs, or
|
||||
# only tests a path.
|
||||
HOUSEKEEPING = frozenset({"create_dir", "log", "mkdir", "chmod", "rm", "unlink"})
|
||||
|
||||
Read = Callable[[str], "str | None"]
|
||||
|
||||
|
||||
def _unquote(value: str) -> str:
|
||||
return value.strip().strip("'\"")
|
||||
|
||||
|
||||
def _is_file(path: str) -> bool:
|
||||
return bool(_EXTENSION.search(PurePosixPath(path).name))
|
||||
|
||||
|
||||
def _mentions_bios(text: str) -> bool:
|
||||
return BIOS in text or "${bios_path}" in text
|
||||
|
||||
|
||||
class Script:
|
||||
"""One component shell script, line by line, with its enclosing tests."""
|
||||
|
||||
def __init__(self, path: str, text: str) -> None:
|
||||
self.path = path
|
||||
self.lines = text.splitlines()
|
||||
|
||||
def statements(self) -> list[tuple[int, list[str], str, list[str]]]:
|
||||
"""(line, words, raw, enclosing conditions) for each command, `&&` chains split."""
|
||||
found = []
|
||||
branches: list[str] = []
|
||||
for number, line in enumerate(self.lines, 1):
|
||||
stripped = line.strip()
|
||||
if not stripped or stripped.startswith("#"):
|
||||
continue
|
||||
opened = re.match(r"^(if|elif)\s+(.*?)\s*;\s*then\s*$", stripped)
|
||||
if opened is not None:
|
||||
condition = opened.group(2)
|
||||
if opened.group(1) == "if":
|
||||
branches.append(condition)
|
||||
elif branches:
|
||||
branches[-1] = condition
|
||||
continue
|
||||
if stripped == "else" and branches:
|
||||
branches[-1] = f"not ({branches[-1]})"
|
||||
continue
|
||||
if stripped == "fi":
|
||||
if branches:
|
||||
branches.pop()
|
||||
continue
|
||||
shown = [c for c in branches if "$action" not in c]
|
||||
for part in re.split(r"\s+&&\s+|\s+\|\|\s+", stripped):
|
||||
words = split(part)
|
||||
if words:
|
||||
found.append((number, words, part, shown))
|
||||
return found
|
||||
|
||||
|
||||
class Component:
|
||||
"""What one component's scripts and presets hand its emulator."""
|
||||
|
||||
def __init__(self, name: str, read: Read) -> None:
|
||||
self.name = name
|
||||
self.read = read
|
||||
self.build = "libretro" if name == LIBRETRO_COMPONENT else "standalone"
|
||||
self.records: list[Launcher] = []
|
||||
self.variables = self._variables()
|
||||
|
||||
def _variables(self) -> dict[str, str]:
|
||||
text = self.read(f"{self.name}/component_functions.sh") or ""
|
||||
return {
|
||||
m.group(1): m.group(2)
|
||||
for m in (_ASSIGN.match(line.strip()) for line in text.splitlines())
|
||||
if m is not None
|
||||
}
|
||||
|
||||
def resolve(self, word: str) -> str:
|
||||
"""A word with the component's own bios/ paths filled in (`$retroarch_config_scummvm`)."""
|
||||
def fill(found: re.Match[str]) -> str:
|
||||
value = self.variables.get(found.group(1) or found.group(2), "")
|
||||
return value if _mentions_bios(value) else found.group(0)
|
||||
|
||||
return re.sub(r"\$\{(\w+)\}|\$(\w+)", fill, word)
|
||||
|
||||
def config_name(self, value: str) -> str:
|
||||
"""`melonDS.toml` for `$melonds_config`, as component_functions.sh defines it."""
|
||||
variable = re.fullmatch(r"\$\{?(\w+)\}?", value)
|
||||
if variable is None or variable.group(1) not in self.variables:
|
||||
return value
|
||||
return PurePosixPath(self.variables[variable.group(1)]).name
|
||||
|
||||
def record(
|
||||
self, kind: str, names: list[str], lines: list[tuple[str, int]], **fields: Any
|
||||
) -> None:
|
||||
self.records.append(Launcher(
|
||||
emulator=fields.pop("emulator", self.name), build=fields.pop("build", self.build),
|
||||
kind=kind, names=names, source_ref=source_ref(lines), lines=list(lines), **fields,
|
||||
))
|
||||
|
||||
def read_prepare(self) -> None:
|
||||
path = f"{self.name}/component_prepare.sh"
|
||||
text = self.read(path)
|
||||
if text is None:
|
||||
return
|
||||
script = Script(path, text)
|
||||
settings: dict[tuple[str, ...], list[tuple[int, str, str]]] = {}
|
||||
copies: dict[tuple[str, str | None], list[tuple[int, str, str]]] = {}
|
||||
for number, words, raw, conditions in script.statements():
|
||||
depends = "; ".join(conditions) or None
|
||||
command = words[0]
|
||||
if command != "set_setting_value":
|
||||
words = [self.resolve(w) for w in words]
|
||||
raw = " ".join(words)
|
||||
if command == "set_setting_value" and len(words) >= 4:
|
||||
self._setting(number, words, depends, settings)
|
||||
continue
|
||||
if command == "dir_prep" and len(words) == 3:
|
||||
self._dir_prep(path, number, words[1], words[2], depends)
|
||||
continue
|
||||
if command == "ln" and _mentions_bios(raw):
|
||||
self._link(path, number, words, depends)
|
||||
continue
|
||||
if command == "cp" and len(words) >= 3 and _mentions_bios(words[-1]):
|
||||
source, target = words[-2], words[-1]
|
||||
folder, name = split_path(source)
|
||||
copies.setdefault((folder, depends), []).append((number, name, target))
|
||||
continue
|
||||
if command == "tar" and "-C" in words and _mentions_bios(words[words.index("-C") + 1]):
|
||||
self._tar(path, number, words, raw, depends)
|
||||
continue
|
||||
if command == "sed" and PLACEHOLDER in raw:
|
||||
self._preset(script, number, words)
|
||||
continue
|
||||
if not _mentions_bios(raw):
|
||||
continue
|
||||
if command in HOUSEKEEPING or command in ("[[", "[", "if") or command.startswith("[["):
|
||||
continue
|
||||
raise LauncherPatternMissing(
|
||||
f"{path}:{number}", f"unrecognised use of $bios_path: {raw}"
|
||||
)
|
||||
for setting, hits in settings.items():
|
||||
self._settings(path, setting, hits)
|
||||
for (folder, depends), hits in copies.items():
|
||||
names = [name for _n, name, _t in hits]
|
||||
targets = [target for _n, _name, target in hits]
|
||||
self.record(
|
||||
"copies", names, [(path, n) for n, _name, _t in hits], search_dir=folder,
|
||||
passes_to=_render_targets(names, targets), fails_when_missing=False,
|
||||
depends_on_option=depends or None,
|
||||
)
|
||||
|
||||
def _setting(
|
||||
self, number: int, words: list[str], depends: str | None,
|
||||
settings: dict[tuple[str, ...], list[tuple[int, str, str]]],
|
||||
) -> None:
|
||||
"""A set_setting_value that writes a bios/ path into a config."""
|
||||
value = _unquote(words[3])
|
||||
if not _mentions_bios(value):
|
||||
return
|
||||
section = words[5] if len(words) > 5 else None
|
||||
where = f"[{section}] {words[2]}" if section else words[2]
|
||||
target = self.config_name(words[1])
|
||||
if _is_file(value):
|
||||
settings.setdefault(("fixed_name", target, depends or ""), []).append(
|
||||
(number, value, where)
|
||||
)
|
||||
else:
|
||||
key = ("passes_path", target, where, depends or "")
|
||||
settings.setdefault(key, []).append((number, value, where))
|
||||
|
||||
def _tar(self, path: str, number: int, words: list[str], raw: str, depends: str | None) -> None:
|
||||
"""A tar that extracts an archive into bios/."""
|
||||
if "-czf" in words:
|
||||
return
|
||||
archive = next((w for w in words if w.endswith((".tar.gz", ".tgz", ".tar"))), None)
|
||||
if archive is None:
|
||||
raise LauncherPatternMissing(
|
||||
f"{path}:{number}", f"tar into bios/ of no archive: {raw}"
|
||||
)
|
||||
self.record(
|
||||
"copies", [], [(path, number)], search_dir=archive,
|
||||
passes_to=words[words.index("-C") + 1], fails_when_missing=False,
|
||||
depends_on_option=depends,
|
||||
)
|
||||
|
||||
def _settings(self, path: str, key: tuple[str, ...], hits: list[tuple[int, str, str]]) -> None:
|
||||
kind, target = key[0], key[1]
|
||||
depends = key[-1] or None
|
||||
lines = [(path, n) for n, _v, _w in hits]
|
||||
if kind == "fixed_name":
|
||||
folders = {split_path(value)[0] for _n, value, _w in hits}
|
||||
if len(folders) != 1:
|
||||
raise LauncherPatternMissing(
|
||||
f"{path}:{hits[0][0]}", "fixed names in several folders"
|
||||
)
|
||||
names = list(dict.fromkeys(split_path(value)[1] for _n, value, _w in hits))
|
||||
wheres = list(dict.fromkeys(w for _n, _v, w in hits))
|
||||
self.record(
|
||||
"fixed_name", names, lines,
|
||||
case_insensitive=False, search_dir=folders.pop(),
|
||||
passes_to=f"{target} " + ", ".join(wheres),
|
||||
fails_when_missing=False, depends_on_option=depends,
|
||||
)
|
||||
return
|
||||
values = {v for _n, v, _w in hits}
|
||||
if len(values) != 1:
|
||||
raise LauncherPatternMissing(f"{path}:{hits[0][0]}", f"{key[2]} set to several folders")
|
||||
self.record(
|
||||
"passes_path", [], lines, search_dir=values.pop(),
|
||||
passes_to=f"{target} {key[2]}", fails_when_missing=False, depends_on_option=depends,
|
||||
)
|
||||
|
||||
def _dir_prep(self, path: str, number: int, real: str, link: str, depends: str | None) -> None:
|
||||
"""`dir_prep REAL LINK` makes LINK a symlink to REAL (functions/other_functions.sh)."""
|
||||
region = _GC_REGION.search(link)
|
||||
if region is not None:
|
||||
self.record(
|
||||
"links", [], [(path, number)], slot=region.group(1), search_dir=real,
|
||||
passes_to=f"{link} is a symlink to it", fails_when_missing=False,
|
||||
depends_on_option=depends,
|
||||
)
|
||||
return
|
||||
if real.startswith(BIOS):
|
||||
self.record(
|
||||
"links", [], [(path, number)], search_dir=real,
|
||||
passes_to=f"{link} is a symlink to it", fails_when_missing=False,
|
||||
depends_on_option=depends,
|
||||
)
|
||||
# A user folder (saves, textures, cheats) linked into bios/ hands no BIOS over.
|
||||
|
||||
def _link(self, path: str, number: int, words: list[str], depends: str | None) -> None:
|
||||
paths = [w for w in words[1:] if not w.startswith("-")]
|
||||
if len(paths) != 2 or not _mentions_bios(paths[0]):
|
||||
raise LauncherPatternMissing(
|
||||
f"{path}:{number}", f"link without a bios/ source: {words}"
|
||||
)
|
||||
folder, name = split_path(paths[0])
|
||||
self.record(
|
||||
"links", [name], [(path, number)], case_insensitive=False, search_dir=folder,
|
||||
passes_to=f"{paths[1]} is a symlink to it", fails_when_missing=False,
|
||||
depends_on_option=depends,
|
||||
)
|
||||
|
||||
def _preset(self, script: Script, number: int, words: list[str]) -> None:
|
||||
"""`sed -i "s#RETRODECKBIOSDIR#${bios_path}#g" "$cfg"` on a preset copied just above.
|
||||
|
||||
Each line naming the BIOS or the roms folder is a record: a search
|
||||
list can mix them (XRoar's rompath, GZDoom's IWAD directories).
|
||||
"""
|
||||
target = words[-1]
|
||||
substitutions = self._substitutions(script, target)
|
||||
copied = None
|
||||
for line_no, line in enumerate(script.lines[:number], 1):
|
||||
cp = split(line.strip().split("&&")[0])
|
||||
if cp and cp[0] == "cp" and cp[-1] == target and "$component_config/" in cp[-2]:
|
||||
copied = (line_no, cp[-2].split("$component_config/", 1)[1])
|
||||
if copied is None:
|
||||
raise LauncherPatternMissing(f"{script.path}:{number}", f"no preset copied to {target}")
|
||||
preset = f"{self.name}/rd_assets/rd_config/{copied[1]}"
|
||||
# The reset copies the preset over the user's file, then fills its
|
||||
# placeholders: that is the install, and nothing keeps an older file.
|
||||
evidence: dict[str, Any] = {
|
||||
"installs": {
|
||||
"path": target,
|
||||
"source_ref": source_ref(
|
||||
[(script.path, copied[0])]
|
||||
+ [(script.path, line) for _v, line in substitutions.values()]
|
||||
),
|
||||
},
|
||||
"kept_if_present": False,
|
||||
"overrides": self.launch_rewrites(target),
|
||||
}
|
||||
text = self.read(preset)
|
||||
if text is None:
|
||||
raise LauncherPatternMissing(preset, "preset is missing")
|
||||
section = None
|
||||
found = 0
|
||||
for line_no, line in enumerate(text.splitlines(), 1):
|
||||
stripped = line.strip()
|
||||
if re.fullmatch(r"\[[^\]]+\]", stripped):
|
||||
section = stripped
|
||||
if stripped.startswith("#") or not any(
|
||||
p in stripped for p in (PLACEHOLDER, ROMS_PLACEHOLDER)
|
||||
):
|
||||
continue
|
||||
setting = re.match(r"^([\w.$()-]+)\s*(?:=|\s)\s*(.+)$", stripped)
|
||||
if setting is None:
|
||||
raise LauncherPatternMissing(f"{preset}:{line_no}", f"placeholder in {stripped}")
|
||||
named = [p for p in substitutions if p in stripped]
|
||||
if PLACEHOLDER not in stripped and not named:
|
||||
# A roms placeholder the script leaves as written.
|
||||
continue
|
||||
key, value = setting.group(1), _unquote(setting.group(2))
|
||||
for placeholder, (variable, _line) in substitutions.items():
|
||||
value = value.replace(placeholder, variable)
|
||||
where = f"{section} {key}" if section else key
|
||||
found += PLACEHOLDER in stripped
|
||||
applied = [(script.path, copied[0]), (script.path, number)] + [
|
||||
(script.path, substitutions[p][1]) for p in named
|
||||
]
|
||||
self.record(
|
||||
"passes_path", [], [(preset, line_no)] + applied,
|
||||
search_dir=value, passes_to=f"{self.config_name(target)} {where}",
|
||||
fails_when_missing=False, **evidence,
|
||||
)
|
||||
if key == "rompath":
|
||||
self.romlists(preset, text, value, applied, evidence)
|
||||
if not found:
|
||||
raise LauncherPatternMissing(preset, f"no {PLACEHOLDER} line")
|
||||
|
||||
@staticmethod
|
||||
def _substitutions(script: Script, target: str) -> dict[str, tuple[str, int]]:
|
||||
"""Each placeholder sed rewrites in ``target``: (variable, line)."""
|
||||
found = {}
|
||||
for line_no, line in enumerate(script.lines, 1):
|
||||
for m in re.finditer(r"s#(RETRODECK\w+)#\$\{?(\w+)\}?#g[\"']?\s+\"([^\"]+)\"", line):
|
||||
if m.group(3) == target:
|
||||
found[m.group(1)] = (f"${m.group(2)}", line_no)
|
||||
return found
|
||||
|
||||
def launch_rewrites(self, target: str) -> list[str]:
|
||||
"""The sed lines of the component launcher rewriting ``target``."""
|
||||
path = f"{self.name}/component_launcher.sh"
|
||||
text = self.read(path)
|
||||
if text is None:
|
||||
return []
|
||||
return [
|
||||
source_ref([(path, number)])
|
||||
for number, line in enumerate(text.splitlines(), 1)
|
||||
if re.search(r"\bsed\b.*\s-i\b", line) and target in line
|
||||
]
|
||||
|
||||
def romlists(
|
||||
self, preset: str, text: str, rompath: str, applied: list[tuple[str, int]],
|
||||
evidence: dict[str, Any],
|
||||
) -> None:
|
||||
"""XRoar's `romlist NAME=a,b,@other`: the names tried for each ROM, in order.
|
||||
|
||||
A list no XRoar machine or cartridge looks up is no read: coco1,
|
||||
coco1e, coco1e_ext, coco2, coco2_ext and coco2b are defined by XRoar
|
||||
(src/xroar.c:663-670) and named by nothing else.
|
||||
"""
|
||||
lists: dict[str, tuple[int, list[str]]] = {}
|
||||
for line_no, line in enumerate(text.splitlines(), 1):
|
||||
found = re.match(r"^romlist\s+([\w-]+)=(.*)$", line.strip())
|
||||
if found is not None:
|
||||
items = [_unquote(i) for i in re.findall(r'"[^"]*"|[^,]+', found.group(2))]
|
||||
lists[found.group(1)] = (line_no, items)
|
||||
if not lists:
|
||||
raise LauncherPatternMissing(preset, "rompath with no romlist")
|
||||
|
||||
def expand(name: str, seen: tuple[str, ...]) -> list[str]:
|
||||
names = []
|
||||
for item in lists[name][1]:
|
||||
if item.startswith("@"):
|
||||
ref = item[1:]
|
||||
if ref not in lists or ref in seen:
|
||||
raise LauncherPatternMissing(preset, f"romlist {name} refers to {item}")
|
||||
names += expand(ref, seen + (ref,))
|
||||
else:
|
||||
names.append(item)
|
||||
return list(dict.fromkeys(names))
|
||||
|
||||
for name, (line_no, _items) in lists.items():
|
||||
if name in UNREAD_ROMLISTS:
|
||||
continue
|
||||
self.record(
|
||||
"names_searched", expand(name, (name,)), [(preset, line_no)] + applied,
|
||||
slot=name, search_dir=rompath, passes_to=f"romlist {name}",
|
||||
fails_when_missing=False, **evidence,
|
||||
)
|
||||
|
||||
def read_launcher(self) -> None:
|
||||
path = f"{self.name}/component_launcher.sh"
|
||||
text = self.read(path)
|
||||
if text is None:
|
||||
return
|
||||
for number, words, raw, conditions in Script(path, text).statements():
|
||||
if not _mentions_bios(raw):
|
||||
continue
|
||||
if words[0] == "exec" and len(words) > 1 and _mentions_bios(words[1]):
|
||||
folder, name = split_path(words[1])
|
||||
self.record(
|
||||
"fixed_name", [name], [(path, number)], case_insensitive=False,
|
||||
search_dir=folder, passes_to="exec", fails_when_missing=True,
|
||||
depends_on_option="; ".join(conditions) or None,
|
||||
)
|
||||
continue
|
||||
raise LauncherPatternMissing(
|
||||
f"{path}:{number}", f"unrecognised use of $bios_path: {raw}"
|
||||
)
|
||||
|
||||
def read_firmware_download(self) -> None:
|
||||
"""A firmware URL RetroDECK downloads and hands to the emulator's installer."""
|
||||
path = f"{self.name}/component_functions.sh"
|
||||
text = self.read(path)
|
||||
if text is None:
|
||||
return
|
||||
urls = {
|
||||
name: value for name, value in self.variables.items()
|
||||
if re.match(r"https?://", value)
|
||||
}
|
||||
script = Script(path, text)
|
||||
statements = script.statements()
|
||||
for number, words, _raw, _conditions in statements:
|
||||
if words[0] != "download_file" or len(words) < 3:
|
||||
continue
|
||||
source = re.fullmatch(r"\$\{?(\w+)\}?", words[1])
|
||||
if source is None or source.group(1) not in urls:
|
||||
continue
|
||||
destination = words[2]
|
||||
installs = [
|
||||
(n, w) for n, w, _r, _c in statements
|
||||
if destination in w and w[0] != "download_file"
|
||||
and any(_installs(f) for f in w)
|
||||
]
|
||||
if not installs:
|
||||
raise LauncherPatternMissing(
|
||||
f"{path}:{number}", f"{destination} is downloaded but never installed"
|
||||
)
|
||||
install_line, install = installs[0]
|
||||
flag = next(f for f in install if _installs(f))
|
||||
function = self._function_at(script, number)
|
||||
assigned = next(
|
||||
n for n, line in enumerate(script.lines, 1)
|
||||
if line.strip().startswith(f"{source.group(1)}=")
|
||||
)
|
||||
folder, name = split_path(destination)
|
||||
self.record(
|
||||
"fixed_name", [name], [(path, assigned), (path, number), (path, install_line)],
|
||||
case_insensitive=False, search_dir=folder,
|
||||
passes_to=f"component_launcher.sh {flag}", fails_when_missing=False,
|
||||
depends_on_option=f"{function} downloads {urls[source.group(1)]}",
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _function_at(script: Script, number: int) -> str:
|
||||
for line in reversed(script.lines[:number]):
|
||||
found = re.match(r"^([\w-]+)\s*\(\)\s*\{", line)
|
||||
if found is not None:
|
||||
return found.group(1)
|
||||
raise LauncherPatternMissing(f"{script.path}:{number}", "download outside a function")
|
||||
|
||||
|
||||
def _installs(word: str) -> bool:
|
||||
"""A launcher flag that installs a firmware file: RPCS3 --installfw, Vita3K --firmware."""
|
||||
return word.startswith("--install") or word == "--firmware"
|
||||
|
||||
|
||||
def _render_targets(names: list[str], targets: list[str]) -> str:
|
||||
"""Where copied names land: one folder when each keeps its name, else each path."""
|
||||
folders = {split_path(t)[0] for t in targets}
|
||||
kept = [split_path(t)[1] for t in targets] == [PurePosixPath(n).name for n in names]
|
||||
if kept and len(folders) == 1:
|
||||
return f"{folders.pop()}/<name>"
|
||||
return ", ".join(targets)
|
||||
|
||||
|
||||
def core_options(read: Read) -> list[Launcher]:
|
||||
"""RetroArch core options in RetroDECK's preset whose value names a BIOS file."""
|
||||
text = read(CORE_OPTIONS)
|
||||
prepare_path = f"{LIBRETRO_COMPONENT}/component_prepare.sh"
|
||||
prepare = read(prepare_path) or ""
|
||||
if text is None:
|
||||
raise LauncherPatternMissing(CORE_OPTIONS, "preset is missing")
|
||||
copied = [
|
||||
n for n, line in enumerate(prepare.splitlines(), 1)
|
||||
if "retroarch-core-options.cfg" in line and line.strip().startswith("cp ")
|
||||
]
|
||||
if not copied:
|
||||
raise LauncherPatternMissing(prepare_path, "the core options preset is never copied")
|
||||
target = split(prepare.splitlines()[copied[0] - 1].strip())[-1]
|
||||
records = []
|
||||
for line_no, line in enumerate(text.splitlines(), 1):
|
||||
found = re.match(r'^([\w.-]+)\s*=\s*"([^"]*)"$', line.strip())
|
||||
if found is None or not _FILE_VALUE.search(found.group(2)):
|
||||
continue
|
||||
key, value = found.group(1), found.group(2)
|
||||
records.append(Launcher(
|
||||
emulator=LIBRETRO_COMPONENT, build="libretro", kind="core_option", names=[value],
|
||||
passes_to=f"core option {key}", fails_when_missing=False,
|
||||
installs={"path": target, "source_ref": source_ref([(prepare_path, copied[0])])},
|
||||
kept_if_present=False, overrides=[],
|
||||
source_ref=source_ref([(CORE_OPTIONS, line_no), (prepare_path, copied[0])]),
|
||||
))
|
||||
if not records:
|
||||
raise LauncherPatternMissing(CORE_OPTIONS, "no core option names a file")
|
||||
return records
|
||||
|
||||
|
||||
def extract_launchers(components: list[str], read: Read) -> list[dict[str, Any]]:
|
||||
"""Every launcher record of the given components, read through `read(repo path)`.
|
||||
|
||||
`read` returns None only for a file the component does not have.
|
||||
"""
|
||||
records: list[Launcher] = []
|
||||
for name in components:
|
||||
component = Component(name, read)
|
||||
component.read_prepare()
|
||||
component.read_launcher()
|
||||
component.read_firmware_download()
|
||||
records += merge_records(component.records)
|
||||
if LIBRETRO_COMPONENT in components:
|
||||
records += core_options(read)
|
||||
if not records:
|
||||
raise LauncherPatternMissing("components", "no component hands a file to its emulator")
|
||||
return [record.entry() for record in records]
|
||||
@@ -0,0 +1,161 @@
|
||||
"""RetroPie's launcher layer, read from the scriptmodules.
|
||||
|
||||
RetroPie publishes no BIOS list, but its package scripts decide where a file
|
||||
dropped in ~/RetroPie/BIOS ends up: px68k links five names into ~/.keropi,
|
||||
redream links dc_boot.bin under another name, sdltrs passes one ROM per
|
||||
machine on its command line, the fs-uae launch script refuses to start
|
||||
without kick13.rom. Each package also says which project it builds
|
||||
(`rp_module_repo`) and which systems it registers (`addSystem`), which is
|
||||
what ties a package to the emulator profile describing that build.
|
||||
|
||||
The bash is read as text, never run. A small evaluator follows what the
|
||||
scripts do between a function's braces: local assignments, arrays, `for`
|
||||
loops, brace expansion, `$md_id` and calls into other packages' functions,
|
||||
the way RetroPie runs them in one shell. Every line of a package function
|
||||
that names the BIOS directory must match a known construct, else the scrape
|
||||
stops with LauncherPatternMissing: a use nobody classified would otherwise
|
||||
drop out of the platform file without a word.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from pathlib import PurePosixPath
|
||||
from typing import Any
|
||||
|
||||
from .retropie_reader import PackageReader, mentions_bios, split_path
|
||||
from .retropie_scripts import (
|
||||
Launcher,
|
||||
LauncherPatternMissing,
|
||||
Module,
|
||||
SCRIPTMODULES,
|
||||
SECTIONS,
|
||||
Scripts,
|
||||
VAR,
|
||||
merge_records,
|
||||
source_ref,
|
||||
)
|
||||
|
||||
PACKAGES_SCRIPT = "retropie_packages.sh"
|
||||
|
||||
|
||||
def package_record(scripts: Scripts, package: Module) -> Launcher:
|
||||
"""What the package builds and the systems it registers."""
|
||||
systems: list[str] = []
|
||||
lines: list[tuple[str, int]] = [(package.path, package.id_line)]
|
||||
if package.repo_line is not None:
|
||||
lines.append((package.path, package.repo_line))
|
||||
for event in scripts.walk(package):
|
||||
if event.heredoc or not event.words or not event.words[0]:
|
||||
continue
|
||||
command = event.words[0][0]
|
||||
if command == "addSystem":
|
||||
values = event.words[1] if len(event.words) > 1 else []
|
||||
elif command == "addPort":
|
||||
values = ["ports"]
|
||||
else:
|
||||
continue
|
||||
if not values:
|
||||
raise LauncherPatternMissing(f"{event.path}:{event.line}", f"{command} takes no value")
|
||||
for value in values:
|
||||
if "$" in value or not value:
|
||||
raise LauncherPatternMissing(
|
||||
f"{event.path}:{event.line}", f"system name {value!r} not resolved"
|
||||
)
|
||||
if value not in systems:
|
||||
systems.append(value)
|
||||
lines.append((event.path, event.line))
|
||||
return Launcher(
|
||||
emulator=package.id, package=package.id, repo=package.repo,
|
||||
systems=systems or None, build=package.build, kind="package", names=[],
|
||||
source_ref=source_ref(lines),
|
||||
)
|
||||
|
||||
|
||||
def launch_script_records(scripts: Scripts) -> list[Launcher]:
|
||||
"""The launch scripts installed next to an emulator that refuse to start without a file."""
|
||||
records = []
|
||||
for path, text in sorted(scripts.files.items()):
|
||||
parts = PurePosixPath(path).parts
|
||||
is_script = (
|
||||
len(parts) == 4 and parts[0] == SCRIPTMODULES and parts[1] in SECTIONS
|
||||
and path.endswith(".sh")
|
||||
)
|
||||
if not is_script or not mentions_bios(text):
|
||||
continue
|
||||
package = scripts.modules.get(parts[2])
|
||||
if package is None:
|
||||
raise LauncherPatternMissing(path, f"launch script of no package {parts[2]}")
|
||||
records += _launch_script(path, text.splitlines(), package)
|
||||
return records
|
||||
|
||||
|
||||
def _launch_script(path: str, lines: list[str], package: Module) -> list[Launcher]:
|
||||
env: dict[str, str] = {"HOME": "$HOME"}
|
||||
records = []
|
||||
checks = 0
|
||||
number = 0
|
||||
while number < len(lines):
|
||||
number += 1
|
||||
stripped = lines[number - 1].strip()
|
||||
if not stripped or stripped.startswith("#"):
|
||||
continue
|
||||
assign = re.match(r'^([A-Za-z_]\w*)="([^"]*)"$', stripped)
|
||||
if assign is not None:
|
||||
env[assign.group(1)] = VAR.sub(
|
||||
lambda m: env.get(m.group(1) or m.group(3), m.group(0)), assign.group(2)
|
||||
)
|
||||
continue
|
||||
check = re.match(r'^if \[\[ ! -f "([^"]+)" \]\]; then$', stripped)
|
||||
if check is None:
|
||||
continue
|
||||
tested = check.group(1)
|
||||
resolved = VAR.sub(lambda m: env.get(m.group(1) or m.group(3), m.group(0)), tested)
|
||||
if not mentions_bios(resolved):
|
||||
continue
|
||||
block_start = number
|
||||
message: str | None = None
|
||||
exits = False
|
||||
while number < len(lines) and lines[number].strip() != "fi":
|
||||
number += 1
|
||||
body = lines[number - 1].strip()
|
||||
exits = exits or body == "exit 1"
|
||||
pause = re.search(r'--pause "([^"]*)"', body)
|
||||
if pause is not None:
|
||||
message = pause.group(1)
|
||||
number += 1
|
||||
if not exits:
|
||||
continue
|
||||
checks += 1
|
||||
variable = re.fullmatch(r"\$\{?(\w+)\}?", tested)
|
||||
passes_to = None
|
||||
cited = list(range(block_start, number + 1))
|
||||
if variable is not None:
|
||||
for later, line in enumerate(lines[number:], number + 1):
|
||||
flag = re.search(r'(--?[\w-]+)="\$' + variable.group(1) + r'"', line)
|
||||
if flag is not None:
|
||||
passes_to = f"command line {flag.group(1)}"
|
||||
cited.append(later)
|
||||
break
|
||||
folder, name = split_path(resolved)
|
||||
records.append(Launcher(
|
||||
emulator=package.id, package=package.id, build=package.build,
|
||||
kind="fixed_name", names=[name], case_insensitive=False,
|
||||
search_dir=folder, passes_to=passes_to,
|
||||
fails_when_missing=message if message is not None else True,
|
||||
source_ref=source_ref([(path, n) for n in cited]),
|
||||
))
|
||||
if not checks:
|
||||
raise LauncherPatternMissing(path, "names the BIOS directory but checks no file")
|
||||
return records
|
||||
|
||||
|
||||
def extract_launchers(files: dict[str, str]) -> list[dict[str, Any]]:
|
||||
"""Every launcher record, from the scriptmodules keyed by repo-relative path."""
|
||||
scripts = Scripts(files)
|
||||
records: list[Launcher] = []
|
||||
for package in sorted(scripts.modules.values(), key=lambda m: m.path):
|
||||
records.append(package_record(scripts, package))
|
||||
records += merge_records(PackageReader(scripts, package).read())
|
||||
records += launch_script_records(scripts)
|
||||
return [record.entry() for record in records]
|
||||
@@ -0,0 +1,540 @@
|
||||
"""Launcher records of one RetroPie package, from the statements its functions run."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from pathlib import PurePosixPath
|
||||
from typing import Any
|
||||
|
||||
from .retropie_scripts import (
|
||||
Event,
|
||||
Launcher,
|
||||
LauncherPatternMissing,
|
||||
Module,
|
||||
Scripts,
|
||||
FUNCTION,
|
||||
split,
|
||||
source_ref,
|
||||
)
|
||||
|
||||
|
||||
BIOSDIR = "$biosdir"
|
||||
# The roms root (retropie_packages.sh:47-49): MAME's mame.ini lists rom,
|
||||
# sample and artwork folders below it (scriptmodules/emulators/mame.sh:133-136).
|
||||
ROMDIR = "$romdir"
|
||||
|
||||
|
||||
# The launch scripts copied next to an emulator spell the directory out.
|
||||
BIOS_SPELLED = "RetroPie/BIOS"
|
||||
|
||||
# Commands whose $biosdir argument creates, owns or deletes a path and hands
|
||||
# nothing to an emulator.
|
||||
HOUSEKEEPING = frozenset({"mkUserDir", "chown", "chmod", "rm", "mkdir", "iniConfig"})
|
||||
|
||||
# Arguments that name a BIOS file or directory outside $biosdir, per package,
|
||||
# as the emulator documents the flag. Each must still be in the scriptmodule.
|
||||
OUTSIDE_BIOS: dict[str, tuple[str, ...]] = {
|
||||
"basilisk": ("--rom",), # BasiliskII --rom <ROM file>
|
||||
"gngeopi": ("-B",), # gngeo -B/--biospath <directory of neogeo.zip>
|
||||
}
|
||||
|
||||
# Packages whose emulator reads its system files below the working directory
|
||||
# the generated launch script enters with pushd: DraStic opens system/<name>
|
||||
# under it, UAE4All2 kickstarts/<name> (its launchDir is getcwd()). Each must
|
||||
# still pushd.
|
||||
WORKING_DIRECTORY: tuple[str, ...] = ("drastic", "uae4all")
|
||||
|
||||
|
||||
_EXTENSION = re.compile(r"\.[A-Za-z0-9]{1,5}$")
|
||||
|
||||
|
||||
# The character each program splits a search list on, read in its code.
|
||||
# AdvanceMAME strtoks dir_rom on file_dir_separator(), ':' on Linux, in all
|
||||
# three builds RetroPie ships (advance/linux/file.c:138-141 and
|
||||
# advance/osd/fileio.c:696-699 at 96237a5, 685-688 at advancemame-1.4,
|
||||
# 640-643 in advancemame-0.94.0.tar.gz). MAME's path_iterator splits on ';'
|
||||
# whatever the system (src/emu/fileio.cpp:56, 64, 112 at mame0289).
|
||||
LIST_SEPARATORS = {"advmame": ":", "advmame-0.94": ":", "advmame-1.4": ":"}
|
||||
DEFAULT_LIST_SEPARATOR = ";"
|
||||
|
||||
|
||||
def _search_list_in_roms(event: Event, separator: str = DEFAULT_LIST_SEPARATOR) -> bool:
|
||||
"""An iniSet whose value is a list of folders below the roms root.
|
||||
|
||||
One folder alone is where a program writes (cfg_directory, nvram_directory
|
||||
and the others MAME's mame.ini sets): a list is where it searches, split
|
||||
on the separator the program reads it with.
|
||||
"""
|
||||
if len(event.words) < 3 or len(event.words[2]) != 1:
|
||||
return False
|
||||
parts = [p for p in event.words[2][0].split(separator) if p]
|
||||
return len(parts) > 1 and all(
|
||||
p.startswith((ROMDIR + "/", "${romdir}/")) for p in parts
|
||||
)
|
||||
|
||||
|
||||
def mentions_bios(text: str) -> bool:
|
||||
return BIOSDIR in text or "${biosdir}" in text or BIOS_SPELLED in text
|
||||
|
||||
|
||||
def _is_file(path: str) -> bool:
|
||||
return bool(_EXTENSION.search(PurePosixPath(path).name)) and "*" not in path
|
||||
|
||||
|
||||
def split_path(path: str) -> tuple[str, str]:
|
||||
pure = PurePosixPath(path.rstrip("/"))
|
||||
return str(pure.parent), pure.name
|
||||
|
||||
|
||||
class PackageReader:
|
||||
"""Launcher records of one package, from the statements its functions run."""
|
||||
|
||||
def __init__(self, scripts: Scripts, package: Module) -> None:
|
||||
self.scripts = scripts
|
||||
self.package = package
|
||||
self.records: list[Launcher] = []
|
||||
self.installed_as: dict[str, str] = {}
|
||||
|
||||
def record(
|
||||
self, kind: str, names: list[str], lines: list[tuple[str, int]], **fields: Any
|
||||
) -> None:
|
||||
self.records.append(Launcher(
|
||||
emulator=fields.pop("emulator", self.package.id),
|
||||
package=self.package.id,
|
||||
build=self.package.build,
|
||||
kind=kind,
|
||||
names=names,
|
||||
source_ref=source_ref(lines),
|
||||
lines=list(lines),
|
||||
**fields,
|
||||
))
|
||||
|
||||
def final(self, path: str) -> str:
|
||||
"""The file a scratch config ends up as, from the copyDefaultConfig that installs it."""
|
||||
return self.installed_as.get(path, path)
|
||||
|
||||
def read(self) -> list[Launcher]:
|
||||
events = self.scripts.walk(self.package)
|
||||
for event in events:
|
||||
if (
|
||||
not event.heredoc and event.words and event.words[0] == ["copyDefaultConfig"]
|
||||
and len(event.words) >= 3 and len(event.words[1]) == 1 and len(event.words[2]) == 1
|
||||
):
|
||||
self.installed_as.setdefault(event.words[1][0], event.words[2][0])
|
||||
links: list[Event] = []
|
||||
for event in events:
|
||||
if not event.words or not event.words[0]:
|
||||
continue
|
||||
if links and not self._same_link_run(links[-1], event):
|
||||
self._links(links)
|
||||
links = []
|
||||
if self._is_bios_link(event):
|
||||
links.append(event)
|
||||
continue
|
||||
self._classify(event)
|
||||
if links:
|
||||
self._links(links)
|
||||
self._outside_bios(events)
|
||||
self._working_directory(events)
|
||||
self._reaching_links(events)
|
||||
return self.records
|
||||
|
||||
@staticmethod
|
||||
def _depends(event: Event) -> str | None:
|
||||
return "; ".join(event.conditions) if event.conditions else None
|
||||
|
||||
def _classify(self, event: Event) -> None:
|
||||
command = event.words[0][0]
|
||||
if event.heredoc:
|
||||
if mentions_bios(event.raw):
|
||||
self._heredoc_setting(event)
|
||||
return
|
||||
if command == "addEmulator":
|
||||
self._add_emulator(event)
|
||||
return
|
||||
if command == "iniSet" and not mentions_bios(event.raw):
|
||||
# A search path below the roms root: MAME reads its samples from
|
||||
# samplepath $romdir/mame/samples;$romdir/arcade/samples.
|
||||
if _search_list_in_roms(
|
||||
event, LIST_SEPARATORS.get(self.package.id, DEFAULT_LIST_SEPARATOR)
|
||||
):
|
||||
self._ini_set(event)
|
||||
return
|
||||
if not mentions_bios(event.raw):
|
||||
return
|
||||
if command in HOUSEKEEPING:
|
||||
return
|
||||
handlers = {
|
||||
"cp": self._copy,
|
||||
"runCmd": self._run_cmd,
|
||||
"unzip": self._unzip,
|
||||
"mv": self._move,
|
||||
"moveConfigFile": self._move,
|
||||
"moveConfigDir": self._move_dir,
|
||||
"iniSet": self._ini_set,
|
||||
"copyDefaultConfig": self._written,
|
||||
"cat": self._written,
|
||||
"echo": self._written,
|
||||
"cmake": self._build_flag,
|
||||
}
|
||||
handler = handlers.get(command)
|
||||
if handler is None:
|
||||
raise LauncherPatternMissing(
|
||||
f"{event.path}:{event.line}", f"unrecognised use of the BIOS directory: {event.raw}"
|
||||
)
|
||||
handler(event)
|
||||
|
||||
def _is_bios_link(self, event: Event) -> bool:
|
||||
words = event.words
|
||||
if words[0][0] != "ln" or not mentions_bios(event.raw):
|
||||
return False
|
||||
paths = [w for w in words[1:] if not w[0].startswith("-")]
|
||||
if len(paths) != 2 or not all(mentions_bios(v) for v in paths[0]):
|
||||
raise LauncherPatternMissing(
|
||||
f"{event.path}:{event.line}", f"link without a BIOS source: {event.raw}"
|
||||
)
|
||||
return True
|
||||
|
||||
@staticmethod
|
||||
def _same_link_run(previous: Event, event: Event) -> bool:
|
||||
return (
|
||||
event.words[0][0] == "ln"
|
||||
and previous.path == event.path
|
||||
and event.line - previous.line <= 2
|
||||
)
|
||||
|
||||
def _links(self, events: list[Event]) -> None:
|
||||
sources: list[str] = []
|
||||
targets: list[str] = []
|
||||
for event in events:
|
||||
paths = [w for w in event.words[1:] if not w[0].startswith("-")]
|
||||
source, target = paths
|
||||
if len(target) == 1 and len(source) > 1:
|
||||
target = [f"{target[0].rstrip('/')}/{split_path(s)[1]}" for s in source]
|
||||
sources += source
|
||||
targets += target
|
||||
folders = {split_path(s)[0] for s in sources}
|
||||
whole_dir = all(
|
||||
not _is_file(s) and "/" not in s.replace(BIOSDIR, "", 1).strip("/") for s in sources
|
||||
)
|
||||
if whole_dir:
|
||||
names: list[str] = []
|
||||
search_dir = sources[0]
|
||||
passes_to = f"{targets[0]} is a symlink to it"
|
||||
else:
|
||||
if len(folders) != 1:
|
||||
raise LauncherPatternMissing(
|
||||
f"{events[0].path}:{events[0].line}",
|
||||
"links from several BIOS folders in one run",
|
||||
)
|
||||
search_dir = folders.pop()
|
||||
names = [split_path(s)[1] for s in sources]
|
||||
passes_to = _render_targets(names, targets)
|
||||
self.record(
|
||||
"links", names, [(e.path, e.line) for e in events],
|
||||
case_insensitive=False, search_dir=search_dir, passes_to=passes_to,
|
||||
fails_when_missing=False, depends_on_option=self._depends(events[0]),
|
||||
)
|
||||
|
||||
def _copy(self, event: Event) -> None:
|
||||
paths = [v for w in event.words[1:] if not w[0].startswith("-") for v in w]
|
||||
*sources, target = paths
|
||||
if not mentions_bios(target):
|
||||
raise LauncherPatternMissing(
|
||||
f"{event.path}:{event.line}", f"copy out of the BIOS directory: {event.raw}"
|
||||
)
|
||||
folders = {split_path(s)[0] for s in sources}
|
||||
if len(folders) != 1:
|
||||
raise LauncherPatternMissing(f"{event.path}:{event.line}", "copy from several folders")
|
||||
self.record(
|
||||
"copies", [split_path(s)[1] for s in sources], [(event.path, event.line)],
|
||||
search_dir=folders.pop(), passes_to=target.rstrip("/"),
|
||||
fails_when_missing=False, depends_on_option=self._depends(event),
|
||||
)
|
||||
|
||||
def _run_cmd(self, event: Event) -> None:
|
||||
inner = Event(event.path, event.line, event.words[1:], event.raw, event.conditions, False)
|
||||
if not inner.words or inner.words[0][0] != "unzip":
|
||||
raise LauncherPatternMissing(f"{event.path}:{event.line}", f"runCmd of {event.raw}")
|
||||
self._unzip(inner)
|
||||
|
||||
def _unzip(self, event: Event) -> None:
|
||||
values = [v for w in event.words[1:] for v in w]
|
||||
if "-d" not in values:
|
||||
raise LauncherPatternMissing(f"{event.path}:{event.line}", "unzip without -d")
|
||||
target = values[values.index("-d") + 1]
|
||||
archives = [v for v in values if v.endswith(".zip")]
|
||||
if len(archives) != 1 or not mentions_bios(target):
|
||||
raise LauncherPatternMissing(f"{event.path}:{event.line}", f"unzip of {event.raw}")
|
||||
self.record(
|
||||
"copies", [], [(event.path, event.line)],
|
||||
search_dir=archives[0], passes_to=target,
|
||||
fails_when_missing=False, depends_on_option=self._depends(event),
|
||||
)
|
||||
|
||||
def _move(self, event: Event) -> None:
|
||||
source, target = (w for w in event.words[1:] if not w[0].startswith("-"))
|
||||
if not all(mentions_bios(v) for v in source + target):
|
||||
raise LauncherPatternMissing(
|
||||
f"{event.path}:{event.line}", f"move across folders: {event.raw}"
|
||||
)
|
||||
folders = {split_path(s)[0] for s in source}
|
||||
destinations = {split_path(t)[0] for t in target}
|
||||
if len(folders) != 1 or len(destinations) != 1:
|
||||
raise LauncherPatternMissing(
|
||||
f"{event.path}:{event.line}", "move between several folders"
|
||||
)
|
||||
self.record(
|
||||
"moves", [split_path(s)[1] for s in source], [(event.path, event.line)],
|
||||
case_insensitive=False, search_dir=folders.pop(), passes_to=destinations.pop(),
|
||||
fails_when_missing=False, depends_on_option=self._depends(event),
|
||||
)
|
||||
|
||||
def _move_dir(self, event: Event) -> None:
|
||||
link, real = (w[0] for w in event.words[1:3])
|
||||
if not mentions_bios(real) or mentions_bios(link):
|
||||
raise LauncherPatternMissing(
|
||||
f"{event.path}:{event.line}", f"moveConfigDir into a non-BIOS folder: {event.raw}"
|
||||
)
|
||||
self.record(
|
||||
"links", [], [(event.path, event.line)],
|
||||
search_dir=real, passes_to=f"{link} is a symlink to it",
|
||||
fails_when_missing=False, depends_on_option=self._depends(event),
|
||||
)
|
||||
|
||||
def _ini_set(self, event: Event) -> None:
|
||||
key, value = event.words[1][0], event.words[2][0]
|
||||
target = self._ini_file(event)
|
||||
passes_to = f"{key} in {self.final(target)}" if target else key
|
||||
if _is_file(value) and ";" not in value:
|
||||
folder, name = split_path(value)
|
||||
self.record(
|
||||
"fixed_name", [name], [(event.path, event.line)],
|
||||
case_insensitive=False, search_dir=folder, passes_to=passes_to,
|
||||
fails_when_missing=False, depends_on_option=self._depends(event),
|
||||
)
|
||||
return
|
||||
self.record(
|
||||
"passes_path", [], [(event.path, event.line)],
|
||||
search_dir=value, passes_to=passes_to,
|
||||
fails_when_missing=False, depends_on_option=self._depends(event),
|
||||
)
|
||||
|
||||
def _ini_file(self, event: Event) -> str | None:
|
||||
"""The file the closest iniConfig above this iniSet points at."""
|
||||
if len(event.words) > 3:
|
||||
return event.words[3][0]
|
||||
lines = self.scripts.files[event.path].splitlines()
|
||||
for number in range(event.line - 1, 0, -1):
|
||||
words = split(lines[number - 1].strip())
|
||||
if words and words[0] == "iniConfig" and len(words) >= 4:
|
||||
return words[3]
|
||||
if FUNCTION.match(lines[number - 1]):
|
||||
break
|
||||
return None
|
||||
|
||||
def _written(self, event: Event) -> None:
|
||||
"""A file the package writes into the BIOS directory itself."""
|
||||
target = next(
|
||||
(v for w in reversed(event.words[1:]) for v in w if mentions_bios(v)), None
|
||||
)
|
||||
if target is None or not _is_file(target):
|
||||
raise LauncherPatternMissing(f"{event.path}:{event.line}", f"write of {event.raw}")
|
||||
folder, name = split_path(target)
|
||||
self.record(
|
||||
"copies", [name], [(event.path, event.line)],
|
||||
search_dir=None, passes_to=folder,
|
||||
fails_when_missing=False, depends_on_option=self._depends(event),
|
||||
)
|
||||
|
||||
def _build_flag(self, event: Event) -> None:
|
||||
flags = [
|
||||
v for w in event.words[1:] for v in w
|
||||
if v.startswith("-D") and "=" in v and mentions_bios(v)
|
||||
]
|
||||
if not flags:
|
||||
raise LauncherPatternMissing(f"{event.path}:{event.line}", f"cmake of {event.raw}")
|
||||
for flag in flags:
|
||||
option, value = flag.split("=", 1)
|
||||
self.record(
|
||||
"passes_path", [], [(event.path, event.line)],
|
||||
search_dir=value, passes_to=f"build option {option}",
|
||||
fails_when_missing=False, depends_on_option=self._depends(event),
|
||||
)
|
||||
|
||||
def _heredoc_setting(self, event: Event) -> None:
|
||||
"""A `KEY = $biosdir/...` or `--flag="$biosdir"` line of a generated file."""
|
||||
text = event.raw
|
||||
setting = re.match(r'^([\w.-]+)\s*=\s*"?([^"]*)"?$', text)
|
||||
flag = re.match(r'^(--?[\w-]+)(?:=|\s+)"?([^"]*)"?$', text)
|
||||
found = flag or setting
|
||||
if found is None:
|
||||
raise LauncherPatternMissing(
|
||||
f"{event.path}:{event.line}", f"generated line names the BIOS directory: {text}"
|
||||
)
|
||||
key, value = found.group(1), found.group(2)
|
||||
kind, names, folder = "passes_path", [], value
|
||||
if _is_file(value):
|
||||
folder, name = split_path(value)
|
||||
kind, names = "fixed_name", [name]
|
||||
written = _redirect_target(event.opener)
|
||||
if written is None:
|
||||
raise LauncherPatternMissing(
|
||||
f"{event.path}:{event.line}", "generated file with no > or >> target"
|
||||
)
|
||||
self.record(
|
||||
kind, names, [(event.path, event.line)],
|
||||
case_insensitive=False if kind == "fixed_name" else None,
|
||||
search_dir=folder, passes_to=f"{key} in {self.final(written)}",
|
||||
fails_when_missing=False, depends_on_option=self._depends(event),
|
||||
)
|
||||
|
||||
def _add_emulator(self, event: Event) -> None:
|
||||
if len(event.words) < 5:
|
||||
return
|
||||
command = event.words[4][0]
|
||||
if not mentions_bios(command):
|
||||
return
|
||||
names = event.words[2]
|
||||
tokens = split(command)
|
||||
found = [
|
||||
(flag, value) for flag, value in zip(tokens, tokens[1:])
|
||||
if flag.startswith("-") and mentions_bios(value)
|
||||
]
|
||||
found += [
|
||||
(head, tail) for head, sep, tail in (token.partition("=") for token in tokens)
|
||||
if head.startswith("-") and sep and mentions_bios(tail)
|
||||
]
|
||||
if not found:
|
||||
raise LauncherPatternMissing(
|
||||
f"{event.path}:{event.line}",
|
||||
f"addEmulator names the BIOS directory without a flag: {command}",
|
||||
)
|
||||
for emulator in names:
|
||||
for flag, value in found:
|
||||
self._command_line(event, emulator, flag, value)
|
||||
|
||||
def _command_line(self, event: Event, emulator: str, flag: str, value: str) -> None:
|
||||
folder, name = split_path(value)
|
||||
if _is_file(value):
|
||||
kind, names, search = "fixed_name", [name], folder
|
||||
else:
|
||||
kind, names, search = "passes_path", [], value
|
||||
self.record(
|
||||
kind, names, [(event.path, event.line)], emulator=emulator,
|
||||
case_insensitive=False if kind == "fixed_name" else None,
|
||||
search_dir=search, passes_to=f"command line {flag}",
|
||||
fails_when_missing=False, depends_on_option=self._depends(event),
|
||||
)
|
||||
|
||||
def _outside_bios(self, events: list[Event]) -> None:
|
||||
flags = OUTSIDE_BIOS.get(self.package.id)
|
||||
if not flags:
|
||||
return
|
||||
seen: set[str] = set()
|
||||
for event in events:
|
||||
if event.words[0][0] != "addEmulator" or len(event.words) < 5:
|
||||
continue
|
||||
tokens = split(event.words[4][0])
|
||||
for flag, value in zip(tokens, tokens[1:]):
|
||||
if flag in flags:
|
||||
seen.add(flag)
|
||||
for emulator in event.words[2]:
|
||||
self._command_line(event, emulator, flag, value)
|
||||
missing = sorted(set(flags) - seen)
|
||||
if missing:
|
||||
raise LauncherPatternMissing(
|
||||
self.package.path, f"addEmulator no longer passes {missing}"
|
||||
)
|
||||
|
||||
|
||||
def _reaching_links(self, events: list[Event]) -> None:
|
||||
"""The directories outside the BIOS one that a whole-directory link lies in.
|
||||
|
||||
openmsx's moveConfigDir "$home/.openMSX" "$configdir/msx/openmsx"
|
||||
puts the emulator's directory where the systemroms link to BIOS/openmsx
|
||||
lies, and xroar's ./configure --prefix="$md_inst" builds the program
|
||||
whose share/xroar/roms links to $biosdir. Neither line names the BIOS
|
||||
directory, and each says where the link is read from.
|
||||
"""
|
||||
suffix = " is a symlink to it"
|
||||
linked = [
|
||||
(record.passes_to or "").removesuffix(suffix).rstrip("/")
|
||||
for record in self.records
|
||||
if record.kind == "links" and not record.names
|
||||
and (record.passes_to or "").endswith(suffix)
|
||||
]
|
||||
if not linked:
|
||||
return
|
||||
|
||||
def holds(directory: str) -> bool:
|
||||
directory = directory.strip("\"'").rstrip("/")
|
||||
return bool(directory) and any(
|
||||
path == directory or path.startswith(directory + "/") for path in linked
|
||||
)
|
||||
|
||||
for event in events:
|
||||
if event.heredoc or not event.words or mentions_bios(event.raw):
|
||||
continue
|
||||
command = event.words[0][0]
|
||||
if command == "moveConfigDir" and len(event.words) >= 3:
|
||||
link, real = event.words[1][0], event.words[2][0]
|
||||
if holds(real):
|
||||
self.record(
|
||||
"links", [], [(event.path, event.line)],
|
||||
search_dir=real, passes_to=f"{link}{suffix}",
|
||||
fails_when_missing=False, depends_on_option=self._depends(event),
|
||||
)
|
||||
elif command.endswith("configure"):
|
||||
for word in event.words[1:]:
|
||||
prefix = word[0].strip("\"'")
|
||||
if prefix.startswith("--prefix=") and holds(prefix[len("--prefix="):]):
|
||||
self.record(
|
||||
"passes_path", [], [(event.path, event.line)],
|
||||
search_dir=prefix[len("--prefix="):].strip("\"'"),
|
||||
passes_to="${prefix} of configure --prefix",
|
||||
fails_when_missing=False, depends_on_option=self._depends(event),
|
||||
)
|
||||
|
||||
def _working_directory(self, events: list[Event]) -> None:
|
||||
"""The folder a generated launch script enters before it runs the emulator."""
|
||||
if self.package.id not in WORKING_DIRECTORY:
|
||||
return
|
||||
found = False
|
||||
for event in events:
|
||||
if not event.heredoc or not event.words or event.words[0] != ["pushd"]:
|
||||
continue
|
||||
script = _redirect_target(event.opener)
|
||||
if script is None or len(event.words) != 2 or len(event.words[1]) != 1:
|
||||
raise LauncherPatternMissing(
|
||||
f"{event.path}:{event.line}", f"pushd outside a launch script: {event.raw}"
|
||||
)
|
||||
found = True
|
||||
self.record(
|
||||
"passes_path", [], [(event.path, event.line)],
|
||||
search_dir=event.words[1][0].strip("\"'"),
|
||||
passes_to=f"working directory of {script}",
|
||||
fails_when_missing=False, depends_on_option=self._depends(event),
|
||||
)
|
||||
if not found:
|
||||
raise LauncherPatternMissing(
|
||||
self.package.path, "the launch script no longer enters a working directory"
|
||||
)
|
||||
|
||||
|
||||
def _redirect_target(words: list[list[str]]) -> str | None:
|
||||
"""The file a `cat > FILE << EOF` or `cat << EOF >> FILE` line writes."""
|
||||
flat = [w[0] for w in words if w]
|
||||
for index, word in enumerate(flat[:-1]):
|
||||
if word in (">", ">>"):
|
||||
return flat[index + 1]
|
||||
return None
|
||||
|
||||
|
||||
def _render_targets(names: list[str], targets: list[str]) -> str:
|
||||
"""Where linked names land: one folder when the names are kept, each path when renamed."""
|
||||
folders = {split_path(t)[0] for t in targets}
|
||||
kept = [split_path(t)[1] for t in targets] == names
|
||||
if kept and len(folders) == 1:
|
||||
return f"{folders.pop()}/<name>"
|
||||
return ", ".join(targets)
|
||||
@@ -0,0 +1,497 @@
|
||||
"""RetroPie's scriptmodules loaded as one shell, and the launcher record read from them."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import shlex
|
||||
from collections.abc import Iterator
|
||||
from dataclasses import dataclass, field
|
||||
from functools import partial
|
||||
from itertools import product
|
||||
from pathlib import PurePosixPath
|
||||
from typing import Any, ClassVar
|
||||
|
||||
from .configgen import Launcher as ConfiggenLauncher
|
||||
from ..retropie_modules import module_field_lines
|
||||
|
||||
|
||||
SCRIPTMODULES = "scriptmodules"
|
||||
SECTIONS = ("emulators", "libretrocores", "ports")
|
||||
|
||||
|
||||
# The package whose config every lr- core runs under.
|
||||
LIBRETRO_FRONTEND = "retroarch"
|
||||
|
||||
|
||||
FUNCTION = re.compile(r"^function\s+([\w.+-]+)\s*\(\)\s*\{\s*$")
|
||||
_ASSIGN = re.compile(r"^(?:local\s+)?([A-Za-z_]\w*)=(.*)$")
|
||||
_DECLARE = re.compile(r"^local\s+([A-Za-z_]\w*(?:\s+[A-Za-z_]\w*)*)\s*$")
|
||||
_FOR = re.compile(r"^for\s+([A-Za-z_]\w*)\s+in\s+(.*?)\s*(?:;\s*do)?\s*$")
|
||||
_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*\]\]$')
|
||||
|
||||
|
||||
class LauncherPatternMissing(ValueError):
|
||||
"""A construct an extractor reads is absent from the scriptmodules."""
|
||||
|
||||
def __init__(self, path: str, what: str) -> None:
|
||||
super().__init__(f"{path}: {what}")
|
||||
|
||||
|
||||
@dataclass
|
||||
class Launcher(ConfiggenLauncher):
|
||||
"""One thing a package hands an emulator, or the package itself."""
|
||||
|
||||
# Unset when the package script checks nothing, where configgen writes False.
|
||||
fails_when_missing: bool | str | None = None
|
||||
package: str | None = None
|
||||
repo: str | None = None
|
||||
lines: list[tuple[str, int]] = field(default_factory=list, repr=False)
|
||||
|
||||
ENTRY_ORDER: ClassVar[tuple[str, ...]] = (
|
||||
"emulator", "package", "repo", "systems", "build", "kind", "slot",
|
||||
"names", "case_insensitive", "search_dir", "passes_to",
|
||||
"fails_when_missing", "depends_on_option", "installs", "kept_if_present",
|
||||
"overrides", "source_ref",
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
class Module:
|
||||
"""One package script: its id, section, lines and functions."""
|
||||
|
||||
path: str
|
||||
section: str
|
||||
lines: list[str]
|
||||
id: str
|
||||
id_line: int
|
||||
repo: str | None
|
||||
repo_line: int | None
|
||||
functions: dict[str, tuple[int, int]] = field(default_factory=dict)
|
||||
|
||||
@property
|
||||
def build(self) -> str:
|
||||
libretro = self.section == "libretrocores" or self.id == LIBRETRO_FRONTEND
|
||||
return "libretro" if libretro else "standalone"
|
||||
|
||||
|
||||
@dataclass
|
||||
class Event:
|
||||
"""A statement reached while walking a package's functions."""
|
||||
|
||||
path: str
|
||||
line: int
|
||||
words: list[list[str]]
|
||||
raw: str
|
||||
conditions: list[str]
|
||||
heredoc: bool
|
||||
opener: list[list[str]] = field(default_factory=list)
|
||||
|
||||
|
||||
def _logical_lines(
|
||||
lines: list[str], start: int, end: int
|
||||
) -> Iterator[tuple[int, str, str | None]]:
|
||||
"""(line number, text, heredoc opener or None) for lines start..end, continuations joined."""
|
||||
tag: str | None = None
|
||||
opener = ""
|
||||
number = start
|
||||
while number <= end:
|
||||
text = lines[number - 1]
|
||||
first = number
|
||||
if tag is not None:
|
||||
if text.strip() == tag:
|
||||
tag = None
|
||||
else:
|
||||
yield first, text, opener
|
||||
number += 1
|
||||
continue
|
||||
while text.rstrip().endswith("\\") and number < end:
|
||||
number += 1
|
||||
text = text.rstrip()[:-1] + " " + lines[number - 1].strip()
|
||||
opened = _HEREDOC.search(text)
|
||||
if opened is not None:
|
||||
tag = opened.group(1)
|
||||
opener = text.strip()
|
||||
yield first, text, None
|
||||
number += 1
|
||||
|
||||
|
||||
def _brace(word: str) -> list[str]:
|
||||
"""Bash brace expansion of comma lists, outside variable references."""
|
||||
found = re.search(r"(?<!\$)\{([^{}$]*,[^{}$]*)\}", word)
|
||||
if found is None:
|
||||
return [word]
|
||||
head, tail = word[: found.start()], word[found.end():]
|
||||
return [
|
||||
expanded
|
||||
for option in found.group(1).split(",")
|
||||
for expanded in _brace(head + option + tail)
|
||||
]
|
||||
|
||||
|
||||
def split(text: str) -> list[str]:
|
||||
"""Shell words with quotes removed, a line bash itself would accept."""
|
||||
try:
|
||||
return shlex.split(text, comments=True)
|
||||
except ValueError:
|
||||
return text.split()
|
||||
|
||||
|
||||
class Scripts:
|
||||
"""Every package script, with the functions RetroPie loads into one shell."""
|
||||
|
||||
def __init__(self, files: dict[str, str]) -> None:
|
||||
self.files = files
|
||||
self.modules: dict[str, Module] = {}
|
||||
self.owner: dict[str, Module] = {}
|
||||
self._walked: dict[str, list[Event]] = {}
|
||||
for path in sorted(files):
|
||||
parts = PurePosixPath(path).parts
|
||||
is_package = (
|
||||
len(parts) == 3
|
||||
and parts[0] == SCRIPTMODULES
|
||||
and parts[1] in SECTIONS
|
||||
and parts[2].endswith(".sh")
|
||||
)
|
||||
if is_package:
|
||||
module = self._parse(path, parts[1], files[path])
|
||||
if module is not None:
|
||||
self.modules[module.id] = module
|
||||
if not self.modules:
|
||||
raise LauncherPatternMissing(SCRIPTMODULES, "no package script declares rp_module_id")
|
||||
for module in self.modules.values():
|
||||
for name in module.functions:
|
||||
self.owner[name] = module
|
||||
|
||||
@staticmethod
|
||||
def _parse(path: str, section: str, text: str) -> Module | None:
|
||||
lines = text.splitlines()
|
||||
fields = module_field_lines(text)
|
||||
if "id" not in fields:
|
||||
return None
|
||||
repo = fields.get("repo")
|
||||
module = Module(
|
||||
path=path, section=section, lines=lines,
|
||||
id=fields["id"][0], id_line=fields["id"][1],
|
||||
repo=repo[0] if repo else None, repo_line=repo[1] if repo else None,
|
||||
)
|
||||
opened: tuple[str, int] | None = None
|
||||
tag: str | None = None
|
||||
for number, line in enumerate(lines, 1):
|
||||
# A generated script may define functions of its own.
|
||||
if tag is not None:
|
||||
if line.strip() == tag:
|
||||
tag = None
|
||||
continue
|
||||
heredoc = _HEREDOC.search(line)
|
||||
if heredoc is not None:
|
||||
tag = heredoc.group(1)
|
||||
header = FUNCTION.match(line)
|
||||
if header is not None:
|
||||
opened = (header.group(1), number)
|
||||
elif opened is not None and line.rstrip() == "}":
|
||||
module.functions[opened[0]] = (opened[1], number)
|
||||
opened = None
|
||||
if opened is not None:
|
||||
raise LauncherPatternMissing(path, f"function {opened[0]} has no closing brace")
|
||||
return module
|
||||
|
||||
def echo_value(self, name: str) -> str | None:
|
||||
"""What a function whose whole body is one `echo "X"` prints."""
|
||||
module = self.owner.get(name)
|
||||
if module is None:
|
||||
return None
|
||||
start, end = module.functions[name]
|
||||
body = [line.strip() for line in module.lines[start:end - 1] if line.strip()]
|
||||
if len(body) == 1:
|
||||
words = split(body[0])
|
||||
if len(words) == 2 and words[0] == "echo":
|
||||
return words[1]
|
||||
return None
|
||||
|
||||
def walk(self, package: Module) -> list[Event]:
|
||||
"""Every statement of a package's functions, as RetroPie runs them for it."""
|
||||
if package.id not in self._walked:
|
||||
events: dict[tuple[str, int], Event] = {}
|
||||
for name in package.functions:
|
||||
self._walk(package, name, {}, [], set(), events)
|
||||
self._walked[package.id] = sorted(
|
||||
events.values(), key=lambda e: (e.path != package.path, e.path, e.line)
|
||||
)
|
||||
return self._walked[package.id]
|
||||
|
||||
def _walk(
|
||||
self,
|
||||
package: Module,
|
||||
name: str,
|
||||
args: dict[str, list[str]],
|
||||
conditions: list[str],
|
||||
stack: set[str],
|
||||
events: dict[tuple[str, int], Event],
|
||||
) -> None:
|
||||
if name in stack:
|
||||
return
|
||||
module = self.owner[name]
|
||||
start, end = module.functions[name]
|
||||
env: dict[str, list[str]] = dict(args)
|
||||
loops: list[tuple[str | None, list[str] | None]] = []
|
||||
branches: list[tuple[str, bool | None]] = []
|
||||
array: tuple[str, list[str]] | None = None
|
||||
for number, text, opener in _logical_lines(module.lines, start + 1, end - 1):
|
||||
stripped = text.strip()
|
||||
if array is not None:
|
||||
if self._array_line(array, stripped, package, env):
|
||||
array = None
|
||||
continue
|
||||
if opener is not None:
|
||||
if self._live(branches):
|
||||
events.setdefault((module.path, number), Event(
|
||||
module.path, number, self._expand_all(stripped.split(), package, env),
|
||||
stripped, conditions + self._shown(branches, package, env), True,
|
||||
self._expand_all(split(opener), package, env),
|
||||
))
|
||||
continue
|
||||
if not stripped or stripped.startswith("#"):
|
||||
continue
|
||||
if self._branch(stripped, package, env, branches):
|
||||
continue
|
||||
if not self._live(branches):
|
||||
continue
|
||||
if self._loop(stripped, package, env, loops):
|
||||
continue
|
||||
if stripped in ("do", "then", "else", "fi", "esac", "{", "}"):
|
||||
continue
|
||||
guarded = self._guard(
|
||||
stripped, package, env, conditions + self._shown(branches, package, env)
|
||||
)
|
||||
if guarded is None:
|
||||
continue
|
||||
stripped, shown = guarded
|
||||
opens = re.match(r"^(?:local\s+)?([A-Za-z_]\w*)=\(([^)]*)$", stripped)
|
||||
if opens is not None:
|
||||
array = (opens.group(1), [opens.group(2)])
|
||||
continue
|
||||
if self._bind(stripped, package, env):
|
||||
continue
|
||||
words = [self.expand(w, package, env) for w in split(stripped)]
|
||||
# The first walk to reach a line is the one with its caller's arguments.
|
||||
events.setdefault(
|
||||
(module.path, number), Event(module.path, number, words, stripped, shown, False)
|
||||
)
|
||||
self._descend(package, name, words, shown, stack, events)
|
||||
|
||||
def _descend(
|
||||
self,
|
||||
package: Module,
|
||||
name: str,
|
||||
words: list[list[str]],
|
||||
shown: list[str],
|
||||
stack: set[str],
|
||||
events: dict[tuple[str, int], Event],
|
||||
) -> None:
|
||||
"""Walk the function a statement calls, with the words it passes."""
|
||||
callee = words[0][0] if words and words[0] else None
|
||||
if callee in self.owner and callee != name:
|
||||
call_args = {str(i): w for i, w in enumerate(words[1:], 1)}
|
||||
self._walk(package, callee, call_args, shown, stack | {name}, events)
|
||||
|
||||
def _expand_all(
|
||||
self, words: list[str], package: Module, env: dict[str, list[str]]
|
||||
) -> list[list[str]]:
|
||||
return [self.expand(w, package, env) for w in words]
|
||||
|
||||
def _array_line(
|
||||
self, array: tuple[str, list[str]], stripped: str, package: Module,
|
||||
env: dict[str, list[str]],
|
||||
) -> bool:
|
||||
"""Add one line to a multi-line array, and say whether it closed it."""
|
||||
body = re.sub(r"\s+#.*$", "", stripped)
|
||||
closed = body.endswith(")")
|
||||
array[1].append(body[:-1] if closed else body)
|
||||
if closed:
|
||||
words = split(" ".join(array[1]))
|
||||
env[array[0]] = [v for w in words for v in self.expand(w, package, env)]
|
||||
return closed
|
||||
|
||||
def _loop(
|
||||
self, stripped: str, package: Module, env: dict[str, list[str]],
|
||||
loops: list[tuple[str | None, list[str] | None]],
|
||||
) -> bool:
|
||||
"""Track for/while/until/done, and say whether the line was one of them."""
|
||||
loop = _FOR.match(stripped)
|
||||
if loop is not None:
|
||||
values = [v for w in split(loop.group(2)) for v in self.expand(w, package, env)]
|
||||
loops.append((loop.group(1), env.get(loop.group(1))))
|
||||
env[loop.group(1)] = values
|
||||
return True
|
||||
if re.match(r"^(while|until)\b|^for\s*\(\(", stripped):
|
||||
loops.append((None, None))
|
||||
return True
|
||||
if stripped == "done" or stripped.startswith(("done ", "done;")):
|
||||
if loops:
|
||||
var, previous = loops.pop()
|
||||
if var is not None:
|
||||
if previous is None:
|
||||
env.pop(var, None)
|
||||
else:
|
||||
env[var] = previous
|
||||
return True
|
||||
return False
|
||||
|
||||
def _guard(
|
||||
self, stripped: str, package: Module, env: dict[str, list[str]], shown: list[str]
|
||||
) -> tuple[str, list[str]] | None:
|
||||
"""The statement a `[[ test ]] && statement` runs and its conditions, None if never."""
|
||||
guard = re.match(r"^\[\[\s*(.*?)\s*\]\]\s*&&\s*(.*)$", stripped)
|
||||
if guard is None:
|
||||
return stripped, shown
|
||||
verdict = self._md_id_test(f"[[ {guard.group(1)} ]]", package)
|
||||
if verdict is False or "$md_mode" in guard.group(1) or "$mode" in guard.group(1):
|
||||
return None
|
||||
if verdict is None:
|
||||
shown = shown + [self._render(guard.group(1), package, env)]
|
||||
return guard.group(2), shown
|
||||
|
||||
def _branch(
|
||||
self, stripped: str, package: Module, env: dict[str, list[str]],
|
||||
branches: list[tuple[str, bool | None]],
|
||||
) -> bool:
|
||||
"""Track if/elif/else/fi, and say whether the line was one of them."""
|
||||
opened = re.match(r"^(if|elif)\s+(.*?)\s*(?:;\s*then)?\s*$", stripped)
|
||||
if opened is not None:
|
||||
condition = opened.group(2)
|
||||
verdict = self._md_id_test(condition, package)
|
||||
if "$md_mode" in condition or "$mode" in condition:
|
||||
verdict = True if "install" in condition else None
|
||||
if opened.group(1) == "if":
|
||||
branches.append((condition, verdict))
|
||||
elif branches:
|
||||
previous, previous_verdict = branches[-1]
|
||||
if previous_verdict is True:
|
||||
verdict = False
|
||||
branches[-1] = (condition, verdict)
|
||||
return True
|
||||
if stripped == "else" and branches:
|
||||
condition, verdict = branches[-1]
|
||||
branches[-1] = (f"not ({condition})", None if verdict is None else not verdict)
|
||||
return True
|
||||
if stripped == "fi" or stripped.startswith("fi "):
|
||||
if branches:
|
||||
branches.pop()
|
||||
return True
|
||||
return False
|
||||
|
||||
@staticmethod
|
||||
def _live(branches: list[tuple[str, bool | None]]) -> bool:
|
||||
return all(verdict is not False for _c, verdict in branches)
|
||||
|
||||
def _shown(
|
||||
self, branches: list[tuple[str, bool | None]], package: Module, env: dict[str, list[str]]
|
||||
) -> list[str]:
|
||||
return [
|
||||
self._render(condition, package, env)
|
||||
for condition, verdict in branches if verdict is None
|
||||
]
|
||||
|
||||
def _render(self, condition: str, package: Module, env: dict[str, list[str]]) -> str:
|
||||
"""A condition with its variables filled in when each takes one value."""
|
||||
values = self.expand(condition, package, env)
|
||||
return values[0] if len(values) == 1 else condition
|
||||
|
||||
@staticmethod
|
||||
def _md_id_test(condition: str, package: Module) -> bool | None:
|
||||
test = _MD_ID_TEST.match(condition.strip())
|
||||
if test is None:
|
||||
return None
|
||||
equal = package.id == test.group(2)
|
||||
return equal if test.group(1) == "==" else not equal
|
||||
|
||||
def _bind(self, stripped: str, package: Module, env: dict[str, list[str]]) -> bool:
|
||||
"""Record a variable assignment, and say whether the line was one."""
|
||||
if _DECLARE.match(stripped):
|
||||
return True
|
||||
assign = _ASSIGN.match(stripped)
|
||||
if assign is None:
|
||||
return False
|
||||
name, value = assign.group(1), assign.group(2).strip()
|
||||
if value.startswith("("):
|
||||
closing = value.rfind(")")
|
||||
inner = value[1:closing] if closing > 0 else value[1:]
|
||||
env[name] = [v for w in split(inner) for v in self.expand(w, package, env)]
|
||||
return True
|
||||
words = split(value) or [""]
|
||||
if "$(" in words[0] and _SUBST.fullmatch(words[0]) is None:
|
||||
# A command's output: the variable stays a reference.
|
||||
env.pop(name, None)
|
||||
return True
|
||||
expanded = self.expand(words[0], package, env)
|
||||
if any("$(" in v for v in expanded):
|
||||
env.pop(name, None)
|
||||
else:
|
||||
env[name] = expanded
|
||||
return True
|
||||
|
||||
def expand(self, word: str, package: Module, env: dict[str, list[str]]) -> list[str]:
|
||||
"""Every value a word takes: braces, $md_id, bound variables, $(echo functions)."""
|
||||
word = re.sub(r"\$\{md_id\}|\$md_id\b", package.id, word)
|
||||
|
||||
def substitute(found: re.Match[str]) -> str:
|
||||
printed = self.echo_value(found.group(1))
|
||||
return printed if printed is not None else found.group(0)
|
||||
|
||||
word = _SUBST.sub(substitute, word)
|
||||
results: list[str] = []
|
||||
for braced in _brace(word):
|
||||
names = [m.group(1) or m.group(3) for m in VAR.finditer(braced)]
|
||||
bound = [n for n in names if n in env]
|
||||
if not bound:
|
||||
results.append(braced)
|
||||
continue
|
||||
results.extend(
|
||||
VAR.sub(partial(_bound_value, dict(zip(bound, values))), braced)
|
||||
for values in product(*(env[n] for n in bound))
|
||||
)
|
||||
return results
|
||||
|
||||
|
||||
def _bound_value(chosen: dict[str, str], found: re.Match[str]) -> str:
|
||||
key = found.group(1) or found.group(3)
|
||||
return chosen.get(key, found.group(0))
|
||||
|
||||
|
||||
def merge_records(records: list[Launcher]) -> list[Launcher]:
|
||||
"""Records equal but for their lines become one, citing every line."""
|
||||
merged: dict[tuple[Any, ...], Launcher] = {}
|
||||
for record in records:
|
||||
entry = record.entry()
|
||||
entry.pop("source_ref")
|
||||
key = tuple((k, repr(v)) for k, v in entry.items())
|
||||
if key in merged:
|
||||
kept = merged[key]
|
||||
kept.lines += record.lines
|
||||
kept.source_ref = source_ref(kept.lines)
|
||||
else:
|
||||
merged[key] = record
|
||||
return list(merged.values())
|
||||
|
||||
|
||||
def source_ref(lines: list[tuple[str, int]]) -> str:
|
||||
"""`path:a-b, c` per file, in first-seen file order, adjacent lines joined."""
|
||||
# Not shell.merge_lines: joining across a one-line gap would turn
|
||||
# the committed lr-prboom.sh:86, 88 of four retropie.yml records into 86-88.
|
||||
by_path: dict[str, list[int]] = {}
|
||||
for path, number in lines:
|
||||
by_path.setdefault(path, []).append(number)
|
||||
parts = []
|
||||
for path, numbers in by_path.items():
|
||||
ranges: list[list[int]] = []
|
||||
for number in sorted(set(numbers)):
|
||||
if ranges and number == ranges[-1][1] + 1:
|
||||
ranges[-1][1] = number
|
||||
else:
|
||||
ranges.append([number, number])
|
||||
spans = ", ".join(str(a) if a == b else f"{a}-{b}" for a, b in ranges)
|
||||
parts.append(f"{path}:{spans}")
|
||||
return ", ".join(parts)
|
||||
@@ -0,0 +1,587 @@
|
||||
"""ROCKNIX's launcher layer, read from its packages at the pinned tag.
|
||||
|
||||
ROCKNIX starts each standalone emulator from a shell script and installs a
|
||||
config with the package. Between a file in /storage/roms/bios and the
|
||||
emulator, the config names the path (melonDS, xemu, mednafen), the script
|
||||
searches or links (yabasanshiro, drastic, dolphin), or the emulator is
|
||||
handed a directory and left to choose (DuckStation, AetherSX2). Several
|
||||
packages ship one config per device: a record carries `device` only where
|
||||
the value read differs between them.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import posixpath
|
||||
import re
|
||||
from collections.abc import Callable
|
||||
|
||||
from .configgen import Launcher
|
||||
from scraper.launchers.shell import (
|
||||
describe_keys,
|
||||
LauncherPatternMissing,
|
||||
Link,
|
||||
link_record,
|
||||
RepoTree,
|
||||
Script,
|
||||
fixed_paths,
|
||||
Setting,
|
||||
settings,
|
||||
source_ref,
|
||||
)
|
||||
from .rocknix_configs import (
|
||||
BIOS_ROOT,
|
||||
CONFIG_ROOT,
|
||||
Installed,
|
||||
RETROARCH,
|
||||
STANDALONE,
|
||||
file_under,
|
||||
fixed_path_keys,
|
||||
config_records,
|
||||
device_configs,
|
||||
directory_records,
|
||||
per_device,
|
||||
with_evidence,
|
||||
)
|
||||
|
||||
|
||||
def retroarch(tree: RepoTree) -> list[Launcher]:
|
||||
"""system_directory of the retroarch.cfg each device installs."""
|
||||
configs = device_configs(tree, RETROARCH, "retroarch.cfg", folder="sources")
|
||||
wanted = ("system_directory", "systemfiles_in_content_dir")
|
||||
|
||||
def read(path: str, text: str) -> tuple[tuple[tuple[str, str], ...], set[int]]:
|
||||
found = {s.key: s for s in settings(text) if s.key in wanted}
|
||||
if "system_directory" not in found:
|
||||
raise LauncherPatternMissing(path, "system_directory")
|
||||
return tuple((k, found[k].value) for k in wanted if k in found), {
|
||||
s.line for s in found.values()
|
||||
}
|
||||
|
||||
records = []
|
||||
for device, value, refs in per_device(tree, configs, f"{RETROARCH}/package.mk", read):
|
||||
assert isinstance(value, tuple)
|
||||
values = dict(value)
|
||||
records.append(with_evidence(
|
||||
tree,
|
||||
Launcher(
|
||||
emulator="retroarch",
|
||||
build="libretro",
|
||||
kind="passes_path",
|
||||
names=[],
|
||||
source_ref=source_ref(refs),
|
||||
search_dir=values["system_directory"],
|
||||
passes_to="retroarch.cfg " + ", ".join(f'{k} = "{v}"' for k, v in value),
|
||||
device=device,
|
||||
),
|
||||
f"{CONFIG_ROOT}/retroarch/retroarch.cfg",
|
||||
[k for k, _ in value],
|
||||
))
|
||||
return records
|
||||
|
||||
|
||||
def amiberry(tree: RepoTree) -> list[Launcher]:
|
||||
"""The A500 or A1200 config, chosen by the game name, then the kickstarts link."""
|
||||
package = f"{STANDALONE}/amiberry"
|
||||
script = Script(
|
||||
f"{package}/scripts/start_amiberry.sh", tree.read(f"{package}/scripts/start_amiberry.sh")
|
||||
)
|
||||
test_line, test = script.find(r"grep -E '([^']+)'", "machine choice by game name")
|
||||
then_line, then = script.find(
|
||||
r"cp \S+/(\w+-default\.uae)", "config copied for a match", test_line
|
||||
)
|
||||
else_line, _ = script.find(r"^\s*else\b", "else of the machine choice", then_line)
|
||||
other_line, other = script.find(
|
||||
r"cp \S+/(\w+-default\.uae)", "config copied otherwise", else_line
|
||||
)
|
||||
sed_line, sed = script.find(
|
||||
r'sed -i "s#(@\w+@)#\$\{(\w+)\}#g"', "placeholder substitution", other_line
|
||||
)
|
||||
used: set[int] = {test_line, then_line, else_line, other_line, sed_line}
|
||||
root = script.expand("${" + sed.group(2) + "}", sed_line, used)
|
||||
written = re.search(r'"?(\$\{?\w+\}?)"?\s*$', script.lines[then_line - 1])
|
||||
if written is None:
|
||||
raise script.missing("destination of the config copy")
|
||||
target = script.expand(written.group(1), then_line, set())
|
||||
# A WHDLoad archive is booted by --autoload, which builds its own setup
|
||||
# (kickstart included) over the config: the record holds for floppies.
|
||||
autoload = [n for n, line in script.code() if re.search(r"amiberry .*--autoload", line)]
|
||||
if not autoload:
|
||||
raise script.missing("WHDLoad boot with --autoload")
|
||||
content = (
|
||||
"content not booted with --autoload, a WHDLoad .lha or .zip "
|
||||
f"({posixpath.basename(script.path)}:{', '.join(map(str, autoload))})"
|
||||
)
|
||||
records = []
|
||||
for config, condition in (
|
||||
(then.group(1), f"game name matches {test.group(1)}"),
|
||||
(other.group(1), f"game name does not match {test.group(1)}"),
|
||||
):
|
||||
path = f"{package}/config/conf/{config}"
|
||||
found = [
|
||||
Setting(s.section, s.key, s.value.replace(sed.group(1), root), s.line)
|
||||
for s in settings(tree.read(path))
|
||||
]
|
||||
keys = [(s.section, s.key) for s in found if file_under(s.value, root)]
|
||||
if not keys:
|
||||
raise LauncherPatternMissing(path, f"key naming a file under {sed.group(1)}")
|
||||
value, lines = fixed_paths(found, keys, path)
|
||||
slot = re.fullmatch(r"Amiga(\w+)-default\.uae", config)
|
||||
records.append(with_evidence(
|
||||
tree,
|
||||
Launcher(
|
||||
emulator="amiberry",
|
||||
build="standalone",
|
||||
kind="fixed_name",
|
||||
names=list(value.names),
|
||||
source_ref=source_ref([(script.path, used), (path, lines)]),
|
||||
slot=slot.group(1) if slot else config,
|
||||
search_dir=value.search_dir,
|
||||
passes_to=f"{describe_keys(config, value.keys)} (amiberry -f)",
|
||||
depends_on_option=f"{condition}, {content}",
|
||||
),
|
||||
target,
|
||||
fixed_path_keys(value),
|
||||
script,
|
||||
source_name=config,
|
||||
))
|
||||
mk = Script(f"{package}/package.mk", tree.read(f"{package}/package.mk"))
|
||||
links = mk.links(BIOS_ROOT, fixed={"INSTALL": ""})
|
||||
if not links:
|
||||
raise mk.missing(f"ln -s of {BIOS_ROOT}")
|
||||
records.extend(link_record("amiberry", mk, link) for link in links)
|
||||
# The script copies the installed folder, links included, to the one it
|
||||
# enters before it runs amiberry: the kickstarts link is read there.
|
||||
copy_line, copy = script.find(r"cp -rf? (\S+) \$\{?(\w+)\}?\s*$", "copy of the installed folder")
|
||||
cd_line, cd = script.find(r"^\s*cd \$\{?(\w+)\}?\s*$", "working directory")
|
||||
if cd.group(1) != copy.group(2):
|
||||
raise LauncherPatternMissing(script.path, "cd into the copied folder")
|
||||
entered: set[int] = {cd_line}
|
||||
folder = script.expand("${" + cd.group(1) + "}", cd_line, entered)
|
||||
records.append(Launcher(
|
||||
emulator="amiberry", build="standalone", kind="passes_path", names=[],
|
||||
source_ref=source_ref([(script.path, entered)]),
|
||||
search_dir=folder, passes_to=f"working directory of {script.path.rsplit('/', 1)[-1]}",
|
||||
))
|
||||
installed = copy.group(1).rstrip("/")
|
||||
for link in links:
|
||||
if not link.link.startswith(installed + "/"):
|
||||
continue
|
||||
copied = folder + link.link[len(installed):]
|
||||
records.append(Launcher(
|
||||
emulator="amiberry", build="standalone", kind="links", names=list(link.names),
|
||||
source_ref=source_ref([(mk.path, link.lines), (script.path, {copy_line} | entered)]),
|
||||
search_dir=link.bios_side,
|
||||
passes_to=f"symlink {copied} -> {link.target}, copied with {installed}",
|
||||
))
|
||||
return records
|
||||
|
||||
|
||||
def hatari(tree: RepoTree) -> list[Launcher]:
|
||||
package = f"{STANDALONE}/hatarisa"
|
||||
# The script is named after the package's binary: start_hatari.sh became
|
||||
# start_hatarisa.sh (2e7041d273), so it is found, not spelled.
|
||||
starts = sorted(
|
||||
name for name in tree.listdir(f"{package}/scripts")
|
||||
if name.startswith("start_") and name.endswith(".sh")
|
||||
)
|
||||
if len(starts) != 1:
|
||||
raise LauncherPatternMissing(f"{package}/scripts", "one start script")
|
||||
script = Script(f"{package}/scripts/{starts[0]}", tree.read(f"{package}/scripts/{starts[0]}"))
|
||||
copy_line, copy = script.find(r"cp \S+/([\w-]+\.cfg) ", "default config copy")
|
||||
run_line, _ = script.find(r"--configfile", "--configfile", copy_line)
|
||||
path = f"{package}/config/conf/{copy.group(1)}"
|
||||
found = settings(tree.read(path))
|
||||
keys = [(s.section, s.key) for s in found if file_under(s.value, BIOS_ROOT)]
|
||||
if not keys:
|
||||
raise LauncherPatternMissing(path, f"key naming a file under {BIOS_ROOT}")
|
||||
value, lines = fixed_paths(found, keys, path)
|
||||
copied = re.search(r'"?(\$\{?\w+\}?)"?\s*$', script.lines[copy_line - 1])
|
||||
if copied is None:
|
||||
raise script.missing("destination of the default config copy")
|
||||
return [with_evidence(
|
||||
tree,
|
||||
Launcher(
|
||||
emulator="hatari",
|
||||
build="standalone",
|
||||
kind="fixed_name",
|
||||
names=list(value.names),
|
||||
source_ref=source_ref([(path, lines), (script.path, {copy_line, run_line})]),
|
||||
search_dir=value.search_dir,
|
||||
passes_to=f"{describe_keys(copy.group(1), value.keys)} (--configfile)",
|
||||
),
|
||||
script.expand(copied.group(1), copy_line, set()),
|
||||
fixed_path_keys(value),
|
||||
script,
|
||||
source_name=copy.group(1),
|
||||
)]
|
||||
|
||||
|
||||
def melonds(tree: RepoTree) -> list[Launcher]:
|
||||
package = f"{STANDALONE}/melonds-sa"
|
||||
script = Script(
|
||||
f"{package}/scripts/start_melonds.sh", tree.read(f"{package}/scripts/start_melonds.sh")
|
||||
)
|
||||
enable_line, _ = script.find(r"ExternalBIOSEnable=1", "ExternalBIOSEnable=1")
|
||||
tests = [
|
||||
(number, found)
|
||||
for number, line in script.code()
|
||||
if number < enable_line and (found := re.search(r'if \[ "\$(\w+)" = "(\w+)" \]', line))
|
||||
]
|
||||
if not tests:
|
||||
raise script.missing("test that enables the external BIOS")
|
||||
test_line, test = tests[-1]
|
||||
setting_line, setting = script.find(
|
||||
rf"^\s*{test.group(1)}=\$\(get_setting (\w+) ", f"setting read into {test.group(1)}"
|
||||
)
|
||||
condition = f"{setting.group(1)} = {test.group(2)} sets ExternalBIOSEnable=1, otherwise 0"
|
||||
configs = [c.path for c in device_configs(tree, package, "melonDS.ini")]
|
||||
# melonDS opens the DSi BIOS and firmware keys only under
|
||||
# DSiExternalBIOSEnable, off unless a config sets it.
|
||||
dsi_external = any(
|
||||
s.key == "DSiExternalBIOSEnable" and s.value not in ("", "0")
|
||||
for path in configs for s in settings(tree.read(path))
|
||||
)
|
||||
|
||||
def unread(key: tuple[str, str]) -> bool:
|
||||
return not dsi_external and key[1] in ("DSiBIOS9Path", "DSiBIOS7Path", "DSiFirmwarePath")
|
||||
|
||||
conf_line, conf = script.find(r'^\s*CONF_DIR="([^"]+)"', "CONF_DIR")
|
||||
records = config_records(
|
||||
tree, "melonds", package, "melonDS.ini", depends_on_option=condition,
|
||||
installed=Installed(f"{conf.group(1)}/melonDS.ini", script), unread=unread,
|
||||
)
|
||||
for record in records:
|
||||
record.source_ref += (
|
||||
f", {source_ref([(script.path, {setting_line, test_line, enable_line})])}"
|
||||
)
|
||||
return records
|
||||
|
||||
|
||||
def dsperate(tree: RepoTree) -> list[Launcher]:
|
||||
package = f"{STANDALONE}/dsperate-sa"
|
||||
script = Script(
|
||||
f"{package}/scripts/start_dsperate.sh", tree.read(f"{package}/scripts/start_dsperate.sh")
|
||||
)
|
||||
run_line, _ = script.find(r"/usr/bin/dsperate --config ", "dsperate --config")
|
||||
records = config_records(
|
||||
tree, "dsperate", package, "dsperate.ini", " (--config)",
|
||||
installed=Installed(script.expand("${DSPERATE_INI}", run_line, set()), script),
|
||||
)
|
||||
for record in records:
|
||||
record.source_ref += f", {source_ref([(script.path, {run_line})])}"
|
||||
return records
|
||||
|
||||
|
||||
def xemu(tree: RepoTree) -> list[Launcher]:
|
||||
package = f"{STANDALONE}/xemu-sa"
|
||||
script = Script(
|
||||
f"{package}/scripts/start_xemu.sh", tree.read(f"{package}/scripts/start_xemu.sh")
|
||||
)
|
||||
copy_line, _ = script.find(
|
||||
r'cp -r "\$\{SOURCE_DIR\}/\$\{XEMU_INI\}"', "xemu.toml copy at launch"
|
||||
)
|
||||
records = config_records(
|
||||
tree, "xemu", package, "xemu.toml", " (copied at each launch)",
|
||||
installed=Installed(script.expand("${CONF_DIR}/${XEMU_INI}", copy_line, set()), script),
|
||||
)
|
||||
for record in records:
|
||||
record.source_ref += f", {source_ref([(script.path, {copy_line})])}"
|
||||
return records
|
||||
|
||||
|
||||
def nanoboyadvance(tree: RepoTree) -> list[Launcher]:
|
||||
package = f"{STANDALONE}/nanoboyadvance-sa"
|
||||
path = f"{package}/config/config.toml"
|
||||
found = settings(tree.read(path))
|
||||
keys = [(s.section, s.key) for s in found if file_under(s.value, BIOS_ROOT)]
|
||||
if not keys:
|
||||
raise LauncherPatternMissing(path, f"key naming a file under {BIOS_ROOT}")
|
||||
value, lines = fixed_paths(found, keys, path)
|
||||
mk_path = f"{package}/package.mk"
|
||||
mk_line, _ = Script(mk_path, tree.read(mk_path)).find(
|
||||
r"config/config\.toml", "config.toml install"
|
||||
)
|
||||
start_path = f"{package}/scripts/start_nanoboyadvance.sh"
|
||||
return [with_evidence(
|
||||
tree,
|
||||
Launcher(
|
||||
emulator="nanoboyadvance",
|
||||
build="standalone",
|
||||
kind="fixed_name",
|
||||
names=list(value.names),
|
||||
source_ref=source_ref([(path, lines), (mk_path, {mk_line})]),
|
||||
search_dir=value.search_dir,
|
||||
passes_to=describe_keys("config.toml", value.keys),
|
||||
# NanoBoyAdvance exits when its BIOS cannot be read
|
||||
# (src/platform/sdl/main.cpp:180-185 at the build ROCKNIX ships).
|
||||
fails_when_missing=True,
|
||||
),
|
||||
f"{CONFIG_ROOT}/nanoboyadvance/config.toml",
|
||||
fixed_path_keys(value),
|
||||
Script(start_path, tree.read(start_path)),
|
||||
)]
|
||||
|
||||
|
||||
def mednafen(tree: RepoTree) -> list[Launcher]:
|
||||
"""The firmware keys of mednafen.template, one record per module."""
|
||||
package = f"{STANDALONE}/mednafen"
|
||||
path = f"{package}/config/common/mednafen.template"
|
||||
found = settings(tree.read(path), separator=" ")
|
||||
folder = next((s for s in found if s.key == "filesys.path_firmware"), None)
|
||||
if folder is None:
|
||||
raise LauncherPatternMissing(path, "filesys.path_firmware")
|
||||
pattern = re.compile(r"(\w+)\.(\w*bios\w*|ggrom|cart\.\w+_path)")
|
||||
firmware = [s for s in found if pattern.fullmatch(s.key) and s.value and not s.value.isdigit()]
|
||||
if not firmware:
|
||||
raise LauncherPatternMissing(path, "firmware keys")
|
||||
script_path = f"{package}/scripts/start_mednafen.sh"
|
||||
script = Script(script_path, tree.read(script_path))
|
||||
gen_line, _ = script.find(r"mednafen_gen_config\.sh", "config generation")
|
||||
test_line, _ = script.find(
|
||||
r'if \[ ! -f "\$MEDNAFEN_HOME/mednafen\.cfg" \]', "mednafen.cfg test"
|
||||
)
|
||||
modules: dict[str, list[Setting]] = {}
|
||||
for setting in firmware:
|
||||
modules.setdefault(setting.key.split(".", 1)[0], []).append(setting)
|
||||
home = script.expand("${MEDNAFEN_HOME}", gen_line, set())
|
||||
return [with_evidence(
|
||||
tree,
|
||||
Launcher(
|
||||
emulator="mednafen",
|
||||
build="standalone",
|
||||
kind="fixed_name",
|
||||
names=list(dict.fromkeys(s.value for s in group)),
|
||||
source_ref=source_ref(
|
||||
[
|
||||
(path, {folder.line, *(s.line for s in group)}),
|
||||
(script_path, {test_line, gen_line}),
|
||||
]
|
||||
),
|
||||
slot=module,
|
||||
search_dir=folder.value,
|
||||
passes_to="mednafen.cfg " + ", ".join(s.key for s in group),
|
||||
),
|
||||
f"{home}/mednafen.cfg",
|
||||
[s.key for s in group],
|
||||
script,
|
||||
writers=("mednafen_gen_config.sh",),
|
||||
) for module, group in modules.items()]
|
||||
|
||||
|
||||
def yabasanshiro(tree: RepoTree) -> list[Launcher]:
|
||||
package = f"{STANDALONE}/yabasanshiro-sa"
|
||||
script = Script(
|
||||
f"{package}/scripts/start_yabasanshiro.sh",
|
||||
tree.read(f"{package}/scripts/start_yabasanshiro.sh"),
|
||||
)
|
||||
option_line, option = script.find(r"=\$\(get_setting (\w+) ", "BIOS option")
|
||||
test_line, test = script.find(r'if \[ "\$\w+" = (\w+) \]', "BIOS option test", option_line)
|
||||
loop = next((lp for lp in script.loops() if lp.start > test_line), None)
|
||||
if loop is None:
|
||||
raise script.missing("loop over BIOS names")
|
||||
find_line, find = script.find(
|
||||
rf"\$\(find (\S+) -name \$\{{{loop.var}\}}", "find of each name", loop.start, loop.end
|
||||
)
|
||||
flag_line, flag = script.find(
|
||||
r'="(-\w) \$\{\w+\}"', "flag the found path is passed with", find_line, loop.end
|
||||
)
|
||||
break_line, _ = script.find(r"^\s*break\b", "break on the first found", flag_line, loop.end)
|
||||
return [
|
||||
Launcher(
|
||||
emulator="yabasanshiro",
|
||||
build="standalone",
|
||||
kind="names_searched",
|
||||
names=loop.items,
|
||||
source_ref=source_ref(
|
||||
[(script.path, {option_line, test_line, *range(loop.start, loop.end + 1)})]
|
||||
),
|
||||
case_insensitive=False,
|
||||
search_dir=f"{find.group(1)} (recursive)",
|
||||
passes_to=f"yabasanshiro {flag.group(1)} <first path found>",
|
||||
fails_when_missing=False,
|
||||
depends_on_option=f"{option.group(1)} = {test.group(1)} (game, then platform)",
|
||||
)
|
||||
]
|
||||
|
||||
|
||||
def duckstation(tree: RepoTree) -> list[Launcher]:
|
||||
return directory_records(
|
||||
tree,
|
||||
"duckstation",
|
||||
f"{STANDALONE}/duckstation-sa",
|
||||
"settings.ini",
|
||||
("BIOS", "SearchDirectory"),
|
||||
(("BIOS", "PathNTSCU"), ("BIOS", "PathNTSCJ"), ("BIOS", "PathPAL")),
|
||||
f"{CONFIG_ROOT}/duckstation/settings.ini",
|
||||
f"{STANDALONE}/duckstation-sa/scripts/start_duckstation.sh",
|
||||
)
|
||||
|
||||
|
||||
def armsx2(tree: RepoTree) -> list[Launcher]:
|
||||
return directory_records(
|
||||
tree,
|
||||
"armsx2",
|
||||
f"{STANDALONE}/armsx2-sa",
|
||||
"ARMSX2/inis/PCSX2.ini",
|
||||
("Folders", "Bios"),
|
||||
(("Filenames", "BIOS"),),
|
||||
f"{CONFIG_ROOT}/ARMSX2/inis/PCSX2.ini",
|
||||
f"{STANDALONE}/armsx2-sa/scripts/start_armsx2.sh",
|
||||
)
|
||||
|
||||
|
||||
# Start scripts whose ln -s commands put a BIOS path where the emulator reads.
|
||||
def pico8(tree: RepoTree) -> list[Launcher]:
|
||||
"""The PICO-8 binary start_pico8.sh executes, outside /storage/roms/bios.
|
||||
|
||||
The script picks the binary by HW_ARCH, pico8_64 on aarch64 and
|
||||
pico8_dyn on any other, and runs it from GAME_DIR, or from
|
||||
GAME_DIR/${HW_ARCH} when that folder exists.
|
||||
"""
|
||||
path = f"{STANDALONE}/pico-8/scripts/start_pico8.sh"
|
||||
script = Script(path, tree.read(path))
|
||||
game_line, game = script.find(r'^\s*GAME_DIR="([^"$]+)"', "GAME_DIR assignment")
|
||||
case_line, _ = script.find(r"^\s*case \$\{HW_ARCH\} in", "case on HW_ARCH")
|
||||
arch_line, arch = script.find(r"^\s*(\w+)\)", "HW_ARCH branch", case_line + 1)
|
||||
first_line, first = script.find(r'STATIC_BIN="([^"$]+)"', "binary of the first branch", arch_line)
|
||||
other_line, _ = script.find(r"^\s*\*\)", "default HW_ARCH branch", first_line)
|
||||
rest_line, rest = script.find(r'STATIC_BIN="([^"$]+)"', "binary of the default branch", other_line)
|
||||
sub_line, _ = script.find(
|
||||
r'if \[ -d "\$\{GAME_DIR\}/\$\{HW_ARCH\}" \]', "per-architecture launch folder"
|
||||
)
|
||||
end_line, _ = script.find(r"^\s*fi\b", "end of the launch folder test", sub_line)
|
||||
run_line, _ = script.find(r"^\s*\$\{LAUNCH_DIR\}/\$\{STATIC_BIN\} ", "binary run")
|
||||
return [
|
||||
Launcher(
|
||||
emulator="pico-8",
|
||||
build="standalone",
|
||||
kind="fixed_name",
|
||||
names=[first.group(1), rest.group(1)],
|
||||
source_ref=source_ref([(path, {
|
||||
game_line, case_line, arch_line, first_line, other_line, rest_line,
|
||||
*range(sub_line, end_line + 1), run_line,
|
||||
})]),
|
||||
search_dir=game.group(1).rstrip("/"),
|
||||
passes_to="exec",
|
||||
fails_when_missing=False,
|
||||
depends_on_option=(
|
||||
f"HW_ARCH {arch.group(1)} runs {first.group(1)}, any other {rest.group(1)}, "
|
||||
f"from {game.group(1).rstrip('/')}/${{HW_ARCH}} when that folder exists"
|
||||
),
|
||||
)
|
||||
]
|
||||
|
||||
|
||||
LINK_SCRIPTS = (
|
||||
("drastic", f"{STANDALONE}/drastic-sa/scripts/start_drastic.sh"),
|
||||
("dolphin", f"{STANDALONE}/dolphin-sa/scripts/start_dolphin_gc.sh"),
|
||||
("flycast", f"{STANDALONE}/flycast-sa/scripts/start_flycast.sh"),
|
||||
("cemu", f"{STANDALONE}/cemu-sa/scripts/start_cemu.sh"),
|
||||
("rpcs3", f"{STANDALONE}/rpcs3-sa/scripts/start_rpcs3.sh"),
|
||||
)
|
||||
|
||||
|
||||
def links(tree: RepoTree) -> list[Launcher]:
|
||||
records = []
|
||||
for emulator, path in LINK_SCRIPTS:
|
||||
script = Script(path, tree.read(path))
|
||||
found = script.links(BIOS_ROOT)
|
||||
if not found:
|
||||
raise script.missing(f"ln -s of a path under {BIOS_ROOT}")
|
||||
for link in found:
|
||||
guard = _existence_guard(script, link)
|
||||
if guard is not None:
|
||||
link.lines.add(guard)
|
||||
records.append(
|
||||
link_record(
|
||||
emulator,
|
||||
script,
|
||||
link,
|
||||
case_insensitive=False if guard is not None else None,
|
||||
fails_when_missing=False,
|
||||
)
|
||||
)
|
||||
return records
|
||||
|
||||
|
||||
# Packages whose build patch replaces the function an emulator resolves a
|
||||
# directory with by a fixed path: ROCKNIX's Flycast returns
|
||||
# /storage/roms/dreamcast/data as its data directory, which start_flycast.sh
|
||||
# then links to the BIOS tree.
|
||||
DIRECTORY_PATCHES = (
|
||||
("flycast", f"{STANDALONE}/flycast-sa/patches/000-conf-dir.patch", "find_user_data_dir"),
|
||||
)
|
||||
|
||||
|
||||
def patched_directories(tree: RepoTree) -> list[Launcher]:
|
||||
records = []
|
||||
for emulator, path, function in DIRECTORY_PATCHES:
|
||||
lines = tree.read(path).splitlines()
|
||||
target = next(
|
||||
(line[len("+++ b/"):] for line in lines if line.startswith("+++ b/")), None
|
||||
)
|
||||
start = next(
|
||||
(n for n, line in enumerate(lines, 1) if re.search(rf"\b{function}\(\)", line)),
|
||||
None,
|
||||
)
|
||||
returned = None
|
||||
if target is not None and start is not None:
|
||||
returned = next(
|
||||
(
|
||||
(n, match.group(1))
|
||||
for n, line in enumerate(lines[start:], start + 1)
|
||||
if (match := re.match(r'^\+\s*return "(/[^"]+)";', line))
|
||||
),
|
||||
None,
|
||||
)
|
||||
if start is None or returned is None:
|
||||
raise LauncherPatternMissing(path, f"{function}() patched to return a fixed path")
|
||||
number, directory = returned
|
||||
records.append(Launcher(
|
||||
emulator=emulator,
|
||||
build="standalone",
|
||||
kind="passes_path",
|
||||
names=[],
|
||||
source_ref=source_ref([(path, {start, number})]),
|
||||
search_dir=directory.rstrip("/"),
|
||||
passes_to=f"{function}() in {target} returns it",
|
||||
fails_when_missing=False,
|
||||
))
|
||||
return records
|
||||
|
||||
|
||||
def _existence_guard(script: Script, link: Link) -> int | None:
|
||||
"""The line of a -e test of the BIOS-side path the link waits for, if any."""
|
||||
last = max(link.lines)
|
||||
tests = [
|
||||
number
|
||||
for number, line in script.code()
|
||||
if number < last
|
||||
and re.search(
|
||||
r"\[ -e \S*" + re.escape(link.bios_side) + "/", script.expand(line, number, set())
|
||||
)
|
||||
]
|
||||
return tests[-1] if tests and last - tests[-1] <= 3 else None
|
||||
|
||||
|
||||
EXTRACTORS: tuple[Callable[[RepoTree], list[Launcher]], ...] = (
|
||||
retroarch,
|
||||
amiberry,
|
||||
hatari,
|
||||
melonds,
|
||||
dsperate,
|
||||
nanoboyadvance,
|
||||
xemu,
|
||||
mednafen,
|
||||
yabasanshiro,
|
||||
duckstation,
|
||||
armsx2,
|
||||
pico8,
|
||||
patched_directories,
|
||||
links,
|
||||
)
|
||||
|
||||
|
||||
def extract_launchers(tree: RepoTree) -> list[dict]:
|
||||
"""Every launcher record the extractors find, in extractor order."""
|
||||
return [record.entry() for extractor in EXTRACTORS for record in extractor(tree)]
|
||||
@@ -0,0 +1,279 @@
|
||||
"""The configs ROCKNIX installs per device, and the records of the BIOS paths they hold."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import posixpath
|
||||
import re
|
||||
from collections.abc import Callable, Hashable
|
||||
from dataclasses import dataclass
|
||||
from typing import TypeVar
|
||||
|
||||
from .configgen import Launcher
|
||||
from .shell import (
|
||||
FixedPaths,
|
||||
LauncherPatternMissing,
|
||||
RepoTree,
|
||||
Script,
|
||||
apply_evidence,
|
||||
config_placement,
|
||||
describe_keys,
|
||||
first_boot_placement,
|
||||
fixed_paths,
|
||||
settings,
|
||||
source_ref,
|
||||
)
|
||||
|
||||
|
||||
ROCKNIX = "projects/ROCKNIX"
|
||||
DEVICES = f"{ROCKNIX}/devices"
|
||||
STANDALONE = f"{ROCKNIX}/packages/emulators/standalone"
|
||||
RETROARCH = f"{ROCKNIX}/packages/emulators/libretro/retroarch"
|
||||
BIOS_ROOT = "/storage/roms/bios"
|
||||
CONFIG_ROOT = "/storage/.config"
|
||||
# The first-boot step copying every package's /usr/config to /storage/.config.
|
||||
USERCONFIG = f"{ROCKNIX}/packages/sysutils/systemd/scripts/userconfig-setup"
|
||||
|
||||
Lines = list[tuple[str, set[int]]]
|
||||
# What per_device groups configs by: equal values make one group.
|
||||
Found = TypeVar("Found", bound=Hashable)
|
||||
|
||||
|
||||
@dataclass
|
||||
class DeviceConfig:
|
||||
"""The config file one or more devices install, and the lines that pick it."""
|
||||
|
||||
path: str
|
||||
devices: list[str]
|
||||
mk_lines: set[int]
|
||||
|
||||
|
||||
def device_configs(
|
||||
tree: RepoTree, package: str, file: str, folder: str = "config"
|
||||
) -> list[DeviceConfig]:
|
||||
"""Each distinct file package.mk installs as `file` for some device.
|
||||
|
||||
The directory comes from `${PKG_DIR}/<folder>/${DEVICE}/` or from a
|
||||
`case ${DEVICE}` naming it. A device whose directory is absent does not
|
||||
get the package. A directory that is a symlink resolves to its target.
|
||||
"""
|
||||
mk_path = f"{package}/package.mk"
|
||||
mk = Script(mk_path, tree.read(mk_path))
|
||||
arms: list[tuple[list[str], str]] = []
|
||||
mk_lines: set[int] = set()
|
||||
for block in re.finditer(r'case\s+"?\$\{?DEVICE\}?"?\s+in(.*?)\besac\b', mk.text, re.S):
|
||||
body = block.group(1)
|
||||
if not re.search(rf"CONFIG=|\$\{{PKG_DIR\}}/{folder}/", body):
|
||||
continue
|
||||
offset = block.start(1)
|
||||
for case_arm in re.finditer(r"^\s*([\w*|]+)\)(.*?);;", body, re.M | re.S):
|
||||
chosen = re.search(
|
||||
rf'CONFIG="([^"]+)"|\$\{{PKG_DIR\}}/{folder}/([^/\s]+)', case_arm.group(2)
|
||||
)
|
||||
if chosen:
|
||||
arms.append((case_arm.group(1).split("|"), chosen.group(1) or chosen.group(2)))
|
||||
mk_lines.add(mk.text.count("\n", 0, offset + case_arm.start(2)) + 1)
|
||||
break
|
||||
if not arms:
|
||||
number, _ = mk.find(
|
||||
rf"\$\{{PKG_DIR\}}/{folder}/\$\{{DEVICE\}}/", f"{folder}/${{DEVICE}} copy"
|
||||
)
|
||||
arms, mk_lines = [(["*"], "${DEVICE}")], {number}
|
||||
root = f"{package}/{folder}"
|
||||
entries = tree.listdir(root)
|
||||
by_path: dict[str, DeviceConfig] = {}
|
||||
for device, entry in tree.listdir(DEVICES).items():
|
||||
if entry.kind != "dir":
|
||||
continue
|
||||
arm = next((d for patterns, d in arms if device in patterns or "*" in patterns), None)
|
||||
if arm is None:
|
||||
continue
|
||||
name = device if arm in ("${DEVICE}", "${CONFIG}") else arm
|
||||
found = entries.get(name)
|
||||
if found is None:
|
||||
continue
|
||||
if found.kind == "link":
|
||||
name = found.target.rstrip("/")
|
||||
path = f"{root}/{name}/{file}"
|
||||
by_path.setdefault(path, DeviceConfig(path, [], mk_lines)).devices.append(device)
|
||||
if not by_path:
|
||||
raise LauncherPatternMissing(root, f"{file} for any device")
|
||||
return sorted(by_path.values(), key=lambda c: c.path)
|
||||
|
||||
|
||||
def per_device(
|
||||
tree: RepoTree,
|
||||
configs: list[DeviceConfig],
|
||||
mk_path: str,
|
||||
read: Callable[[str, str], tuple[Found, set[int]]],
|
||||
) -> list[tuple[str | None, Found, Lines]]:
|
||||
"""Configs grouped by what read() finds in them.
|
||||
|
||||
read(path, text) returns a comparable value and the lines it comes from.
|
||||
One group gives one result without a device. Otherwise each group names
|
||||
its devices, in the order of the devices directory.
|
||||
"""
|
||||
groups: dict[Found, tuple[list[str], Lines]] = {}
|
||||
for config in configs:
|
||||
value, lines = read(config.path, tree.read(config.path))
|
||||
devices, refs = groups.setdefault(value, ([], []))
|
||||
devices.extend(config.devices)
|
||||
refs.append((config.path, lines))
|
||||
mk_lines = set().union(*(c.mk_lines for c in configs))
|
||||
if len(groups) == 1:
|
||||
((value, (_, refs)),) = groups.items()
|
||||
return [(None, value, [*refs, (mk_path, mk_lines)])]
|
||||
order = list(tree.listdir(DEVICES))
|
||||
return [
|
||||
(", ".join(sorted(devices, key=order.index)), value, [*refs, (mk_path, mk_lines)])
|
||||
for value, (devices, refs) in sorted(
|
||||
groups.items(), key=lambda g: min(order.index(d) for d in g[1][0])
|
||||
)
|
||||
]
|
||||
|
||||
|
||||
def file_under(value: str, root: str) -> bool:
|
||||
return value.startswith(root.rstrip("/") + "/")
|
||||
|
||||
|
||||
def bios_keys(tree: RepoTree, paths: list[str], root: str = BIOS_ROOT) -> list[tuple[str, str]]:
|
||||
"""Keys whose value is a file under root in at least one of the configs."""
|
||||
keys: list[tuple[str, str]] = []
|
||||
for path in paths:
|
||||
for setting in settings(tree.read(path)):
|
||||
key = (setting.section, setting.key)
|
||||
if file_under(setting.value, root) and key not in keys:
|
||||
keys.append(key)
|
||||
if not keys:
|
||||
raise LauncherPatternMissing(paths[0], f"key naming a file under {root}")
|
||||
return keys
|
||||
|
||||
|
||||
def with_evidence(
|
||||
tree: RepoTree,
|
||||
record: Launcher,
|
||||
target: str,
|
||||
keys: list[str],
|
||||
start: Script | None = None,
|
||||
writers: tuple[str, ...] = (),
|
||||
source_name: str = "",
|
||||
) -> Launcher:
|
||||
"""A config record with the steps that put its file at ``target``.
|
||||
|
||||
The first boot copies /usr/config to /storage/.config, leaving a file
|
||||
already there. A start script can copy or generate it again, and its
|
||||
sed lines rewriting one of the record's keys are the overrides.
|
||||
"""
|
||||
placements = [first_boot_placement(Script(USERCONFIG, tree.read(USERCONFIG)), target)]
|
||||
if start is not None:
|
||||
placements.append(config_placement(
|
||||
start, target, keys, writers, source_name, required=False
|
||||
))
|
||||
return apply_evidence(record, placements)
|
||||
|
||||
|
||||
def fixed_path_keys(value: FixedPaths) -> list[str]:
|
||||
return [f"[{section}] {key}" if section else key for section, key in value.keys]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Installed:
|
||||
"""Where the launch puts a per-device config, and the start script doing it."""
|
||||
|
||||
target: str = ""
|
||||
start: Script | None = None
|
||||
|
||||
|
||||
def config_records(
|
||||
tree: RepoTree,
|
||||
emulator: str,
|
||||
package: str,
|
||||
file: str,
|
||||
passes_to_suffix: str = "",
|
||||
depends_on_option: str | None = None,
|
||||
installed: Installed | None = None,
|
||||
unread: Callable[[tuple[str, str]], bool] = lambda key: False,
|
||||
) -> list[Launcher]:
|
||||
"""fixed_name records for the bios paths of a config installed per device.
|
||||
|
||||
``unread`` drops the keys the shipped configs leave the emulator
|
||||
reading no file from.
|
||||
"""
|
||||
installed = installed or Installed()
|
||||
configs = device_configs(tree, package, file)
|
||||
keys = [k for k in bios_keys(tree, [c.path for c in configs]) if not unread(k)]
|
||||
name = posixpath.basename(file)
|
||||
|
||||
def read(path: str, text: str) -> tuple[FixedPaths, set[int]]:
|
||||
return fixed_paths(settings(text), keys, path)
|
||||
|
||||
records = []
|
||||
for device, value, refs in per_device(tree, configs, f"{package}/package.mk", read):
|
||||
assert isinstance(value, FixedPaths)
|
||||
described = describe_keys(name, value.keys)
|
||||
records.append(with_evidence(
|
||||
tree,
|
||||
Launcher(
|
||||
emulator=emulator,
|
||||
build="standalone",
|
||||
kind="fixed_name",
|
||||
names=list(value.names),
|
||||
source_ref=source_ref(refs),
|
||||
search_dir=value.search_dir or None,
|
||||
passes_to=(
|
||||
(described + passes_to_suffix) if value.names else f"{described} left empty"
|
||||
),
|
||||
device=device,
|
||||
depends_on_option=depends_on_option,
|
||||
),
|
||||
installed.target or f"{CONFIG_ROOT}/{posixpath.basename(package)}/{name}",
|
||||
fixed_path_keys(value),
|
||||
installed.start,
|
||||
))
|
||||
return records
|
||||
|
||||
|
||||
def directory_records(
|
||||
tree: RepoTree,
|
||||
emulator: str,
|
||||
package: str,
|
||||
file: str,
|
||||
folder_key: tuple[str, str],
|
||||
file_keys: tuple[tuple[str, str], ...],
|
||||
target: str = "",
|
||||
start: str = "",
|
||||
) -> list[Launcher]:
|
||||
"""scans_dir records: the config hands a directory and leaves the file keys empty."""
|
||||
configs = device_configs(tree, package, file)
|
||||
name = posixpath.basename(file)
|
||||
|
||||
def read(path: str, text: str) -> tuple[str, set[int]]:
|
||||
found = {(s.section, s.key): s for s in settings(text)}
|
||||
if folder_key not in found:
|
||||
raise LauncherPatternMissing(path, f"[{folder_key[0]}] {folder_key[1]}")
|
||||
set_files = [k for k in file_keys if k in found and found[k].value]
|
||||
if set_files:
|
||||
raise LauncherPatternMissing(path, f"empty [{set_files[0][0]}] {set_files[0][1]}")
|
||||
lines = {found[k].line for k in (folder_key, *file_keys) if k in found}
|
||||
return found[folder_key].value, lines
|
||||
|
||||
unset = describe_keys("", file_keys).strip()
|
||||
records = []
|
||||
for device, folder, refs in per_device(tree, configs, f"{package}/package.mk", read):
|
||||
passes = f"{name} [{folder_key[0]}] {folder_key[1]} = {folder}, {unset} unset"
|
||||
records.append(with_evidence(
|
||||
tree,
|
||||
Launcher(
|
||||
emulator=emulator,
|
||||
build="standalone",
|
||||
kind="scans_dir",
|
||||
names=[],
|
||||
source_ref=source_ref(refs),
|
||||
search_dir=folder,
|
||||
passes_to=passes,
|
||||
device=device,
|
||||
),
|
||||
target,
|
||||
[f"[{s}] {k}" for s, k in (folder_key, *file_keys)],
|
||||
Script(start, tree.read(start)) if start else None,
|
||||
))
|
||||
return records
|
||||
@@ -0,0 +1,795 @@
|
||||
"""Readers for launchers written as shell scripts and key=value configs.
|
||||
|
||||
ROCKNIX and EmuDeck launch emulators from bash: a start script links or
|
||||
writes a BIOS path, a config shipped with the package names the file. These
|
||||
helpers read that text without running it. Each one targets a construct
|
||||
(an assignment, a for loop, an ln command, a key of a config) and the
|
||||
extractors built on them raise LauncherPatternMissing when the construct is
|
||||
gone, so a rewrite upstream stops the scrape instead of publishing nothing.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import posixpath
|
||||
import re
|
||||
from collections.abc import Callable, Iterable
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
from model.sourceref import span
|
||||
|
||||
from ..base_scraper import fetch_bytes, github_tree
|
||||
from .configgen import Launcher, LauncherPatternMissing
|
||||
|
||||
NAME = r"[A-Za-z_][A-Za-z0-9_]*"
|
||||
# A single-quoted "$" is literal: it is carried as this mark through expansion.
|
||||
LITERAL_DOLLAR = "\x00"
|
||||
# A loop variable expands to this mark around its name, so the caller can
|
||||
# tell which part of a path the loop supplies.
|
||||
LOOP_MARK = "\x01"
|
||||
|
||||
|
||||
def merge_lines(lines: Iterable[int]) -> list[tuple[int, int]]:
|
||||
"""Line numbers as sorted spans, a gap of one line joined."""
|
||||
spans: list[tuple[int, int]] = []
|
||||
for line in sorted(set(lines)):
|
||||
if spans and line <= spans[-1][1] + 2:
|
||||
spans[-1] = (spans[-1][0], line)
|
||||
else:
|
||||
spans.append((line, line))
|
||||
return spans
|
||||
|
||||
|
||||
def source_ref(parts: Iterable[tuple[str, Iterable[int]]]) -> str:
|
||||
"""path:a-b, c for each file, files in the order given."""
|
||||
merged: dict[str, set[int]] = {}
|
||||
for path, lines in parts:
|
||||
merged.setdefault(path, set()).update(lines)
|
||||
return ", ".join(
|
||||
f"{path}:{', '.join(span(*s) for s in merge_lines(lines))}"
|
||||
for path, lines in merged.items()
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
class Word:
|
||||
"""A shell word: as written, and with quotes removed."""
|
||||
|
||||
raw: str
|
||||
text: str
|
||||
|
||||
|
||||
def words(line: str) -> list[Word]:
|
||||
"""The words of one command line, quotes removed, comments dropped.
|
||||
|
||||
Variables are left unexpanded, each written ${NAME} so the quoting that
|
||||
ended a name ("$a""b") still ends it. A "$" inside single quotes is kept
|
||||
as LITERAL_DOLLAR so a later expansion leaves it alone.
|
||||
"""
|
||||
lexer = _Lexer(line)
|
||||
i = 0
|
||||
while i < len(line):
|
||||
if lexer.quote == "'":
|
||||
lexer.single(line[i])
|
||||
elif lexer.quote == '"':
|
||||
i = lexer.double(i)
|
||||
else:
|
||||
step = lexer.plain(i)
|
||||
if step is None:
|
||||
break
|
||||
i = step
|
||||
i += 1
|
||||
if lexer.started:
|
||||
lexer.close_segment()
|
||||
lexer.result.append(Word(lexer.raw, lexer.text))
|
||||
return lexer.result
|
||||
|
||||
|
||||
class _Lexer:
|
||||
"""The state words() keeps while it reads a line character by character."""
|
||||
|
||||
def __init__(self, line: str) -> None:
|
||||
self.line = line
|
||||
self.result: list[Word] = []
|
||||
self.raw, self.text, self.quote, self.started, self.segment = "", "", "", False, 0
|
||||
|
||||
def close_segment(self) -> None:
|
||||
self.text = self.text[:self.segment] + re.sub(
|
||||
rf"\$({NAME})", r"${\1}", self.text[self.segment:]
|
||||
)
|
||||
self.segment = len(self.text)
|
||||
|
||||
def single(self, char: str) -> None:
|
||||
"""One character inside single quotes."""
|
||||
self.raw += char
|
||||
if char == "'":
|
||||
self.quote = ""
|
||||
self.segment = len(self.text)
|
||||
else:
|
||||
self.text += LITERAL_DOLLAR if char == "$" else char
|
||||
|
||||
def double(self, i: int) -> int:
|
||||
"""The character at i inside double quotes, and the index of the last one read."""
|
||||
line, char = self.line, self.line[i]
|
||||
self.raw += char
|
||||
if char == "\\" and i + 1 < len(line) and line[i + 1] in '"\\$`':
|
||||
self.raw += line[i + 1]
|
||||
self.text += LITERAL_DOLLAR if line[i + 1] == "$" else line[i + 1]
|
||||
return i + 1
|
||||
if char == '"':
|
||||
self.quote = ""
|
||||
self.close_segment()
|
||||
else:
|
||||
self.text += char
|
||||
return i
|
||||
|
||||
def plain(self, i: int) -> int | None:
|
||||
"""The character at i outside quotes, and the index of the last one read (None at a comment)."""
|
||||
line, char = self.line, self.line[i]
|
||||
if char in "'\"":
|
||||
self.close_segment()
|
||||
self.quote, self.started = char, True
|
||||
self.raw += char
|
||||
elif char == "\\" and i + 1 < len(line):
|
||||
self.raw += char + line[i + 1]
|
||||
self.text += line[i + 1]
|
||||
self.started = True
|
||||
return i + 1
|
||||
elif char == "#" and not self.started:
|
||||
return None
|
||||
elif char.isspace() or char == ";":
|
||||
if self.started:
|
||||
self.close_segment()
|
||||
self.result.append(Word(self.raw, self.text))
|
||||
self.raw, self.text, self.started, self.segment = "", "", False, 0
|
||||
if char == ";":
|
||||
self.result.append(Word(";", ";"))
|
||||
else:
|
||||
self.raw += char
|
||||
self.text += char
|
||||
self.started = True
|
||||
return i
|
||||
|
||||
|
||||
@dataclass
|
||||
class Assignment:
|
||||
line: int
|
||||
value: str
|
||||
|
||||
|
||||
@dataclass
|
||||
class Loop:
|
||||
"""A for loop: its variable, its items and the lines they come from."""
|
||||
|
||||
var: str
|
||||
items: list[str]
|
||||
start: int
|
||||
end: int
|
||||
lines: set[int] = field(default_factory=set)
|
||||
|
||||
|
||||
@dataclass
|
||||
class Link:
|
||||
"""An ln -s whose link or target lies under the BIOS root."""
|
||||
|
||||
target: str
|
||||
link: str
|
||||
bios_side: str
|
||||
names: list[str]
|
||||
lines: set[int]
|
||||
bios_is_target: bool = True
|
||||
expands: dict[str, list[str]] = field(default_factory=dict)
|
||||
|
||||
|
||||
def _placeholders(text: str, marks: dict[str, Loop]) -> str:
|
||||
"""Loop marks written as {VAR}, the placeholder `expands` resolves."""
|
||||
for mark, loop in marks.items():
|
||||
text = text.replace(mark, "{" + loop.var + "}")
|
||||
return text
|
||||
|
||||
|
||||
class Script:
|
||||
"""One shell script or makefile, read line by line."""
|
||||
|
||||
def __init__(self, path: str, text: str) -> None:
|
||||
self.path = path
|
||||
self.text = text
|
||||
self.lines = text.splitlines()
|
||||
self._assignments: dict[str, list[Assignment]] = {}
|
||||
self._arrays: dict[str, tuple[int, list[str]]] = {}
|
||||
for number, line in enumerate(self.lines, 1):
|
||||
found = re.match(rf"\s*(?:local\s+|export\s+)?({NAME})=(.*)$", line)
|
||||
if found is None:
|
||||
continue
|
||||
array = re.fullmatch(r"\((.*)\)\s*", found.group(2))
|
||||
if array:
|
||||
self._arrays[found.group(1)] = (number, [w.text for w in words(array.group(1))])
|
||||
continue
|
||||
value = words(found.group(2))
|
||||
if value and value[0].raw:
|
||||
self._assignments.setdefault(found.group(1), []).append(
|
||||
Assignment(number, value[0].text)
|
||||
)
|
||||
|
||||
def missing(self, what: str) -> LauncherPatternMissing:
|
||||
return LauncherPatternMissing(self.path, what)
|
||||
|
||||
def code(self) -> Iterable[tuple[int, str]]:
|
||||
"""Lines that are not comments."""
|
||||
for number, line in enumerate(self.lines, 1):
|
||||
if not line.lstrip().startswith("#"):
|
||||
yield number, line
|
||||
|
||||
def find(
|
||||
self, pattern: str, what: str, start: int = 1, end: int | None = None
|
||||
) -> tuple[int, re.Match[str]]:
|
||||
"""The first code line from start to end matching pattern."""
|
||||
for number, line in self.code():
|
||||
if number < start or (end is not None and number > end):
|
||||
continue
|
||||
found = re.search(pattern, line)
|
||||
if found:
|
||||
return number, found
|
||||
raise self.missing(what)
|
||||
|
||||
def assignment_ending(self, suffix: str) -> Assignment | None:
|
||||
"""The first assignment whose value ends with suffix."""
|
||||
return next(
|
||||
(a for found in self._assignments.values() for a in found if a.value.endswith(suffix)),
|
||||
None,
|
||||
)
|
||||
|
||||
def value(self, name: str, before: int) -> Assignment | None:
|
||||
"""The last assignment of name above a line, else the first below it."""
|
||||
assignments = self._assignments.get(name, [])
|
||||
above = [a for a in assignments if a.line < before]
|
||||
if above:
|
||||
return above[-1]
|
||||
return assignments[0] if assignments else None
|
||||
|
||||
def expand(
|
||||
self, text: str, line: int, used: set[int], fixed: dict[str, str] | None = None
|
||||
) -> str:
|
||||
"""Variables replaced by their assigned value, unknown ones as ${NAME}."""
|
||||
fixed = fixed or {}
|
||||
|
||||
def replace(found: re.Match[str], depth: int) -> str:
|
||||
name = found.group(1) or found.group(2)
|
||||
if name in fixed:
|
||||
return fixed[name]
|
||||
assignment = self.value(name, line)
|
||||
if assignment is None or depth > 8:
|
||||
return "${" + name + "}"
|
||||
used.add(assignment.line)
|
||||
return expand_once(assignment.value, assignment.line, depth + 1)
|
||||
|
||||
def expand_once(value: str, at: int, depth: int) -> str:
|
||||
nonlocal line
|
||||
saved, line = line, at
|
||||
try:
|
||||
return re.sub(rf"\$\{{({NAME})\}}|\$({NAME})", lambda m: replace(m, depth), value)
|
||||
finally:
|
||||
line = saved
|
||||
|
||||
return expand_once(text, line, 0).replace(LITERAL_DOLLAR, "$")
|
||||
|
||||
def loops(self) -> list[Loop]:
|
||||
"""Every for loop, items from a word list or from "${ARRAY[@]}"."""
|
||||
found_loops = []
|
||||
for number, line in self.code():
|
||||
head = re.match(rf"\s*for ({NAME}) in (.*?)\s*(?:;\s*do)?\s*$", line)
|
||||
if head is None:
|
||||
continue
|
||||
items = [w.text for w in words(head.group(2)) if w.text != ";"]
|
||||
lines = {number}
|
||||
if len(items) == 1 and (array := re.fullmatch(rf"\$\{{({NAME})\[@\]\}}", items[0])):
|
||||
if array.group(1) not in self._arrays:
|
||||
raise self.missing(f"array {array.group(1)}")
|
||||
array_line, items = self._arrays[array.group(1)]
|
||||
lines.add(array_line)
|
||||
found_loops.append(Loop(head.group(1), items, number, self._loop_end(number), lines))
|
||||
return found_loops
|
||||
|
||||
def _loop_end(self, start: int) -> int:
|
||||
depth = 0
|
||||
for number, line in self.code():
|
||||
if number < start:
|
||||
continue
|
||||
if re.match(r"\s*(for|while|until)\b", line):
|
||||
depth += 1
|
||||
if re.match(r"\s*done\b", line) or re.search(r";\s*done\s*$", line):
|
||||
depth -= 1
|
||||
if depth == 0:
|
||||
return number
|
||||
raise self.missing(f"done of the loop at line {start}")
|
||||
|
||||
def links(self, bios_root: str, fixed: dict[str, str] | None = None) -> list[Link]:
|
||||
"""ln -s commands with the link or its target under bios_root.
|
||||
|
||||
Links in one loop, or written one by one as P/n linked to Q/n, are
|
||||
one Link listing each n.
|
||||
"""
|
||||
loops = self.loops()
|
||||
found: list[Link] = []
|
||||
for number, line in self.code():
|
||||
command = words(line)
|
||||
heads = [
|
||||
i
|
||||
for i, w in enumerate(command)
|
||||
if w.raw == "ln"
|
||||
and (i == 0 or command[i - 1].raw in {";", "then", "do", "&&", "||"})
|
||||
]
|
||||
for head in heads:
|
||||
args = []
|
||||
for word in command[head + 1 :]:
|
||||
if word.raw in {";", "&&", "||"}:
|
||||
break
|
||||
args.append(word)
|
||||
options = [w.text for w in args if w.text.startswith("-")]
|
||||
operands = [w.text for w in args if not w.text.startswith("-")]
|
||||
if not any("s" in o for o in options) or len(operands) != 2:
|
||||
continue
|
||||
enclosing = [lp for lp in loops if lp.start < number <= lp.end]
|
||||
env = dict(fixed or {})
|
||||
marks = {f"{LOOP_MARK}{lp.var}{LOOP_MARK}": lp for lp in enclosing}
|
||||
env.update({lp.var: mark for mark, lp in marks.items()})
|
||||
used = {number}
|
||||
target, link = (self.expand(op, number, used, env) for op in operands)
|
||||
if not (_under(target, bios_root) or _under(link, bios_root)):
|
||||
continue
|
||||
bios_is_target = _under(target, bios_root)
|
||||
bios_side = (target if bios_is_target else link).rstrip("/")
|
||||
folder, _, last = bios_side.rpartition("/")
|
||||
present = [m for m in marks if m in target or m in link]
|
||||
if any(m in folder for m in present):
|
||||
raise self.missing(
|
||||
f"loop variable only in the last segment of the ln at line {number}"
|
||||
)
|
||||
names: list[str] = []
|
||||
expands: dict[str, list[str]] = {}
|
||||
if present:
|
||||
bios_side = folder
|
||||
if last in marks:
|
||||
names = list(marks[last].items)
|
||||
else:
|
||||
names = [_placeholders(last, marks)]
|
||||
expands = {lp.var: list(lp.items) for m, lp in marks.items() if m in last}
|
||||
if bios_is_target and last not in link:
|
||||
link = f"{link.rstrip('/')}/{last}"
|
||||
for mark in present:
|
||||
used |= marks[mark].lines
|
||||
template = _placeholders(last, marks) if expands else "<name>"
|
||||
target, link = (
|
||||
p.replace(last, template) if last in p else _placeholders(p, marks)
|
||||
for p in (target, link)
|
||||
)
|
||||
duplicate = next((f for f in found if (f.target, f.link) == (target, link)), None)
|
||||
if duplicate is not None:
|
||||
duplicate.lines |= used
|
||||
continue
|
||||
found.append(Link(target, link, bios_side, names, used, bios_is_target, expands))
|
||||
return _merge_links(found)
|
||||
|
||||
|
||||
def link_record(
|
||||
emulator: str,
|
||||
script: Script,
|
||||
link: Link,
|
||||
*,
|
||||
guard_lines: Iterable[int] = (),
|
||||
case_insensitive: bool | None = None,
|
||||
fails_when_missing: bool | str | None = False,
|
||||
) -> Launcher:
|
||||
"""The record of an ln -s a script makes under the BIOS root,
|
||||
citing the guard lines the link waits for beside its own."""
|
||||
return Launcher(
|
||||
emulator=emulator,
|
||||
build="standalone",
|
||||
kind="links",
|
||||
names=list(link.names),
|
||||
source_ref=source_ref([(script.path, link.lines | set(guard_lines))]),
|
||||
expands=link.expands or None,
|
||||
search_dir=link.bios_side,
|
||||
passes_to=f"symlink {link.link} -> {link.target}",
|
||||
case_insensitive=case_insensitive,
|
||||
fails_when_missing=fails_when_missing,
|
||||
)
|
||||
|
||||
|
||||
def _under(path: str, root: str) -> bool:
|
||||
return path.rstrip("/") == root.rstrip("/") or path.startswith(root.rstrip("/") + "/")
|
||||
|
||||
|
||||
def _merge_links(links: list[Link]) -> list[Link]:
|
||||
"""Single links P/n -> Q/n sharing P and Q folded into one, names in order."""
|
||||
merged: list[Link] = []
|
||||
folds: dict[tuple[str, str, bool], tuple[Link, list[Link]]] = {}
|
||||
for link in links:
|
||||
bios = link.bios_side.rstrip("/")
|
||||
bios_is_target = link.bios_is_target
|
||||
other = (link.link if bios_is_target else link.target).rstrip("/")
|
||||
name = bios.rsplit("/", 1)[-1]
|
||||
if link.names or other.rsplit("/", 1)[-1] != name:
|
||||
merged.append(link)
|
||||
continue
|
||||
key = (bios.rsplit("/", 1)[0], other.rsplit("/", 1)[0], bios_is_target)
|
||||
if key in folds:
|
||||
folds[key][1].append(link)
|
||||
else:
|
||||
folds[key] = (link, [link])
|
||||
merged.append(link)
|
||||
folded: set[int] = set()
|
||||
for (parent, other_parent, bios_is_target), (first, members) in folds.items():
|
||||
if len(members) == 1:
|
||||
continue
|
||||
first.names = [m.bios_side.rstrip("/").rsplit("/", 1)[-1] for m in members]
|
||||
first.bios_side = parent
|
||||
bios_end, other_end = f"{parent}/<name>", f"{other_parent}/<name>"
|
||||
first.target, first.link = (
|
||||
(bios_end, other_end) if bios_is_target else (other_end, bios_end)
|
||||
)
|
||||
for member in members[1:]:
|
||||
first.lines |= member.lines
|
||||
folded.add(id(member))
|
||||
return [link for link in merged if id(link) not in folded]
|
||||
|
||||
|
||||
_COPY = re.compile(r"(?:^|[\s;&|(])(cp|rsync|install|mv)\s")
|
||||
_GUARD = re.compile(r"\[\[?\s*!\s+-[fde]\s+(\S+)\s*\]")
|
||||
|
||||
|
||||
@dataclass
|
||||
class ConfigPlacement:
|
||||
"""How a start script puts a config where the emulator reads it.
|
||||
|
||||
``install`` are the lines copying it there, ``kept_if_present`` whether
|
||||
every such copy runs only when the file (or its folder) is absent, and
|
||||
``overrides`` the sed lines rewriting one of the record's keys in it.
|
||||
"""
|
||||
|
||||
script: str
|
||||
path: str
|
||||
install: set[int]
|
||||
kept_if_present: bool
|
||||
overrides: set[int]
|
||||
|
||||
|
||||
def _bare_key(key: str) -> str:
|
||||
return key.rsplit("] ", 1)[-1].rsplit("/", 1)[-1].strip()
|
||||
|
||||
|
||||
def _guarded(script: Script, number: int, target: str) -> bool:
|
||||
"""Whether a line runs only when target, or a folder above it, is absent."""
|
||||
|
||||
def covers(found: re.Match[str], at: int) -> bool:
|
||||
guarded = script.expand(words(found.group(1))[0].text, at, set()).rstrip("/")
|
||||
return target == guarded or target.startswith(guarded + "/")
|
||||
|
||||
line = script.lines[number - 1]
|
||||
if any(covers(m, number) for m in _GUARD.finditer(line)):
|
||||
return True
|
||||
depth = 0
|
||||
for at in range(number - 1, 0, -1):
|
||||
text = script.lines[at - 1].strip()
|
||||
if re.match(r"fi\b", text):
|
||||
depth += 1
|
||||
elif re.match(r"if\b", text):
|
||||
if depth:
|
||||
depth -= 1
|
||||
continue
|
||||
return any(covers(m, at) for m in _GUARD.finditer(text))
|
||||
return False
|
||||
|
||||
|
||||
def _quoted_glob(command: str) -> bool:
|
||||
"""Whether the source of a copy holds a "*" only inside quotes."""
|
||||
found = [w for w in words(command)[1:] if not w.raw.startswith("-")]
|
||||
if len(found) < 2:
|
||||
return False
|
||||
raw = found[0].raw
|
||||
return "*" in raw and "*" not in re.sub(r'"[^"]*"|\'[^\']*\'', "", raw)
|
||||
|
||||
|
||||
def _copy_skips(
|
||||
script: Script,
|
||||
number: int,
|
||||
line: str,
|
||||
copy: re.Match[str],
|
||||
target: str,
|
||||
source_name: str,
|
||||
sources: tuple[str, ...],
|
||||
) -> bool | None:
|
||||
"""For a copy that installs ``target``, whether it leaves a file already there.
|
||||
|
||||
None when the copy installs something else.
|
||||
"""
|
||||
args = []
|
||||
for word in words(line[copy.start(1):])[1:]:
|
||||
# The command ends at a separator or a redirection.
|
||||
if word.raw in {";", "&&", "||", "|"} or re.match(r"\d*>|&>", word.raw):
|
||||
break
|
||||
args.append(word.text)
|
||||
operands = [a for a in args if not a.startswith("-")]
|
||||
if not operands:
|
||||
return None
|
||||
# A quoted "*" is a file named *, which no package installs:
|
||||
# the copy does nothing (EmuELEC's duckstation.sh).
|
||||
if _quoted_glob(line[copy.start(1):]):
|
||||
return None
|
||||
destination = script.expand(operands[-1], number, set()).rstrip("/")
|
||||
source = script.expand(operands[0], number, set()).rstrip("/")
|
||||
hits = target == destination or target.startswith(
|
||||
(destination + "/", f"{destination}/{source.rsplit('/', 1)[-1]}")
|
||||
)
|
||||
# A copy of another file into the same place is another
|
||||
# record's: amiberry copies the A500 or the A1200 setup.
|
||||
named = source.rsplit("/", 1)[-1]
|
||||
if not hits or (source_name and "." in named and named != source_name):
|
||||
return None
|
||||
# A named file copied into a folder above the target is
|
||||
# another file of that folder (ARMSX2's secrets.ini).
|
||||
if (
|
||||
not source_name and "." in named and "*" not in named
|
||||
and destination != target and named != target.rsplit("/", 1)[-1]
|
||||
):
|
||||
return None
|
||||
if sources and not source.startswith(sources):
|
||||
return None
|
||||
# cp -i fed by false answers no to every overwrite.
|
||||
prompted = any(
|
||||
a.startswith("-") and not a.startswith("--") and "i" in a[1:] for a in args
|
||||
) and re.search(r"\bfalse\s*\|\s*$", line[:copy.start(1)])
|
||||
return "-n" in args or "--ignore-existing" in args or bool(prompted)
|
||||
|
||||
|
||||
def config_placement(
|
||||
script: Script,
|
||||
target: str,
|
||||
keys: Iterable[str] = (),
|
||||
writers: Iterable[str] = (),
|
||||
source_name: str = "",
|
||||
required: bool = True,
|
||||
sources: tuple[str, ...] = (),
|
||||
) -> ConfigPlacement:
|
||||
"""The lines of a start script that install ``target`` and rewrite its keys.
|
||||
|
||||
A copy installs the target when its destination is the file or a folder
|
||||
above it. ``writers`` are other commands that write the file (ROCKNIX
|
||||
generates mednafen.cfg with mednafen_gen_config.sh). A copy guarded by
|
||||
`[ ! -f X ]` or `[ ! -d X ]` on the target or a folder above it, or made
|
||||
with cp -n or rsync --ignore-existing, leaves a file already there.
|
||||
"""
|
||||
install: set[int] = set()
|
||||
kept = True
|
||||
overrides: set[int] = set()
|
||||
bare = {_bare_key(k) for k in keys} - {""}
|
||||
writer = re.compile("|".join(re.escape(w) for w in writers)) if writers else None
|
||||
for number, line in script.code():
|
||||
if (copy := _COPY.search(line)) or (writer and writer.search(line)):
|
||||
if copy:
|
||||
copied = _copy_skips(script, number, line, copy, target, source_name, sources)
|
||||
if copied is None:
|
||||
continue
|
||||
skip = copied
|
||||
else:
|
||||
skip = False
|
||||
install.add(number)
|
||||
if not (skip or _guarded(script, number, target)):
|
||||
kept = False
|
||||
elif re.search(r"\bsed\b.*\s-i\b|\bsed -i", line) and bare:
|
||||
expanded = script.expand(line, number, set())
|
||||
if (target in expanded or target.rsplit("/", 1)[-1] in expanded) and any(
|
||||
re.search(rf"\b{re.escape(k)}\b", expanded) for k in bare
|
||||
):
|
||||
overrides.add(number)
|
||||
if not install and required:
|
||||
raise script.missing(f"install of {target}")
|
||||
return ConfigPlacement(script.path, target, install, kept, overrides)
|
||||
|
||||
|
||||
def evidence_fields(
|
||||
placements: Iterable[ConfigPlacement],
|
||||
installed: Iterable[tuple[str, Iterable[int]]] = (),
|
||||
) -> dict:
|
||||
"""The installs, kept_if_present and overrides fields of a config record.
|
||||
|
||||
``placements`` are the steps that put the file in place, in the order
|
||||
they run (a first-boot copy, then the start script). ``installed`` are
|
||||
the build steps that put it where they copy it from (a package.mk copy
|
||||
into /usr/config).
|
||||
"""
|
||||
placements = list(placements)
|
||||
steps = [p for p in placements if p.install]
|
||||
if not steps:
|
||||
raise LauncherPatternMissing(placements[0].path if placements else "", "install")
|
||||
return {
|
||||
"installs": {
|
||||
"path": steps[-1].path,
|
||||
"source_ref": source_ref([*installed, *((p.script, p.install) for p in steps)]),
|
||||
},
|
||||
"kept_if_present": all(p.kept_if_present for p in steps),
|
||||
"overrides": [
|
||||
source_ref([(p.script, {line})]) for p in placements for line in sorted(p.overrides)
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def first_boot_placement(setup: Script, target: str) -> ConfigPlacement:
|
||||
"""The first-boot copy of /usr/config to /storage/.config (userconfig-setup),
|
||||
which leaves a file already there and may not reach ``target``."""
|
||||
return config_placement(setup, target, required=False, sources=("/usr/config/",))
|
||||
|
||||
|
||||
def apply_evidence(
|
||||
record: Launcher,
|
||||
placements: Iterable[ConfigPlacement],
|
||||
installed: Iterable[tuple[str, Iterable[int]]] = (),
|
||||
) -> Launcher:
|
||||
"""``record`` with the installs, kept_if_present and overrides fields
|
||||
``evidence_fields`` reads from ``placements``."""
|
||||
fields = evidence_fields(placements, installed)
|
||||
record.installs = fields["installs"]
|
||||
record.kept_if_present = fields["kept_if_present"]
|
||||
record.overrides = fields["overrides"]
|
||||
return record
|
||||
|
||||
|
||||
@dataclass
|
||||
class Setting:
|
||||
section: str
|
||||
key: str
|
||||
value: str
|
||||
line: int
|
||||
|
||||
|
||||
def settings(text: str, separator: str = "=") -> list[Setting]:
|
||||
"""key = value lines under their [section], quotes around the value removed.
|
||||
|
||||
separator " " reads mednafen's "key value" form.
|
||||
"""
|
||||
found, section = [], ""
|
||||
for number, line in enumerate(text.splitlines(), 1):
|
||||
stripped = line.strip()
|
||||
if not stripped or stripped[0] in "#;":
|
||||
continue
|
||||
header = re.fullmatch(r"\[([^\]]+)\]", stripped)
|
||||
if header:
|
||||
section = header.group(1)
|
||||
continue
|
||||
if separator == " ":
|
||||
pair = re.fullmatch(r"(\S+)(?:\s+(.*))?", stripped)
|
||||
else:
|
||||
pair = re.fullmatch(r"([^=\s]+)\s*=\s*(.*)", stripped)
|
||||
if pair is None:
|
||||
continue
|
||||
value = (pair.group(2) or "").strip()
|
||||
if len(value) >= 2 and value[0] == value[-1] and value[0] in "\"'":
|
||||
value = value[1:-1]
|
||||
found.append(Setting(section, pair.group(1), value, number))
|
||||
return found
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class FixedPaths:
|
||||
"""Keys of a config that name a file under one directory."""
|
||||
|
||||
keys: tuple[tuple[str, str], ...]
|
||||
names: tuple[str, ...]
|
||||
search_dir: str
|
||||
|
||||
|
||||
def fixed_paths(
|
||||
found: list[Setting], keys: list[tuple[str, str]], path: str
|
||||
) -> tuple[FixedPaths, set[int]]:
|
||||
"""The values of keys, as names relative to the directory they share."""
|
||||
by_key = {(s.section, s.key): s for s in found}
|
||||
missing = [k for k in keys if k not in by_key]
|
||||
if missing:
|
||||
raise LauncherPatternMissing(path, f"key {missing[0][1]}")
|
||||
values = [by_key[k].value for k in keys if by_key[k].value]
|
||||
lines = {by_key[k].line for k in keys}
|
||||
if not values:
|
||||
return FixedPaths(tuple(keys), (), ""), lines
|
||||
folder = posixpath.commonpath([posixpath.dirname(v) for v in values])
|
||||
names = tuple(posixpath.relpath(v, folder) for v in values)
|
||||
return FixedPaths(tuple(keys), names, folder), lines
|
||||
|
||||
|
||||
def describe_keys(file: str, keys: tuple[tuple[str, str], ...]) -> str:
|
||||
"""file [section] key, key [other] key, sections named where they change."""
|
||||
described, section = file, None
|
||||
for index, (key_section, key) in enumerate(keys):
|
||||
if key_section and key_section != section:
|
||||
described += f" [{key_section}] {key}"
|
||||
section = key_section
|
||||
else:
|
||||
described += (" " if index == 0 else ", ") + key
|
||||
return described
|
||||
|
||||
|
||||
@dataclass
|
||||
class Entry:
|
||||
"""A directory entry: kind is "dir", "file" or "link"."""
|
||||
|
||||
kind: str
|
||||
target: str = ""
|
||||
|
||||
|
||||
class RepoTree:
|
||||
"""Files of one repository revision, read on demand and kept."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
read: Callable[[str], str],
|
||||
listdir: Callable[[str], dict[str, Entry]],
|
||||
) -> None:
|
||||
self._read = read
|
||||
self._listdir = listdir
|
||||
self._texts: dict[str, str] = {}
|
||||
self._dirs: dict[str, dict[str, Entry]] = {}
|
||||
|
||||
def read(self, path: str) -> str:
|
||||
if path not in self._texts:
|
||||
self._texts[path] = self._read(path)
|
||||
return self._texts[path]
|
||||
|
||||
def listdir(self, path: str) -> dict[str, Entry]:
|
||||
if path not in self._dirs:
|
||||
self._dirs[path] = self._listdir(path)
|
||||
return self._dirs[path]
|
||||
|
||||
def has(self, path: str) -> bool:
|
||||
parent, _, name = path.rpartition("/")
|
||||
try:
|
||||
return name in self.listdir(parent)
|
||||
except LauncherPatternMissing:
|
||||
return False
|
||||
|
||||
@classmethod
|
||||
def from_files(cls, files: dict[str, str], links: dict[str, str] | None = None) -> RepoTree:
|
||||
"""A tree held in memory: file texts by path, symlink targets by path."""
|
||||
links = links or {}
|
||||
|
||||
def read(path: str) -> str:
|
||||
if path not in files:
|
||||
raise LauncherPatternMissing(path, "file")
|
||||
return files[path]
|
||||
|
||||
def listdir(path: str) -> dict[str, Entry]:
|
||||
prefix = path.rstrip("/") + "/"
|
||||
entries: dict[str, Entry] = {}
|
||||
for name, target in links.items():
|
||||
if name.startswith(prefix) and "/" not in name[len(prefix) :]:
|
||||
entries[name[len(prefix) :]] = Entry("link", target)
|
||||
for name in files:
|
||||
if name.startswith(prefix):
|
||||
rest = name[len(prefix) :]
|
||||
head, _, tail = rest.partition("/")
|
||||
entries.setdefault(head, Entry("dir" if tail else "file"))
|
||||
if not entries:
|
||||
raise LauncherPatternMissing(path, "directory")
|
||||
return entries
|
||||
|
||||
return cls(read, listdir)
|
||||
|
||||
@classmethod
|
||||
def github(cls, repo: str, rev: str) -> RepoTree:
|
||||
"""A GitHub repository at one revision: raw files and the trees API."""
|
||||
|
||||
def read(path: str) -> str:
|
||||
url = f"https://raw.githubusercontent.com/{repo}/{rev}/{path}"
|
||||
return fetch_bytes(url).decode("utf-8-sig")
|
||||
|
||||
def listdir(path: str) -> dict[str, Entry]:
|
||||
try:
|
||||
listing = github_tree(repo, f"{rev}:{path}", recursive=False)
|
||||
except RuntimeError as e:
|
||||
raise LauncherPatternMissing(path, f"directory ({e})") from e
|
||||
entries = {}
|
||||
for item in listing:
|
||||
if item["mode"] == "120000":
|
||||
entries[item["path"]] = Entry("link", read(f"{path}/{item['path']}").strip())
|
||||
else:
|
||||
entries[item["path"]] = Entry("dir" if item["type"] == "tree" else "file")
|
||||
return entries
|
||||
|
||||
return cls(read, listdir)
|
||||
Reference in new issue
Block a user