diff --git a/scripts/scraper/emudeck_launchers.py b/scripts/scraper/emudeck_launchers.py index 0965dc5d0..0c3b5faff 100644 --- a/scripts/scraper/emudeck_launchers.py +++ b/scripts/scraper/emudeck_launchers.py @@ -158,7 +158,8 @@ def setter_records(tree: RepoTree, name: str, option_key: str | None = None) -> """ script = _script(tree, name) emulator = _emulator(name) - records: list[Launcher] = [] + # 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) @@ -177,7 +178,7 @@ def setter_records(tree: RepoTree, name: str, option_key: str | None = None) -> continue if key not in DIRECTORY_KINDS: raise script.missing(f"known directory key, got {key}") - records.append( + records.append(( Launcher( emulator=emulator, build="libretro" if emulator == "retroarch" else "standalone", @@ -186,10 +187,11 @@ def setter_records(tree: RepoTree, name: str, option_key: str | None = None) -> 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( + records.append(( Launcher( emulator=emulator, build="standalone", @@ -198,19 +200,22 @@ def setter_records(tree: RepoTree, name: str, option_key: str | None = None) -> 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 in records: - _add_option(tree, script, record, option_key) - return records + 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, option_key: str) -> None: +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.""" - config = record.passes_to.split(" ", 1)[0] file_var = script.assignment_ending("/" + config) if file_var is None: raise script.missing(f"config variable for {config}") @@ -383,7 +388,7 @@ def configured(tree: RepoTree) -> list[Launcher]: def links(tree: RepoTree) -> list[Launcher]: - records = [] + records: list[Launcher] = [] for name in LINK_SCRIPTS: script = _script(tree, name) found = script.links(BIOS) diff --git a/scripts/scraper/retrobat_launchers.py b/scripts/scraper/retrobat_launchers.py index 8a65749ae..924e7b577 100644 --- a/scripts/scraper/retrobat_launchers.py +++ b/scripts/scraper/retrobat_launchers.py @@ -1531,20 +1531,19 @@ def cxbx(sources: dict[str, Source]) -> list[Record]: f"{CXBX_DATA_FOLDER}, the folder holding {settings.group(1)}," " which the launcher writes beside the binary" ) - records = [] - for match in named: - records.append( - _record( - match.group(1), - "standalone", - "passes_path", - [], - source_ref((src.path, [src.lines(match.start(), match.end()), settings_span])), - search_dir=f'', - passes_to=passes_to, - fails_when_missing=False, - ) + records = [ + _record( + match.group(1), + "standalone", + "passes_path", + [], + source_ref((src.path, [src.lines(match.start(), match.end()), settings_span])), + search_dir=f'', + 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( @@ -1790,8 +1789,8 @@ def _negate(condition: str) -> str: anything else is wrapped in not (...). """ tests = condition.split(" && ") - compared = [re.fullmatch(rf"(\w+) != ({STRING})", t) for t in tests] - if all(compared): + 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})" @@ -2068,7 +2067,7 @@ def _wrapped(expr: str, opener: str) -> str | None: return None inner = expr[len(opener) + 1 : -1] depth = 0 - for offset, char in _code_chars(inner): + for _offset, char in _code_chars(inner): depth += {"(": 1, ")": -1}.get(char, 0) if depth < 0: return None @@ -2162,16 +2161,9 @@ def _braceless_if(src: Source, offset: int) -> str | None: 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()) - if re.fullmatch(_BIOS_ROOT, expr): - return "bios", [] - changed = re.fullmatch(r'Path\.ChangeExtension\(exe, "(\.\w+)"\)', expr) - if changed: - return f"{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], [] + 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) @@ -2183,28 +2175,10 @@ def _render(src: Source, expr: str, scope: int, before: int) -> Rendered | None: if len(ternary) == 2: branches = _split_top(ternary[1], ":") if len(branches) == 2: - 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 {ternary[0]}, else {second[0]}", first[1] + second[1] + return _render_choice(src, ternary[0], branches, scope, before) terms = _split_top(expr, " + ") if len(terms) > 1: - 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 + return _render_terms(src, terms, scope, before) combine = _wrapped(expr, "Path.Combine") if combine is not None: base, *rest = _split_top(combine, ",") @@ -2216,28 +2190,78 @@ def _render(src: Source, expr: str, scope: int, before: int) -> Rendered | None: if expr in _PATH_PARAMS: return _PATH_PARAMS[expr], [] if re.fullmatch(r"\w+", expr): - 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()) - base = _render(src, src.text[decl.end() : decl_end], scope, decl.start()) - if base is None: - return None - text, spans = base[0], [*base[1], src.lines(decl.start(), decl_end)] - for again in re.compile(rf"(? 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"{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"(?= 4: - value = _unquote(words[3]) - if _mentions_bios(value): - 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)) + 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) @@ -192,18 +181,7 @@ class Component: copies.setdefault((folder, depends), []).append((number, name, target)) continue if command == "tar" and "-C" in words and _mentions_bios(words[words.index("-C") + 1]): - if "-czf" in words: - continue - 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, - ) + self._tar(path, number, words, raw, depends) continue if command == "sed" and PLACEHOLDER in raw: self._preset(script, number, words) @@ -215,8 +193,8 @@ class Component: raise LauncherPatternMissing( f"{path}:{number}", f"unrecognised use of $bios_path: {raw}" ) - for key, hits in settings.items(): - self._settings(path, key, hits) + 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] @@ -226,6 +204,40 @@ class Component: 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 diff --git a/scripts/scraper/retropie_launchers.py b/scripts/scraper/retropie_launchers.py index 544eb1adb..292b3161e 100644 --- a/scripts/scraper/retropie_launchers.py +++ b/scripts/scraper/retropie_launchers.py @@ -23,6 +23,7 @@ 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 @@ -224,8 +225,8 @@ class Scripts: lines = text.splitlines() fields: dict[str, tuple[str, int]] = {} for found in _MODULE_FIELD.finditer(text): - line = text.count("\n", 0, found.start()) + 1 - fields.setdefault(found.group(1), (found.group(2), line)) + field_line = text.count("\n", 0, found.start()) + 1 + fields.setdefault(found.group(1), (found.group(2), field_line)) if "id" not in fields: return None repo = fields.get("repo") @@ -299,21 +300,15 @@ class Scripts: for number, text, opener in _logical_lines(module.lines, start + 1, end - 1): stripped = text.strip() if array is not None: - 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)] + if self._array_line(array, stripped, package, env): array = None continue if opener is not None: if self._live(branches): - words = [self.expand(w, package, env) for w in stripped.split()] events.setdefault((module.path, number), Event( - module.path, number, words, stripped, - conditions + self._shown(branches, package, env), True, - [self.expand(w, package, env) for w in _split(opener)], + 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("#"): @@ -322,35 +317,16 @@ class Scripts: continue if not self._live(branches): continue - 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 - continue - if re.match(r"^(while|until)\b|^for\s*\(\(", stripped): - loops.append((None, None)) - continue - if stripped == "done" or stripped.startswith("done ") or stripped.startswith("done;"): - if loops: - var, previous = loops.pop() - if var is not None: - if previous is None: - env.pop(var, None) - else: - env[var] = previous + if self._loop(stripped, package, env, loops): continue if stripped in ("do", "then", "else", "fi", "esac", "{", "}"): continue - guard = re.match(r"^\[\[\s*(.*?)\s*\]\]\s*&&\s*(.*)$", stripped) - shown = conditions + self._shown(branches, package, env) - if guard is not None: - 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): - continue - if verdict is None: - shown = shown + [self._render(guard.group(1), package, env)] - stripped = guard.group(2) + 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)]) @@ -362,10 +338,79 @@ class Scripts: events.setdefault( (module.path, number), Event(module.path, number, words, stripped, shown, False) ) - 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) + 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]], @@ -462,14 +507,10 @@ class Scripts: if not bound: results.append(braced) continue - for values in product(*(env[n] for n in bound)): - chosen = dict(zip(bound, values)) - - def replace(found: re.Match[str]) -> str: - key = found.group(1) or found.group(3) - return chosen.get(key, found.group(0)) - - results.append(_VAR.sub(replace, braced)) + results.extend( + _VAR.sub(partial(_bound_value, dict(zip(bound, values))), braced) + for values in product(*(env[n] for n in bound)) + ) return results @@ -483,6 +524,11 @@ LIST_SEPARATORS = {"advmame": ":", "advmame-0.94": ":", "advmame-1.4": ":"} DEFAULT_LIST_SEPARATOR = ";" +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 _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. @@ -494,7 +540,7 @@ def _search_list_in_roms(event: Event, separator: str = DEFAULT_LIST_SEPARATOR) return False parts = [p for p in event.words[2][0].split(separator) if p] return len(parts) > 1 and all( - p.startswith(ROMDIR + "/") or p.startswith("${romdir}/") for p in parts + p.startswith((ROMDIR + "/", "${romdir}/")) for p in parts ) @@ -541,9 +587,11 @@ class PackageReader: 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"]: - if 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]) + 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]: @@ -825,8 +873,8 @@ class PackageReader: if flag.startswith("-") and _mentions_bios(value) ] found += [ - tuple(token.split("=", 1)) for token in tokens - if token.startswith("-") and "=" in token and _mentions_bios(token.split("=", 1)[1]) + (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( diff --git a/scripts/scraper/rocknix_launchers.py b/scripts/scraper/rocknix_launchers.py index 73dffbc64..209aeb5dc 100644 --- a/scripts/scraper/rocknix_launchers.py +++ b/scripts/scraper/rocknix_launchers.py @@ -13,8 +13,9 @@ from __future__ import annotations import posixpath import re -from collections.abc import Callable +from collections.abc import Callable, Hashable from dataclasses import dataclass +from typing import TypeVar from .configgen_launchers import Launcher from .shell_launchers import config_placement, evidence_fields @@ -39,6 +40,8 @@ CONFIG_ROOT = "/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 @@ -68,13 +71,13 @@ def device_configs( if not re.search(rf"CONFIG=|\$\{{PKG_DIR\}}/{folder}/", body): continue offset = block.start(1) - for arm in re.finditer(r"^\s*([\w*|]+)\)(.*?);;", body, re.M | re.S): + for case_arm in re.finditer(r"^\s*([\w*|]+)\)(.*?);;", body, re.M | re.S): chosen = re.search( - rf'CONFIG="([^"]+)"|\$\{{PKG_DIR\}}/{folder}/([^/\s]+)', arm.group(2) + rf'CONFIG="([^"]+)"|\$\{{PKG_DIR\}}/{folder}/([^/\s]+)', case_arm.group(2) ) if chosen: - arms.append((arm.group(1).split("|"), chosen.group(1) or chosen.group(2))) - mk_lines.add(mk.text.count("\n", 0, offset + arm.start(2)) + 1) + 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( @@ -107,15 +110,15 @@ def per_device( tree: RepoTree, configs: list[DeviceConfig], mk_path: str, - read: Callable[[str, str], tuple[object, set[int]]], -) -> list[tuple[str | None, object, Lines]]: + 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[object, tuple[list[str], Lines]] = {} + 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, ([], [])) @@ -209,6 +212,14 @@ def _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, @@ -216,8 +227,7 @@ def config_records( file: str, passes_to_suffix: str = "", depends_on_option: str | None = None, - target: str = "", - start: Script | 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. @@ -225,11 +235,12 @@ def config_records( ``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[object, set[int]]: + def read(path: str, text: str) -> tuple[FixedPaths, set[int]]: return fixed_paths(settings(text), keys, path) records = [] @@ -251,9 +262,9 @@ def config_records( device=device, depends_on_option=depends_on_option, ), - target or f"{CONFIG_ROOT}/{posixpath.basename(package)}/{name}", + installed.target or f"{CONFIG_ROOT}/{posixpath.basename(package)}/{name}", _keys(value), - start, + installed.start, )) return records @@ -263,7 +274,7 @@ def retroarch(tree: RepoTree) -> list[Launcher]: configs = device_configs(tree, RETROARCH, "retroarch.cfg", folder="sources") wanted = ("system_directory", "systemfiles_in_content_dir") - def read(path: str, text: str) -> tuple[object, set[int]]: + 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") @@ -483,7 +494,7 @@ def melonds(tree: RepoTree) -> list[Launcher]: conf_line, conf = script.find(r'^\s*CONF_DIR="([^"]+)"', "CONF_DIR") records = config_records( tree, "melonds", package, "melonDS.ini", depends_on_option=condition, - target=f"{conf.group(1)}/melonDS.ini", start=script, unread=unread, + installed=Installed(f"{conf.group(1)}/melonDS.ini", script), unread=unread, ) for record in records: record.source_ref += ( @@ -500,7 +511,7 @@ def dsperate(tree: RepoTree) -> list[Launcher]: run_line, _ = script.find(r"/usr/bin/dsperate --config ", "dsperate --config") records = config_records( tree, "dsperate", package, "dsperate.ini", " (--config)", - target=script.expand("${DSPERATE_INI}", run_line, set()), start=script, + installed=Installed(script.expand("${DSPERATE_INI}", run_line, set()), script), ) for record in records: record.source_ref += f", {source_ref([(script.path, {run_line})])}" @@ -517,7 +528,7 @@ def xemu(tree: RepoTree) -> list[Launcher]: ) records = config_records( tree, "xemu", package, "xemu.toml", " (copied at each launch)", - target=script.expand("${CONF_DIR}/${XEMU_INI}", copy_line, set()), start=script, + 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})])}" @@ -653,7 +664,7 @@ def directory_records( configs = device_configs(tree, package, file) name = posixpath.basename(file) - def read(path: str, text: str) -> tuple[object, set[int]]: + 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]}") @@ -816,7 +827,7 @@ def patched_directories(tree: RepoTree) -> list[Launcher]: ), None, ) - if returned is 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( diff --git a/scripts/scraper/shell_launchers.py b/scripts/scraper/shell_launchers.py index 2ff53e3d8..b37e26001 100644 --- a/scripts/scraper/shell_launchers.py +++ b/scripts/scraper/shell_launchers.py @@ -116,62 +116,89 @@ def words(line: str) -> list[Word]: ended a name ("$a""b") still ends it. A "$" inside single quotes is kept as LITERAL_DOLLAR so a later expansion leaves it alone. """ - result: list[Word] = [] - raw, text, quote, started, segment = "", "", "", False, 0 - - def close_segment() -> None: - nonlocal text, segment - text = text[:segment] + re.sub(rf"\$({NAME})", r"${\1}", text[segment:]) - segment = len(text) - + lexer = _Lexer(line) i = 0 while i < len(line): - char = line[i] - if quote == "'": - raw += char - if char == "'": - quote = "" - segment = len(text) - else: - text += LITERAL_DOLLAR if char == "$" else char - elif quote == '"': - raw += char - if char == "\\" and i + 1 < len(line) and line[i + 1] in '"\\$`': - raw += line[i + 1] - text += LITERAL_DOLLAR if line[i + 1] == "$" else line[i + 1] - i += 1 - elif char == '"': - quote = "" - close_segment() - else: - text += char - elif char in "'\"": - close_segment() - quote, started = char, True - raw += char - elif char == "\\" and i + 1 < len(line): - raw += char + line[i + 1] - text += line[i + 1] - started = True - i += 1 - elif char == "#" and not started: - break - elif char.isspace() or char == ";": - if started: - close_segment() - result.append(Word(raw, text)) - raw, text, started, segment = "", "", False, 0 - if char == ";": - result.append(Word(";", ";")) + if lexer.quote == "'": + lexer.single(line[i]) + elif lexer.quote == '"': + i = lexer.double(i) else: - raw += char - text += char - started = True + step = lexer.plain(i) + if step is None: + break + i = step i += 1 - if started: - close_segment() - result.append(Word(raw, text)) - return result + 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; 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; 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 @@ -488,6 +515,58 @@ def _quoted_glob(command: str) -> bool: 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, @@ -513,43 +592,10 @@ def config_placement( for number, line in script.code(): if (copy := _COPY.search(line)) or (writer and writer.search(line)): if copy: - 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: + copied = _copy_skips(script, number, line, copy, target, source_name, sources) + if copied is None: continue - # 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):]): - continue - destination = script.expand(operands[-1], number, set()).rstrip("/") - source = script.expand(operands[0], number, set()).rstrip("/") - hits = target == destination or target.startswith(destination + "/") or ( - target.startswith(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): - continue - # 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] - ): - continue - if sources and not source.startswith(sources): - continue - # 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)]) - skip = "-n" in args or "--ignore-existing" in args or bool(prompted) + skip = copied else: skip = False install.add(number) @@ -557,9 +603,10 @@ def config_placement( 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: - if any(re.search(rf"\b{re.escape(k)}\b", expanded) for k in bare): - overrides.add(number) + 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)