From 238f70c7a7461d2ca18fa59b9f2d61c84996ec28 Mon Sep 17 00:00:00 2001 From: Abdessamad Derraz <3028866+Abdess@users.noreply.github.com> Date: Wed, 18 Nov 2026 22:16:55 +0100 Subject: [PATCH] refactor: one copy of each duplicated helper --- .github/workflows/deploy-site.yml | 1 + scripts/model/registry.py | 13 ++++++++++++ scripts/model/sourceref.py | 4 ++++ scripts/packs/crossref.py | 19 ++++++----------- scripts/packs/datadirs.py | 10 +-------- scripts/resolve/regions.py | 17 ++-------------- scripts/scraper/buildbot_system.py | 15 ++------------ scripts/scraper/csharp_source.py | 8 +++----- scripts/scraper/retrodeck_launchers.py | 28 ++++++++++---------------- scripts/scraper/shell_launchers.py | 6 ++---- tests/test_refresh_data_dirs.py | 7 ++++--- 11 files changed, 49 insertions(+), 79 deletions(-) diff --git a/.github/workflows/deploy-site.yml b/.github/workflows/deploy-site.yml index 99388aa40..5c4813576 100644 --- a/.github/workflows/deploy-site.yml +++ b/.github/workflows/deploy-site.yml @@ -96,6 +96,7 @@ on: - "scripts/resolve/reconcile.py" - "scripts/resolve/regions.py" - "scripts/resolve/review.py" + - "scripts/resolve/slot.py" - "scripts/resolve/standalone.py" - "scripts/resolve/truth.py" - "scripts/resolve/validation.py" diff --git a/scripts/model/registry.py b/scripts/model/registry.py index 707cb9220..d8e3672be 100644 --- a/scripts/model/registry.py +++ b/scripts/model/registry.py @@ -2,7 +2,9 @@ from __future__ import annotations +import json import os +from pathlib import Path from core.cli import InputMissing from model.sources import source_yaml @@ -67,3 +69,14 @@ def list_release_pack_platforms(platforms_dir: str = "platforms") -> list[str]: for name in list_registered_platforms(platforms_dir) if registry.get(name, {}).get("release_pack") is True ] + + +VERSIONS_FILE = "data/.versions.json" + + +def _load_versions(versions_path: str = VERSIONS_FILE) -> dict[str, dict]: + path = Path(versions_path) + if not path.exists(): + return {} + with open(path) as f: + return json.load(f) diff --git a/scripts/model/sourceref.py b/scripts/model/sourceref.py index f2e202a3c..e5a659821 100644 --- a/scripts/model/sourceref.py +++ b/scripts/model/sourceref.py @@ -536,3 +536,7 @@ def _prose_path( before.rfind("(")) + 1:] path = f"{word} {path}" return path, role, path_start, (path_start, match.end("path")) + + +def span(first: int, last: int) -> str: + return str(first) if first == last else f"{first}-{last}" diff --git a/scripts/packs/crossref.py b/scripts/packs/crossref.py index 08d16d81e..5f95ed792 100644 --- a/scripts/packs/crossref.py +++ b/scripts/packs/crossref.py @@ -21,6 +21,7 @@ from model.declarations import OUTER_ROOTS from model.platforms import load_platform_config from model.registry import list_registered_platforms, load_data_dir_registry from model.systems import _norm_system_id +from packs.gaps import _gap_destination from resolve.archives import archive_entry from resolve.content import content_fits, name_match_size_ok from resolve.directories import directory_members, expand_directory_entries @@ -720,18 +721,6 @@ def profile_breakdown(data: dict) -> str: return ", ".join(parts) -def _effective_path(f: dict, fname: str, is_standalone: bool, save_root: bool) -> str: - # The destination the running build reads, as find_undeclared_files - # takes it: Batocera's standalone Cemu reads keys.txt at - # standalone_path, and the libretro Cemu/keys.txt reported here - # settled the declaration on a slot the platform never fills. - if is_standalone: - return f.get("standalone_path") or f.get("path") or fname - if save_root: - return f.get("path") or fname - return system_dir_path(f, f.get("path") or fname) - - @dataclass class _ProfileComparison: """One profile's entries against the platforms' declarations.""" @@ -768,7 +757,11 @@ class _ProfileComparison: fname = f.get("name", "") platform = self.platform save_root = read_from_save_dir(f, is_standalone) - effective_path = _effective_path(f, fname, is_standalone, save_root) + # The destination the running build reads, as find_undeclared_files + # takes it: Batocera's standalone Cemu reads keys.txt at + # standalone_path, and the libretro Cemu/keys.txt reported here + # settled the declaration on a slot the platform never fills. + effective_path = _gap_destination(f, fname, is_standalone, save_root) slot = slot_key(f, is_standalone) seen_key = slot if len(self.layouts) > 1: diff --git a/scripts/packs/datadirs.py b/scripts/packs/datadirs.py index 01945b454..aa866c1b7 100644 --- a/scripts/packs/datadirs.py +++ b/scripts/packs/datadirs.py @@ -24,12 +24,12 @@ from core.artifacts import file_lock as _file_lock, set_plain_mode from core.cli import InputMissing from core.github import github_token from model.safeparse import yaml_load +from model.registry import VERSIONS_FILE, _load_versions log = logging.getLogger(__name__) DEFAULT_REGISTRY = "platforms/_data_dirs.yml" -VERSIONS_FILE = "data/.versions.json" USER_AGENT = "retrobios/1.0" REQUEST_TIMEOUT = 30 DOWNLOAD_TIMEOUT = 300 @@ -125,14 +125,6 @@ def hold_data_dirs(stack: contextlib.ExitStack, registry: dict) -> None: stack.enter_context(cache_lock(cache, shared=True)) -def _load_versions(versions_path: str = VERSIONS_FILE) -> dict[str, dict]: - path = Path(versions_path) - if not path.exists(): - return {} - with open(path) as f: - return json.load(f) - - def _save_versions( versions: dict[str, dict], versions_path: str = VERSIONS_FILE ) -> None: diff --git a/scripts/resolve/regions.py b/scripts/resolve/regions.py index 7cc271f48..cce718132 100644 --- a/scripts/resolve/regions.py +++ b/scripts/resolve/regions.py @@ -3,6 +3,7 @@ from __future__ import annotations from model.region import WORLD, normalize_declared, rank +from resolve.slot import lookup_slot def platform_region_index( @@ -90,27 +91,13 @@ def lookup_regions(index: dict[str, dict], destination: str, name: str) -> set[s return set(entry["regions"]) -def _index_entry(index: dict[str, dict], destination: str, name: str) -> dict | None: - """The index entry a candidate resolves to, by the lookup_regions order.""" - if destination: - entry = index.get(destination) - if entry: - return entry - parts = destination.split("/") - for i in range(1, len(parts)): - entry = index.get("/".join(parts[i:])) - if entry: - return entry - return index.get(name) - - def lookup_priority(index: dict[str, dict], destination: str, name: str) -> int | None: """The search rank the code gives a candidate, lower first. None when no entry declares one, or when two declarations disagree: a rank in doubt cannot decide what to drop. """ - entry = _index_entry(index, destination, name) + entry = lookup_slot(index, destination, name) priorities = (entry or {}).get("priorities", set()) if len(priorities) != 1: return None diff --git a/scripts/scraper/buildbot_system.py b/scripts/scraper/buildbot_system.py index 76762acea..ca2385f13 100644 --- a/scripts/scraper/buildbot_system.py +++ b/scripts/scraper/buildbot_system.py @@ -3,16 +3,15 @@ from __future__ import annotations import importlib.util -import json import logging import subprocess import sys import urllib.error import urllib.parse import urllib.request -from pathlib import Path from model.safeparse import yaml_load +from model.registry import _load_versions log = logging.getLogger(__name__) @@ -23,7 +22,6 @@ USER_AGENT = "retrobios/1.0" REQUEST_TIMEOUT = 15 DEFAULT_REGISTRY = "platforms/_data_dirs.yml" -VERSIONS_FILE = "data/.versions.json" def fetch_index() -> set[str]: @@ -69,15 +67,6 @@ def get_remote_etag(url: str) -> str | None: return None -def load_versions(versions_path: str = VERSIONS_FILE) -> dict: - """Load cached version/ETag data.""" - path = Path(versions_path) - if not path.exists(): - return {} - with open(path) as f: - return json.load(f) - - def check(registry_path: str = DEFAULT_REGISTRY) -> dict: """Run the buildbot check. Returns structured report.""" try: @@ -87,7 +76,7 @@ def check(registry_path: str = DEFAULT_REGISTRY) -> dict: return {"error": str(exc), "entries": []} tracked = load_tracked_entries(registry_path) - versions = load_versions() + versions = _load_versions() buildbot_set = set(index_zips) tracked_set = set(tracked.keys()) diff --git a/scripts/scraper/csharp_source.py b/scripts/scraper/csharp_source.py index 53a19689c..fea304b44 100644 --- a/scripts/scraper/csharp_source.py +++ b/scripts/scraper/csharp_source.py @@ -8,6 +8,8 @@ import bisect import re from collections.abc import Iterator +from model.sourceref import span + STRING = r'"((?:[^"\\\n]|\\.)*)"' Record = dict[str, object] @@ -143,10 +145,6 @@ def _unique(names: list[str]) -> list[str]: return list(dict.fromkeys(names)) -def _span(first: int, last: int) -> str: - return str(first) if first == last else f"{first}-{last}" - - def _merge(spans: list[tuple[int, int]]) -> list[tuple[int, int]]: """Spans sorted, joined when only one line separates them.""" merged: list[tuple[int, int]] = [] @@ -162,7 +160,7 @@ def source_ref(*parts: tuple[str, list[tuple[int, int]]]) -> str: """path:a-b, c-d for each file, a later range of one file left bare.""" refs = [] for path, spans in parts: - ranges = [_span(*s) for s in _merge(spans)] + ranges = [span(*s) for s in _merge(spans)] refs.append(f"{path}:{', '.join(ranges)}") return ", ".join(refs) diff --git a/scripts/scraper/retrodeck_launchers.py b/scripts/scraper/retrodeck_launchers.py index 120540f96..8f494d943 100644 --- a/scripts/scraper/retrodeck_launchers.py +++ b/scripts/scraper/retrodeck_launchers.py @@ -18,12 +18,18 @@ platform file without a word. from __future__ import annotations import re -import shlex from collections.abc import Callable from pathlib import PurePosixPath from typing import Any -from .retropie_launchers import Launcher, LauncherPatternMissing, merge_records, source_ref +from .retropie_launchers import ( + Launcher, + LauncherPatternMissing, + _split, + _split_path, + merge_records, + source_ref, +) BIOS = "$bios_path" PLACEHOLDER = "RETRODECKBIOSDIR" @@ -49,22 +55,10 @@ HOUSEKEEPING = frozenset({"create_dir", "log", "mkdir", "chmod", "rm", "unlink"} Read = Callable[[str], "str | None"] -def _words(text: str) -> list[str]: - try: - return shlex.split(text, comments=True) - except ValueError: - return text.split() - - def _unquote(value: str) -> str: return value.strip().strip("'\"") -def _split_path(path: str) -> tuple[str, str]: - pure = PurePosixPath(path.rstrip("/")) - return str(pure.parent), pure.name - - def _is_file(path: str) -> bool: return bool(_EXTENSION.search(PurePosixPath(path).name)) @@ -105,7 +99,7 @@ class Script: continue shown = [c for c in branches if "$action" not in c] for part in re.split(r"\s+&&\s+|\s+\|\|\s+", stripped): - words = _words(part) + words = _split(part) if words: found.append((number, words, part, shown)) return found @@ -306,7 +300,7 @@ class Component: substitutions = self._substitutions(script, target) copied = None for line_no, line in enumerate(script.lines[:number], 1): - cp = _words(line.strip().split("&&")[0]) + 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: @@ -524,7 +518,7 @@ def core_options(read: Read) -> list[Launcher]: ] if not copied: raise LauncherPatternMissing(prepare_path, "the core options preset is never copied") - target = _words(prepare.splitlines()[copied[0] - 1].strip())[-1] + 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()) diff --git a/scripts/scraper/shell_launchers.py b/scripts/scraper/shell_launchers.py index d31193925..a1f2ef917 100644 --- a/scripts/scraper/shell_launchers.py +++ b/scripts/scraper/shell_launchers.py @@ -15,6 +15,8 @@ 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_headers from .configgen_launchers import LauncherShapeError @@ -33,10 +35,6 @@ class LauncherPatternMissing(LauncherShapeError): super().__init__(f"{path}: {what} not found") -def span(first: int, last: int) -> str: - return str(first) if first == last else f"{first}-{last}" - - 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]] = [] diff --git a/tests/test_refresh_data_dirs.py b/tests/test_refresh_data_dirs.py index b549e5c76..089d2285d 100644 --- a/tests/test_refresh_data_dirs.py +++ b/tests/test_refresh_data_dirs.py @@ -22,6 +22,7 @@ from unittest import mock import refresh_data_dirs as rdd from packs import datadirs +from model.registry import _load_versions from packs.datatrees import _data_directory_members REPO_ROOT = Path(__file__).resolve().parents[1] @@ -105,12 +106,12 @@ class RefreshConcurrency(unittest.TestCase): lambda *a, **k: _Response(payload)), \ mock.patch.object(datadirs, "_get_remote_etag", return_value="e1"): self.assertTrue(datadirs.refresh_entry("pak", entry, versions_path=self.versions)) - self.assertEqual(datadirs._load_versions(self.versions)["pak"]["archive_size"], + self.assertEqual(_load_versions(self.versions)["pak"]["archive_size"], len(payload)) datadirs._record_version("pak", {"sha": "e1"}, self.versions) (self.cache / "a.bin").write_bytes(b"kept") self.assertFalse(datadirs.refresh_entry("pak", entry, versions_path=self.versions)) - self.assertEqual(datadirs._load_versions(self.versions)["pak"], + self.assertEqual(_load_versions(self.versions)["pak"], {"sha": "e1", "archive_size": len(payload)}) self.assertEqual((self.cache / "a.bin").read_bytes(), b"kept") @@ -187,7 +188,7 @@ class RefreshConcurrency(unittest.TestCase): thread.start() for thread in threads: thread.join() - self.assertEqual(sorted(datadirs._load_versions(self.versions)), sorted(keys)) + self.assertEqual(sorted(_load_versions(self.versions)), sorted(keys)) class PackWalkHoldsTheCache(unittest.TestCase):