diff --git a/scripts/exporter/batocera_exporter.py b/scripts/exporter/batocera_exporter.py index 565e65dfa..d361cd4f9 100644 --- a/scripts/exporter/batocera_exporter.py +++ b/scripts/exporter/batocera_exporter.py @@ -11,6 +11,8 @@ from __future__ import annotations import ast import re +from scraper.batocera_scraper import comment_start, systems_span + from .base_exporter import BaseExporter from resolve.reconcile import NativeFile, NativeSystem, Report @@ -30,34 +32,10 @@ _ITEM = re.compile(r"\{[^{}\n]*\}") _MD5_VALUE = re.compile(r'("md5"\s*:\s*)("[^"]*"|\[[^\[\]]*\])') -_STRING = re.compile(r'"(?:[^"\\\n]|\\.)*"') - - def _commented(text: str, position: int) -> bool: """Whether a '#' outside a string precedes `position` on its line.""" line_start = text.rfind("\n", 0, position) + 1 - return "#" in _STRING.sub("", text[line_start:position]) - - -def _closing_line(text: str, start: int) -> int | None: - """Index of the line holding the brace that closes `systems = {`. - - Read from the parsed module, never executed. None when the script does - not parse or names no such assignment at line `start`. - """ - try: - tree = ast.parse(text) - except SyntaxError: - return None - for node in tree.body: - if ( - isinstance(node, ast.Assign) - and node.lineno - 1 == start - and isinstance(node.value, ast.Dict) - and node.end_lineno is not None - ): - return node.end_lineno - 1 - return None + return comment_start(text[line_start:position]) is not None def _md5_subscript(node: ast.expr) -> bool: @@ -571,21 +549,13 @@ class Exporter(BaseExporter[str]): def _split_original(original: str) -> tuple[list[str], list[str], list[str]]: """Cut the script into what precedes the dict, the dict, what follows.""" lines = original.split("\n") - start = next( - (i for i, line in enumerate(lines) if line.startswith("systems = {")), - None, - ) - if start is None: - raise ValueError("batocera-systems: no systems dict found") - end = next( - (i for i in range(start + 1, len(lines)) if lines[i].startswith("}")), - None, - ) - if end is None: - # EmuELEC closes the dict with an indented brace. - end = _closing_line(original, start) - if end is None: - raise ValueError("batocera-systems: the systems dict is not closed") + try: + opening, closing = systems_span(original) + except ValueError as error: + raise ValueError(f"batocera-systems: {error}") from error + # Found by brace depth: EmuELEC indents the closing brace. + start = original.count("\n", 0, opening) + end = original.count("\n", 0, closing) return lines[: start + 1], lines[start + 1 : end], lines[end:] @staticmethod diff --git a/scripts/scraper/batocera_scraper.py b/scripts/scraper/batocera_scraper.py index 0630a1935..1b126f644 100644 --- a/scripts/scraper/batocera_scraper.py +++ b/scripts/scraper/batocera_scraper.py @@ -335,62 +335,77 @@ def _resolve_truncated_md5(md5: str, md5_index: dict[str, str]) -> str: return md5 +# `systems = {`, or `systems = OrderedDict({` as older forks write it. +_SYSTEMS_START = re.compile(r"^systems\s*=\s*(?:OrderedDict\(\s*)?\{", re.MULTILINE) + + +def comment_start(line: str) -> int | None: + """Index of the # opening a comment on `line`, strings of either quote read whole.""" + quote = None + j = 0 + while j < len(line): + ch = line[j] + if ch == "\\": + j += 2 + continue + if quote: + if ch == quote: + quote = None + elif ch in ('"', "'"): + quote = ch + elif ch == "#": + return j + j += 1 + return None + + +def _strip_comment(line: str) -> str: + """The line without a trailing # comment, strings kept whole.""" + cut = comment_start(line) + return line if cut is None else line[:cut] + + def _closing_brace(raw: str, start: int) -> int: """Index of the brace closing the one at `start`, past strings and comments.""" depth = 0 i = start - in_str = False - str_ch = None + quote = None while i < len(raw): ch = raw[i] - if in_str: + if quote: if ch == "\\": i += 2 continue - if ch == str_ch: - in_str = False + if ch == quote: + quote = None elif ch in ('"', "'"): - in_str = True - str_ch = ch + quote = ch elif ch == "{": depth += 1 elif ch == "}": depth -= 1 if depth == 0: - break + return i elif ch == "#": - while i < len(raw) and raw[i] != "\n": - i += 1 + i = raw.find("\n", i) + if i == -1: + break i += 1 - return i + raise ValueError("the systems dict is not closed") -def _strip_comment(line: str) -> str: - """The line without a trailing # comment, strings kept whole.""" - in_string = False - string_char = None - clean = [] - j = 0 - while j < len(line): - ch = line[j] - if ch == "\\" and j + 1 < len(line): - clean.append(ch) - clean.append(line[j + 1]) - j += 2 - continue - if ch in ('"', "'") and not in_string: - in_string = True - string_char = ch - clean.append(ch) - elif ch == string_char and in_string: - in_string = False - clean.append(ch) - elif ch == "#" and not in_string: - break - else: - clean.append(ch) - j += 1 - return "".join(clean) +def systems_span(raw: str) -> tuple[int, int]: + """Offsets of the opening and closing brace of the `systems` dict of a + batocera-systems script. + + Found by reading strings and comments, never by running the script. + Raises ValueError when the script assigns no such dict or never closes it. + """ + match = _SYSTEMS_START.search(raw) + if not match: + raise ValueError("no 'systems = {' in the script") + start = match.end() - 1 + return start, _closing_brace(raw, start) def extract_systems_dict(raw: str) -> dict: @@ -400,15 +415,8 @@ def extract_systems_dict(raw: str) -> dict: code. A key written twice keeps its later value, as it does when Python runs the script. """ - match = re.search(r"^systems\s*=\s*\{", raw, re.MULTILINE) - if not match: - raise ValueError("no 'systems = {' in the script") - - start = match.start() + raw[match.start() :].index("{") - dict_str = raw[start : _closing_brace(raw, start) + 1] - lines = [_strip_comment(line) for line in dict_str.split("\n")] - - clean_dict_str = "\n".join(lines) + start, end = systems_span(raw) + clean_dict_str = "\n".join(_strip_comment(line) for line in raw[start : end + 1].split("\n")) # OrderedDict({...}) -> just the inner dict literal clean_dict_str = re.sub(r"OrderedDict\(\s*\{", "{", clean_dict_str) @@ -423,7 +431,7 @@ def extract_systems_dict(raw: str) -> dict: def is_checkbios_script(raw_data: str) -> bool: """A batocera-systems script as its forks ship it: the `systems` dict of biosFiles and the checkBios that reads it.""" - has_dict = re.search(r"^systems\s*=\s*\{", raw_data, re.MULTILINE) is not None + has_dict = _SYSTEMS_START.search(raw_data) is not None return has_dict and "def checkBios" in raw_data and '"biosFiles"' in raw_data @@ -650,7 +658,7 @@ class Scraper(CheckBiosScraper): def validate_format(self, raw_data: str) -> bool: """Validate batocera-systems format.""" has_systems = "systems" in raw_data and "biosFiles" in raw_data - has_dict = re.search(r"^systems\s*=\s*\{", raw_data, re.MULTILINE) is not None + has_dict = _SYSTEMS_START.search(raw_data) is not None has_md5 = '"md5"' in raw_data has_file = '"file"' in raw_data return has_systems and has_dict and has_md5 and has_file diff --git a/tests/test_batocera_cores.py b/tests/test_batocera_cores.py index 3c0cfaacc..662818789 100644 --- a/tests/test_batocera_cores.py +++ b/tests/test_batocera_cores.py @@ -243,3 +243,46 @@ class APatchedLibretroBuildTakesItsNameOnly(unittest.TestCase): if __name__ == "__main__": unittest.main() + + +class OneLocatorFindsTheSystemsDict(unittest.TestCase): + """The scraper and the exporter cut batocera-systems at the same braces.""" + + SCRIPT = ( + "import os\n" + "systems = OrderedDict({\n" + " 'a': { 'name': 'it''s }', \"biosFiles\": [ # } in a comment\n" + " { \"md5\": \"x\", \"file\": 'bios/#a.bin' } ] },\n" + " })\n" + "def checkBios(): pass\n" + ) + + def test_the_braces_are_read_past_strings_and_comments(self): + from scripts.scraper.batocera_scraper import extract_systems_dict, systems_span + + start, end = systems_span(self.SCRIPT) + self.assertEqual(self.SCRIPT[start], "{") + self.assertEqual(self.SCRIPT[end:end + 2], "})") + self.assertEqual(extract_systems_dict(self.SCRIPT)["a"]["biosFiles"][0]["file"], "bios/#a.bin") + + def test_the_exporter_cuts_at_the_same_lines(self): + from exporter.batocera_exporter import Exporter + + head, body, tail = Exporter._split_original(self.SCRIPT) + self.assertEqual(head[-1], "systems = OrderedDict({") + self.assertEqual(len(body), 2) + self.assertEqual(tail[0], " })") + + def test_a_comment_starts_outside_either_quote(self): + from scripts.scraper.batocera_scraper import comment_start + + self.assertIsNone(comment_start("'a#b', \"c#d\"")) + self.assertEqual(comment_start("'a#b' # note"), 6) + + def test_an_unclosed_dict_is_refused(self): + from scripts.scraper.batocera_scraper import systems_span + + with self.assertRaisesRegex(ValueError, "not closed"): + systems_span("systems = {\n 'a': {}\n") + with self.assertRaisesRegex(ValueError, "no 'systems = {'"): + systems_span("other = {}\n")