refactor: one copy of each duplicated helper

This commit is contained in:
Abdessamad Derraz committed 2026-11-18 22:16:55 +01:00
1 parent 2c8a9cfad8
commit 238f70c7a7
11 files changed
+49 -79

No files matched your search

+1
View File
@@ -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"
+13
View File
@@ -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)
+4
View File
@@ -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}"
+6 -13
View File
@@ -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:
+1 -9
View File
@@ -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:
+2 -15
View File
@@ -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
+2 -13
View File
@@ -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())
+3 -5
View File
@@ -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)
+11 -17
View File
@@ -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())
+2 -4
View File
@@ -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]] = []
+4 -3
View File
@@ -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):