From 4fdc1001978325c14e9472160e77c9632cbea890 Mon Sep 17 00:00:00 2001 From: Abdessamad Derraz <3028866+Abdess@users.noreply.github.com> Date: Tue, 17 Nov 2026 07:35:02 +0100 Subject: [PATCH] refactor: type romfolders and hash tooling --- scripts/scraper/_hash_merge.py | 145 +++++++++++++------------ scripts/scraper/dat_pack_importer.py | 2 +- scripts/scraper/dat_parser.py | 2 +- scripts/scraper/fbneo_hash_scraper.py | 6 +- scripts/scraper/game_dat_importer.py | 13 +-- scripts/scraper/mame_hash_scraper.py | 13 ++- scripts/scraper/mame_parser.py | 3 +- scripts/scraper/romfolders/__init__.py | 7 +- scripts/scraper/romfolders/card.py | 24 ++-- scripts/scraper/romfolders/es.py | 81 ++++++++------ 10 files changed, 161 insertions(+), 135 deletions(-) diff --git a/scripts/scraper/_hash_merge.py b/scripts/scraper/_hash_merge.py index b83531a83..4ce66daba 100644 --- a/scripts/scraper/_hash_merge.py +++ b/scripts/scraper/_hash_merge.py @@ -461,6 +461,82 @@ def _patch_scalar(text: str, key: str, value: str) -> str: ) +def _owned_end(lines: list[str], start_line: int) -> int: + """The last "owned" line of the entry starting at start_line. + + Owned = indented with 4+ spaces (field lines of this entry). + """ + last_owned = start_line + for j in range(start_line + 1, len(lines)): + stripped = lines[j].strip() + if not stripped: + break # blank line = end of entry + if stripped.startswith("#"): + break # comment = belongs to next entry + if re.match(r"^ - ", lines[j]): + break # next list item + if re.match(r"^ ", lines[j]) or re.match(r"^ \w", lines[j]): + last_owned = j + else: + break + return last_owned + + +def _patch_source_ref(lines: list[str], start_line: int, last_owned: int, source_ref: str) -> int: + """Patch source_ref in-place, or add it. Returns the new last owned line.""" + for j in range(start_line + 1, last_owned + 1): + if re.match(r"^ source_ref:", lines[j]): + lines[j] = f' source_ref: "{source_ref}"' + return last_owned + lines.insert(last_owned + 1, f' source_ref: "{source_ref}"') + return last_owned + 1 + + +def _drop_contents(lines: list[str], start_line: int, last_owned: int) -> int: + """Remove an existing contents block. Returns the new last owned line.""" + contents_start = None + contents_end = None + for j in range(start_line + 1, last_owned + 1): + if re.match(r"^ contents:", lines[j]): + contents_start = j + elif contents_start is not None: + if re.match(r"^ ", lines[j]): + contents_end = j + else: + break + if contents_start is None: + return last_owned + if contents_end is None: + contents_end = contents_start + del lines[contents_start : contents_end + 1] + return last_owned - (contents_end - contents_start + 1) + + +def _patch_entry(lines: list[str], start_line: int, fe: dict) -> None: + contents = fe.get("contents", []) + source_ref = fe.get("source_ref", "") + + last_owned = _owned_end(lines, start_line) + + if source_ref: + last_owned = _patch_source_ref(lines, start_line, last_owned, source_ref) + + # The source settles required for a set the machine runs without + if "required" in fe: + for j in range(start_line + 1, last_owned + 1): + if re.match(r"^ required:", lines[j]): + lines[j] = f" required: {str(fe['required']).lower()}" + break + + last_owned = _drop_contents(lines, start_line, last_owned) + + # Insert new contents after last owned line + if contents: + new_lines = _format_contents(contents).split("\n") + for k, cl in enumerate(new_lines): + lines.insert(last_owned + 1 + k, cl) + + def _patch_bios_entries(text: str, files: list[dict]) -> str: """Patch contents, source_ref and required of bios_zip entries in-place. @@ -469,8 +545,6 @@ def _patch_bios_entries(text: str, files: list[dict]) -> str: lines that follow (4+ spaces), stopping at blank lines, comments, or the next `- name:`. """ - import re - patches: dict[str, dict] = {} for fe in files: if fe.get("category") != "bios_zip": @@ -491,71 +565,8 @@ def _patch_bios_entries(text: str, files: list[dict]) -> str: # Process in reverse so line insertions don't shift indices for idx in range(len(entry_starts) - 1, -1, -1): start_line, entry_name = entry_starts[idx] - if entry_name not in patches: - continue - - fe = patches[entry_name] - contents = fe.get("contents", []) - source_ref = fe.get("source_ref", "") - - # Find the last "owned" line of this entry - # Owned = indented with 4+ spaces (field lines of this entry) - last_owned = start_line - for j in range(start_line + 1, len(lines)): - stripped = lines[j].strip() - if not stripped: - break # blank line = end of entry - if stripped.startswith("#"): - break # comment = belongs to next entry - if re.match(r"^ - ", lines[j]): - break # next list item - if re.match(r"^ ", lines[j]) or re.match(r"^ \w", lines[j]): - last_owned = j - else: - break - - # Patch source_ref in-place - if source_ref: - found_sr = False - for j in range(start_line + 1, last_owned + 1): - if re.match(r"^ source_ref:", lines[j]): - lines[j] = f' source_ref: "{source_ref}"' - found_sr = True - break - if not found_sr: - lines.insert(last_owned + 1, f' source_ref: "{source_ref}"') - last_owned += 1 - - # The source settles required for a set the machine runs without - if "required" in fe: - for j in range(start_line + 1, last_owned + 1): - if re.match(r"^ required:", lines[j]): - lines[j] = f" required: {str(fe['required']).lower()}" - break - - # Remove existing contents block if present - contents_start = None - contents_end = None - for j in range(start_line + 1, last_owned + 1): - if re.match(r"^ contents:", lines[j]): - contents_start = j - elif contents_start is not None: - if re.match(r"^ ", lines[j]): - contents_end = j - else: - break - if contents_end is None and contents_start is not None: - contents_end = contents_start - - if contents_start is not None: - del lines[contents_start : contents_end + 1] - last_owned -= contents_end - contents_start + 1 - - # Insert new contents after last owned line - if contents: - new_lines = _format_contents(contents).split("\n") - for k, cl in enumerate(new_lines): - lines.insert(last_owned + 1 + k, cl) + if entry_name in patches: + _patch_entry(lines, start_line, patches[entry_name]) return "\n".join(lines) diff --git a/scripts/scraper/dat_pack_importer.py b/scripts/scraper/dat_pack_importer.py index 33dc62bb9..d89699da4 100644 --- a/scripts/scraper/dat_pack_importer.py +++ b/scripts/scraper/dat_pack_importer.py @@ -77,7 +77,7 @@ def import_pack(source: str, pack: Path) -> tuple[dict, list[dict], int]: dats = {} entries = [] skipped = 0 - for member, content in _iter_dat_contents(pack): + for _member, content in _iter_dat_contents(pack): try: dat = parse_logiqx(content) except (ValueError, SyntaxError): diff --git a/scripts/scraper/dat_parser.py b/scripts/scraper/dat_parser.py index 07160f9e1..6a2784b4a 100644 --- a/scripts/scraper/dat_parser.py +++ b/scripts/scraper/dat_parser.py @@ -61,7 +61,7 @@ def parse_dat(content: str) -> list[DatRom]: continue current_system = value - elif stripped.startswith("rom (") or stripped.startswith("rom("): + elif stripped.startswith(("rom (", "rom(")): rom = _parse_rom_line(stripped, current_system) if rom: roms.append(rom) diff --git a/scripts/scraper/fbneo_hash_scraper.py b/scripts/scraper/fbneo_hash_scraper.py index 17ac95a43..1f1fea97c 100644 --- a/scripts/scraper/fbneo_hash_scraper.py +++ b/scripts/scraper/fbneo_hash_scraper.py @@ -196,12 +196,10 @@ def _format_diff( return "\n".join(lines) if show_added: - for label in added: - lines.append(f" + {label}") + lines.extend(f" + {label}" for label in added) elif added: lines.append(f" + {len(added)} new ROMs available (main profile only)") - for label in updated: - lines.append(f" ~ {label}") + lines.extend(f" ~ {label}" for label in updated) lines.append(f" = {diff['unchanged']} unchanged") if oos: lines.append(f" . {oos} out of scope") diff --git a/scripts/scraper/game_dat_importer.py b/scripts/scraper/game_dat_importer.py index ecff9f160..c4bb05605 100644 --- a/scripts/scraper/game_dat_importer.py +++ b/scripts/scraper/game_dat_importer.py @@ -36,16 +36,15 @@ from dataclasses import dataclass from datetime import datetime, timezone from pathlib import Path -_SCRIPTS_DIR = str(Path(__file__).resolve().parents[1]) -if _SCRIPTS_DIR not in sys.path: +if (_SCRIPTS_DIR := str(Path(__file__).resolve().parents[1])) not in sys.path: sys.path.insert(0, _SCRIPTS_DIR) -from artifacts import copy_stream_atomic, write_if_changed, write_text_atomic # noqa: E402 -from common import parse_untrusted_xml # noqa: E402 -from region import REGIONS, WORLD # noqa: E402 -from region_audit import NOINTRO # noqa: E402 +from artifacts import copy_stream_atomic, write_if_changed, write_text_atomic +from common import parse_untrusted_xml +from region import REGIONS, WORLD +from region_audit import NOINTRO -from .base_scraper import github_headers # noqa: E402 +from .base_scraper import github_headers SOURCES = ("no-intro", "redump") CACHE_DIR = Path(".cache") / "game-dats" diff --git a/scripts/scraper/mame_hash_scraper.py b/scripts/scraper/mame_hash_scraper.py index 28557323b..c6e71dc91 100644 --- a/scripts/scraper/mame_hash_scraper.py +++ b/scripts/scraper/mame_hash_scraper.py @@ -303,8 +303,7 @@ def _format_diff( elif added: lines.append(f" + {len(added)} new sets available (main profile only)") - for set_name in updated: - lines.append(f" ~ {set_name}.zip (refreshed)") + lines.extend(f" ~ {set_name}.zip (refreshed)" for set_name in updated) oos = diff.get("out_of_scope", 0) lines.append(f" = {unchanged} unchanged") @@ -318,9 +317,9 @@ def _format_diff( def _fetch_hashes(force: bool) -> dict[str, Any]: cache = _load_cache() - if not force and not _is_stale(cache): + if not force and cache is not None and not _is_stale(cache): log.info("using cached data from %s", cache.get("fetched_at", "")) - return cache # type: ignore[return-value] + return cache try: tag = _get_release_tag() @@ -540,8 +539,10 @@ def _platform_archives() -> list[tuple[str, str]]: for name in list_registered_platforms(str(_PLATFORMS_DIR)): config = load_platform_config(name, str(_PLATFORMS_DIR)) for system, data in (config.get("systems") or {}).items(): - for entry in (data or {}).get("files") or []: - stated.append((str(entry.get("name") or ""), str(system))) + stated.extend( + (str(entry.get("name") or ""), str(system)) + for entry in (data or {}).get("files") or [] + ) return stated diff --git a/scripts/scraper/mame_parser.py b/scripts/scraper/mame_parser.py index e87daf195..baef20ee6 100644 --- a/scripts/scraper/mame_parser.py +++ b/scripts/scraper/mame_parser.py @@ -398,8 +398,7 @@ def _parse_rom_entries(block: str, keep_no_dump: bool = False) -> list[dict]: events: list[tuple[int, str, re.Match]] = [] for tag, pat in token_patterns: - for m in pat.finditer(block): - events.append((m.start(), tag, m)) + events.extend((m.start(), tag, m) for m in pat.finditer(block)) # Walked in source order: a ROM_LOAD belongs to the last ROM_REGION above it. events.sort(key=lambda e: e[0]) diff --git a/scripts/scraper/romfolders/__init__.py b/scripts/scraper/romfolders/__init__.py index 2c549e32b..b5b4923f5 100644 --- a/scripts/scraper/romfolders/__init__.py +++ b/scripts/scraper/romfolders/__init__.py @@ -20,12 +20,11 @@ from collections.abc import Callable from dataclasses import dataclass, field from pathlib import Path -_SCRIPTS_DIR = str(Path(__file__).resolve().parents[2]) -if _SCRIPTS_DIR not in sys.path: +if (_SCRIPTS_DIR := str(Path(__file__).resolve().parents[2])) not in sys.path: sys.path.insert(0, _SCRIPTS_DIR) -import upstream # noqa: E402 -from safeparse import yaml_load # noqa: E402 +import upstream +from safeparse import yaml_load CACHE_DIR = upstream.CACHE_DIR diff --git a/scripts/scraper/romfolders/card.py b/scripts/scraper/romfolders/card.py index e910e206e..b1b5ed4fd 100644 --- a/scripts/scraper/romfolders/card.py +++ b/scripts/scraper/romfolders/card.py @@ -208,14 +208,20 @@ def parse_crossmix(spec: dict, fetcher: Fetcher) -> list[dict]: # Koriki +class _CaseConfigParser(ConfigParser): + """Option names kept as written: Koriki's keys are case-sensitive.""" + + def optionxform(self, optionstr: str) -> str: + return optionstr + + @register("koriki") def parse_koriki(spec: dict, fetcher: Fetcher) -> list[dict]: params = spec["params"] key = params["source"] path = params["sections"] text = fetcher.text(key, path) - parser = ConfigParser(interpolation=None, strict=False) - parser.optionxform = str # type: ignore[assignment] + parser = _CaseConfigParser(interpolation=None, strict=False) parser.read_string(text) skip = set(params.get("skip", [])) rows = [] @@ -353,8 +359,8 @@ def parse_minui(spec: dict, fetcher: Fetcher) -> list[dict]: match = re.match(r"^skeleton/[^/]+/Roms/([^/]+)/", path) if match: name = match.group(1) - tag = re.search(r"\(([^()]*)\)\s*$", name) - shipped.setdefault(tag.group(1) if tag else name, name) + paren = re.search(r"\(([^()]*)\)\s*$", name) + shipped.setdefault(paren.group(1) if paren else name, name) paks: dict[str, dict[str, tuple[str, str]]] = {} for path in tree: match = _PAK.match(path) @@ -492,12 +498,12 @@ def parse_gmenu2x(spec: dict, fetcher: Fetcher) -> list[dict]: } key = params["source"] for path in fetcher.tree(key, params["shipped_roms"] + "/"): - folder = path[len(params["shipped_roms"]) + 1:].split("/") - if len(folder) < 2 or folder[0] in rows: + parts = path[len(params["shipped_roms"]) + 1:].split("/") + if len(parts) < 2 or parts[0] in rows: continue - rows[folder[0]] = { - "folder": folder[0], - "source_ref": ref(key, f"{params['shipped_roms']}/{folder[0]}"), + rows[parts[0]] = { + "folder": parts[0], + "source_ref": ref(key, f"{params['shipped_roms']}/{parts[0]}"), "note": "folder the image ships. Its emulator link lives in a release package no repository holds", } return list(rows.values()) diff --git a/scripts/scraper/romfolders/es.py b/scripts/scraper/romfolders/es.py index 2d3a3f6c7..a6f9d84be 100644 --- a/scripts/scraper/romfolders/es.py +++ b/scripts/scraper/romfolders/es.py @@ -160,8 +160,8 @@ def batocera_es(spec: dict, fetcher: Fetcher) -> list[dict]: continue if not system.get("emulators") and not system.get("force"): continue - path = system.get("path", name) - if not path or str(path).startswith("/"): + folder = system.get("path", name) + if not folder or str(folder).startswith("/"): continue base = defaults.get(name) or {} emulator, core = base.get("emulator"), base.get("core") @@ -175,7 +175,7 @@ def batocera_es(spec: dict, fetcher: Fetcher) -> list[dict]: if name in def_lines: refs.append(_ref(key, def_path, def_lines[name])) rows.append({ - "folder": str(path), + "folder": str(folder), "name": name, "extensions": _extensions(system.get("extensions")), "core": str(core) if core else None, @@ -393,6 +393,40 @@ def _conf_values(text: str) -> tuple[dict[str, str], dict[str, int]]: return values, lines +def _nesting(line: str, stack: list[list[str]]) -> bool: + """Follow case and if nesting. True when the line is consumed.""" + match = re.match(r'case\s+"?\$\{?(\w+)\}?"?\s+in', line) + if match: + stack.append(["case", match.group(1), ""]) + return True + if line == "esac": + stack.pop() + return True + if line.startswith("if ") or line.startswith("[") and "&&" not in line and line.endswith("then"): + stack.append(["if", line, ""]) + return True + if line in ("fi",): + if stack and stack[-1][0] == "if": + stack.pop() + return True + return line in ("then", "else") or line.startswith("elif ") + + +def _record_call( + words: list[str], number: int, stack: list[list[str]], + cores: list[dict], systems: dict[str, list[int]], +) -> None: + branches = [(s[1], s[2]) for s in stack] + if words[:1] == ["add_emu_core"] and len(words) >= 4: + cores.append({ + "system": words[1], "emulator": words[2], "core": words[3], + "default": len(words) > 4 and words[4] == "true", + "branches": branches, "line": number, + }) + elif words[:1] == ["add_es_system"] and len(words) >= 2: + systems.setdefault(words[1], []).append(number) + + def _package_calls(text: str) -> tuple[list[dict], dict[str, list[int]]]: """add_emu_core and add_es_system calls of makeinstall_target, each with the `case` branches it sits under as (variable, pattern) pairs. @@ -412,21 +446,7 @@ def _package_calls(text: str) -> tuple[list[dict], dict[str, list[int]]]: continue if raw.startswith("}"): break - match = re.match(r'case\s+"?\$\{?(\w+)\}?"?\s+in', line) - if match: - stack.append(["case", match.group(1), ""]) - continue - if line == "esac": - stack.pop() - continue - if line.startswith("if ") or line.startswith("[") and "&&" not in line and line.endswith("then"): - stack.append(["if", line, ""]) - continue - if line in ("fi",): - if stack and stack[-1][0] == "if": - stack.pop() - continue - if line in ("then", "else") or line.startswith("elif "): + if _nesting(line, stack): continue ends = line.endswith(";;") if ends: @@ -436,16 +456,7 @@ def _package_calls(text: str) -> tuple[list[dict], dict[str, list[int]]]: if match and not line.startswith(("add_", "[", "sed", "cp", "mkdir")): stack[-1][2] = match.group(1).strip() line = match.group(2).strip() - words = line.split() - branches = [(s[1], s[2]) for s in stack] - if words[:1] == ["add_emu_core"] and len(words) >= 4: - cores.append({ - "system": words[1], "emulator": words[2], "core": words[3], - "default": len(words) > 4 and words[4] == "true", - "branches": branches, "line": number, - }) - elif words[:1] == ["add_es_system"] and len(words) >= 2: - systems.setdefault(words[1], []).append(number) + _record_call(line.split(), number, stack, cores, systems) if ends and stack and stack[-1][0] == "case": stack[-1][2] = "" return cores, systems @@ -487,7 +498,8 @@ def elec_conf(spec: dict, fetcher: Fetcher) -> list[dict]: flagged = [c for c in mine if c["default"]] plain = [c for c in flagged if not c["branches"]] star = [c for c in flagged if c["branches"] and c["branches"][-1][1] == "*"] - pick = (plain or star or flagged or [None])[0] + candidates = plain or star or flagged + pick: dict | None = candidates[0] if candidates else None if pick is None: pick = next((c for c in mine if not c["branches"]), mine[0] if mine else None) board_defaults = {} @@ -861,10 +873,11 @@ def recalbox(spec: dict, fetcher: Fetcher) -> list[dict]: core, core_line = _recalbox_get(sections, lines, section, "core", board) emulator, _ = _recalbox_get(sections, lines, section, "emulator", board) exts, _ = _recalbox_get(sections, lines, section, "extensions", board) - if (exts or "").startswith(_FILES_PREFIX): - names.update(_recalbox_names(exts[len(_FILES_PREFIX):])) + listed = exts or "" + if listed.startswith(_FILES_PREFIX): + names.update(_recalbox_names(listed[len(_FILES_PREFIX):])) else: - extensions.update((exts or "").split()) + extensions.update(listed.split()) cores.append({ "core": core, "emulator": emulator, "priority": int(priority or "255"), "source_ref": "; ".join([ @@ -968,8 +981,8 @@ def retropie(spec: dict, fetcher: Fetcher) -> list[dict]: cfg_path = params["platforms_cfg"] cfg = fetcher.text(key, cfg_path) exts: dict[str, tuple[str, int]] = {} - for number, line in enumerate(cfg.splitlines(), 1): - match = re.match(r'^([\w-]+)_exts="([^"]*)"', line) + for number, cfg_line in enumerate(cfg.splitlines(), 1): + match = re.match(r'^([\w-]+)_exts="([^"]*)"', cfg_line) if match: exts[match.group(1)] = (match.group(2), number) platform = set(params["platform_flags"])