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

+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]] = []