refactor: reuse the shared helpers left copied

Copies of helpers the first pass created, replaced by the helper:
- source_yaml_file for our YAML sources (generate_db read them in the
  locale's encoding, a syntax error named no file);
- data_dir_registry_at in registry_bundles, platform_registry_at (new,
  beside load_platform_registry) in the manifest;
- DATA_DIRS_FILE for the registry path five modules spelled;
- load_optional_database, sha1_at, VERSIONS_FILE, installer_module;
- DerivedView where a cache was keyed by id() of a dict;
- count_text and series where a plural or a list was written by hand.
This commit is contained in:
Abdessamad Derraz committed 2026-11-21 10:31:29 +01:00
1 parent 32a4ca1fa1
commit 036a6ebf29
35 files changed
+141 -170

No files matched your search

+2 -2
View File
@@ -18,8 +18,8 @@ import logging
import os
import sys
from core.cli import InputMissing
from core.paths import DATA_DIRS_FILE
from scraper.buildbot_system import (
DEFAULT_REGISTRY,
check,
pending,
print_report,
@@ -44,7 +44,7 @@ def main() -> None:
help="Machine-readable JSON output",
)
parser.add_argument(
"--registry", default=DEFAULT_REGISTRY,
"--registry", default=DATA_DIRS_FILE,
help="the data directory registry to check (default: %(default)s)",
)
args = parser.parse_args()
+11 -19
View File
@@ -68,14 +68,14 @@ from model.targets import apply_target_overrides, platform_overrides, read_targe
from model.registry import list_registered_platforms, load_data_dir_registry, load_platform_registry
from model.profiles import load_emulator_profiles, upstream_profile_index
from core.artifacts import write_text_atomic
from model.safeparse import yaml_load
from model.sources import source_yaml_file
from model.sourcerevision import scraped_revision
from exporter import discover_exporters
from resolve.reconcile import build_native_model
from scripts.scraper import game_dat_importer
from scripts.scraper.redump_dat_scraper import fetch_snapshot
from scripts.scraper.targets import discover_target_scrapers
from core.paths import REPO_ROOT, TRUTH_DIR
from core.paths import DATA_DIRS_FILE, REPO_ROOT, TRUTH_DIR
CORE_INFO_REPO = "https://github.com/libretro/libretro-core-info"
# The git blob of every .info as last reviewed: `--record-coreinfo` writes it.
@@ -323,8 +323,7 @@ def _scrapable_platforms(platforms_dir: Path) -> list[tuple[str, str, Path]]:
path = platforms_dir / f"{name}.yml"
if not path.is_file():
continue
with path.open(encoding="utf-8") as fh:
config = yaml_load(fh) or {}
config = source_yaml_file(path) or {}
scraper = (registry.get(name) or {}).get("scraper")
if not scraper or (config.get("inherits") and not config.get("source")):
continue
@@ -356,10 +355,8 @@ def check_platforms(platforms_dir: Path, workdir: Path, jobs: int) -> list[Findi
return Finding("platforms", name, ERROR, detail="scraper timed out")
if error:
return Finding("platforms", name, ERROR, detail=error)
with path.open(encoding="utf-8") as fh:
old = yaml_load(fh) or {}
with fresh.open(encoding="utf-8") as fh:
new = yaml_load(fh) or {}
old = source_yaml_file(path) or {}
new = source_yaml_file(fresh) or {}
diff = diff_platform(old, new)
status = STALE if diff.changed else OK
return Finding(
@@ -394,12 +391,10 @@ def check_emulatorjs(platforms_dir: Path, offline: bool) -> Finding:
nothing to say so.
"""
subject = "romm emulatorjs"
with (platforms_dir / "emulatorjs.yml").open(encoding="utf-8") as fh:
local = str((yaml_load(fh) or {}).get("version", ""))
local = str((source_yaml_file(platforms_dir / "emulatorjs.yml") or {}).get("version", ""))
if offline:
return Finding("platforms", subject, SKIPPED, local=local, detail="offline")
with (platforms_dir / "romm.yml").open(encoding="utf-8") as fh:
tag = str((yaml_load(fh) or {}).get("version", ""))
tag = str((source_yaml_file(platforms_dir / "romm.yml") or {}).get("version", ""))
for path in ROMM_DOCKERFILES:
try:
text = upstream.http_text(
@@ -618,8 +613,7 @@ def check_targets(
path = targets_dir / f"{platform}.yml"
if not path.is_file():
return [Finding("targets", platform, ERROR, detail="no target file")]
with path.open(encoding="utf-8") as fh:
old = yaml_load(fh) or {}
old = source_yaml_file(path) or {}
module = scrapers.get(platform)
targets = old.get("targets") or {}
if module is not None and offline:
@@ -670,8 +664,7 @@ def check_targets(
return [Finding("targets", platform, ERROR, detail="scraper timed out")]
if error:
return [Finding("targets", platform, ERROR, detail=error)]
with fresh.open(encoding="utf-8") as fh:
new = yaml_load(fh) or {}
new = source_yaml_file(fresh) or {}
diff = diff_targets(old, new)
out = [
Finding(
@@ -748,8 +741,7 @@ def romfolder_sources(platforms_dir: Path) -> dict[str, dict]:
"""setup -> its platforms/romfolders/_sources/<setup>.yml."""
out = {}
for path in sorted((platforms_dir / "romfolders" / "_sources").glob("*.yml")):
with path.open(encoding="utf-8") as fh:
out[path.stem] = yaml_load(fh) or {}
out[path.stem] = source_yaml_file(path) or {}
return out
@@ -1034,7 +1026,7 @@ def _check_buildbot_system() -> Finding:
with contextlib.redirect_stdout(io.StringIO()):
report = buildbot_system.check(
str(REPO_ROOT / "platforms" / "_data_dirs.yml")
str(REPO_ROOT / DATA_DIRS_FILE)
)
if report.get("error"):
return Finding("data", "buildbot system", UNKNOWN, detail="index unreachable")
+2
View File
@@ -15,6 +15,8 @@ DB_FILE = "database.json"
PLATFORMS_DIR = "platforms"
EMULATORS_DIR = "emulators"
BIOS_DIR = "bios"
# The data directory registry refresh_data_dirs, the packs and the checks read.
DATA_DIRS_FILE = f"{PLATFORMS_DIR}/_data_dirs.yml"
# Where generate_truth writes its models and diff_truth and export_native read them.
TRUTH_DIR = "dist/truth"
+1 -1
View File
@@ -31,7 +31,7 @@ def _load_truth(truth_dir: str, platform: str) -> dict | None:
path = os.path.join(truth_dir, f"{platform}.yml")
if not os.path.exists(path):
return None
with open(path) as f:
with open(path, encoding="utf-8") as f:
return yaml_load(f) or {}
+6 -6
View File
@@ -30,7 +30,7 @@ from profiling.citations import collect_citations
from profiling.repos import select_views
from model.sourceref import ref_role, split_source_ref
from model.profiles import ProfileSelectionError, load_emulator_profiles, resolve_profile_name
from model.safeparse import yaml_load
from model.sources import source_yaml_file
# Ways a program asks for somewhere to read from.
SIGNALS = (
@@ -58,8 +58,7 @@ def audit(
name: str, emulators_dir: str, cache_dir: str, offline: bool
) -> list[tuple[str, str]] | None:
"""Signals found in the sources a fileless profile cites."""
with open(os.path.join(emulators_dir, f"{name}.yml"), encoding="utf-8") as handle:
document = yaml_load(handle) or {}
document = source_yaml_file(os.path.join(emulators_dir, f"{name}.yml")) or {}
if document.get("files"):
return None
if document.get("type") == "alias":
@@ -136,9 +135,10 @@ def main() -> None:
known = sorted(path.stem for path in Path(args.emulators_dir).glob("*.yml"))
names = []
for name in known:
with open(Path(args.emulators_dir) / f"{name}.yml", encoding="utf-8") as handle:
if not _settled_before_reading(yaml_load(handle) or {}):
names.append(name)
if not _settled_before_reading(
source_yaml_file(Path(args.emulators_dir) / f"{name}.yml") or {}
):
names.append(name)
flagged = unreachable = 0
for name in names:
+2 -3
View File
@@ -22,7 +22,7 @@ from pathlib import Path
from core.cli import add_repo_inputs
from model.profiles import load_emulator_profiles
from model.region import REGIONS, normalize_declared
from model.safeparse import yaml_load
from model.sources import source_yaml_file
REGIONS_FILE = Path("games") / "regions.yml"
EXTRAS_FILE = Path("games") / "extras.yml"
@@ -32,8 +32,7 @@ _REF_REPO = re.compile(r"(?:^|; )([\w.-]+/[\w.-]+)@([0-9a-f]{8,40}) ")
def load_yaml(path: Path) -> dict:
with Path(path).open(encoding="utf-8") as handle:
return yaml_load(handle) or {}
return source_yaml_file(path) or {}
def profile_pins(profile: dict) -> set[str]:
+15 -12
View File
@@ -19,7 +19,7 @@ from datetime import datetime, timezone
from pathlib import Path
sys.path.insert(0, os.path.dirname(__file__))
from core.cli import add_repo_inputs, require_directory
from core.cli import SourceUnreadable, add_repo_inputs, require_directory
from model.dumpcatalog import annotate_provenance, DEFAULT_PROVENANCE_DIR, load_provenance_snapshots
from core.hashing import compute_hashes
from model.registry import list_registered_platforms
@@ -28,7 +28,8 @@ from core.artifacts import (
write_if_changed,
write_text_atomic,
)
from model.safeparse import require_yaml, yaml_load
from model.safeparse import require_yaml
from model.sources import source_yaml_file
from model.profiles import source_yaml_paths
from resolve.localfile import variant_base_name
from model import retired
@@ -297,14 +298,12 @@ def _declarations(platforms_dir: Path, emulators_dir: Path) -> list[dict]:
] if platforms_dir.is_dir() else []
entries: list[dict] = []
for source in sources:
with open(source) as f:
config = yaml_load(f) or {}
config = source_yaml_file(source) or {}
for system in (config.get("systems") or {}).values():
entries.extend(system.get("files") or [])
if emulators_dir.is_dir():
for source in source_yaml_paths(emulators_dir):
with open(source) as f:
entries.extend((yaml_load(f) or {}).get("files") or [])
entries.extend((source_yaml_file(source) or {}).get("files") or [])
return entries
@@ -651,9 +650,11 @@ def _platform_aliases(book: _AliasBook, unreadable: list[str]) -> None:
):
config_file = platforms_dir / f"{platform_name}.yml"
try:
with open(config_file) as f:
config = yaml_load(f) or {}
except (yaml.YAMLError, OSError) as e:
config = source_yaml_file(config_file) or {}
except SourceUnreadable as e:
unreadable.append(str(e))
continue
except OSError as e:
unreadable.append(f"{config_file}: {e}")
continue
@@ -741,9 +742,11 @@ def _profile_aliases(
return
for emu_file in source_yaml_paths(emulators_dir):
try:
with open(emu_file) as f:
emu_config = yaml_load(f) or {}
except (yaml.YAMLError, OSError) as e:
emu_config = source_yaml_file(emu_file) or {}
except SourceUnreadable as e:
unreadable.append(str(e))
continue
except OSError as e:
unreadable.append(f"{emu_file}: {e}")
continue
# A profile whose entries name each other (dosbox-x opens
+2 -3
View File
@@ -51,7 +51,7 @@ from core.cli import run_cli
from model.region import normalize_declared
from model.romfolders import ProfileResolver, Resolution, SystemResolver, folder_names, load_setups
from core.artifacts import write_text_atomic
from model.safeparse import yaml_load
from model.sources import source_yaml_file
import install
@@ -86,8 +86,7 @@ def dumps(document: object) -> str:
def _load_yaml(path: Path) -> dict:
if not path.exists():
return {}
with path.open(encoding="utf-8") as handle:
return yaml_load(handle) or {}
return source_yaml_file(path) or {}
def _load_json(path: Path) -> dict:
+3 -10
View File
@@ -56,7 +56,6 @@ import argparse
import functools
import hashlib
import http.server
import importlib.util
import json
import os
import re
@@ -64,12 +63,13 @@ import shutil
import subprocess
import sys
import threading
import types
from collections.abc import Iterator
from contextlib import contextmanager
from dataclasses import dataclass
from pathlib import Path
from installer_build.module import installer_module
ROOT = Path(__file__).resolve().parent.parent
OUT = ROOT / "docs_assets" / "demo"
WORK = ROOT / "tmp" / "demo"
@@ -364,18 +364,11 @@ def session_env(base_url: str, work: Path, card: Path,
}
def _installer() -> types.ModuleType:
spec = importlib.util.spec_from_file_location("retrobios_install", ROOT / "install.py")
if spec is None or spec.loader is None:
raise RuntimeError("install.py cannot be loaded")
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
def format_size(size: int) -> str:
"""The size as the installer writes it."""
return str(_installer().format_size(size))
return str(installer_module().format_size(size))
def describe(variant: str, facts: dict) -> str:
+2 -3
View File
@@ -25,6 +25,7 @@ from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "scripts"))
from core.text import series
from model.registry import list_registered_platforms
from model.platforms import load_platform_config
from sitegen.diagrams import OG_SECTIONS, og_card_svg, wrap
@@ -58,10 +59,8 @@ def consoles_tagline(consoles: list[str], lead: str = "BIOS files for") -> str:
listed = names[:shown]
if rest:
text = f"{lead} {', '.join(listed)} and {rest} more"
elif len(listed) > 1:
text = f"{lead} {', '.join(listed[:-1])} and {listed[-1]}"
else:
text = f"{lead} {listed[0]}"
text = f"{lead} {series(listed)}"
if len(wrap(text, TAGLINE_WIDTH, TAGLINE_SIZE)) <= TAGLINE_LINES:
return text
return f"{lead} {len(names)} sections"
+2 -3
View File
@@ -28,7 +28,7 @@ sys.path.insert(0, os.path.dirname(__file__))
from core import upstream
from core.cli import add_repo_inputs, require_directory
from model.safeparse import yaml_load
from model.sources import source_yaml_file
from scraper.clex import blank_comments
from scraper.mame_parser import MACHINE_MACROS
@@ -62,8 +62,7 @@ def audit(
name: str, emulators_dir: str, cache_dir: str, offline: bool
) -> tuple[list[Finding], int, int]:
"""Findings, plus counts of refs that agree and of unjudgeable ones."""
with open(os.path.join(emulators_dir, f"{name}.yml"), encoding="utf-8") as handle:
document = yaml_load(handle) or {}
document = source_yaml_file(os.path.join(emulators_dir, f"{name}.yml")) or {}
trees = {
role: (upstream.parse_repo(str(document.get(role) or "")),
str(document.get(f"{role}_commit") or ""))
+7 -3
View File
@@ -29,13 +29,12 @@ def load_data_dir_registry(platforms_dir: str | Path = PLATFORMS_DIR, required:
return data_dir_registry_at(os.path.join(platforms_dir, "_data_dirs.yml"), required)
def load_platform_registry(platforms_dir: str | Path = PLATFORMS_DIR, required: bool = False) -> dict:
"""Return the `platforms:` mapping from _registry.yml.
def platform_registry_at(registry_path: str | os.PathLike[str], required: bool = False) -> dict:
"""The `platforms:` mapping of a platform registry file.
An absent file is an empty registry, or with ``required`` an input the
command cannot run without.
"""
registry_path = os.path.join(platforms_dir, "_registry.yml")
if not os.path.exists(registry_path):
if required:
raise InputMissing(f"{registry_path} not found")
@@ -43,6 +42,11 @@ def load_platform_registry(platforms_dir: str | Path = PLATFORMS_DIR, required:
return (source_yaml_file(registry_path) or {}).get("platforms") or {}
def load_platform_registry(platforms_dir: str | Path = PLATFORMS_DIR, required: bool = False) -> dict:
"""Return the `platforms:` mapping from _registry.yml."""
return platform_registry_at(os.path.join(platforms_dir, "_registry.yml"), required)
def list_registered_platforms(platforms_dir: str = PLATFORMS_DIR) -> list[str]:
"""List platforms registered in _registry.yml.
-1
View File
@@ -25,7 +25,6 @@ from model.registry import VERSIONS_FILE, load_versions
log = logging.getLogger(__name__)
DEFAULT_REGISTRY = "platforms/_data_dirs.yml"
USER_AGENT = "retrobios/1.0"
REQUEST_TIMEOUT = 30
DOWNLOAD_TIMEOUT = 300
+2 -7
View File
@@ -15,8 +15,7 @@ from core.paths import EMULATORS_DIR, REPO_ROOT, declared_destination, sanitize_
from model.declarations import OUTER_ROOTS, declared_root, outer_layout
from model.platforms import load_platform_config
from model.profiles import load_emulator_profiles
from model.registry import load_data_dir_registry
from model.safeparse import yaml_load
from model.registry import load_data_dir_registry, platform_registry_at
from model.systems import platform_system_names
from packs import slots
from packs.archive import CASE_FOLDING_OS, PACK_DOCUMENTS, Placed
@@ -610,11 +609,7 @@ def _start_manifest(
game_entries = platform_game_data(config, emu_profiles, data_registry)
# Load registry for install metadata
registry: dict = {}
if os.path.exists(registry_path):
with open(registry_path) as f:
registry = yaml_load(f) or {}
plat_registry = registry.get("platforms", {}).get(platform_name, {})
plat_registry = platform_registry_at(registry_path).get(platform_name) or {}
plat_cores = _platform_cores(config, emu_profiles) if opts.target_cores else None
pack_systems = filter_systems_by_target(
+3 -2
View File
@@ -19,7 +19,8 @@ from core.cli import suggest_names
from model.cliargs import platform_arg, require_platform
from model.registry import data_dir_registry_at
from packs.datadirs import DEFAULT_REGISTRY, log, refresh_all, refresh_entry
from core.paths import DATA_DIRS_FILE
from packs.datadirs import log, refresh_all, refresh_entry
def summarize(outcomes: dict[str, bool | None], dry_run: bool) -> str:
@@ -48,7 +49,7 @@ def main() -> None:
"--platform", "-p", type=platform_arg, help="Only refresh entries for this platform"
)
parser.add_argument(
"--registry", default=DEFAULT_REGISTRY, help="Path to _data_dirs.yml"
"--registry", default=DATA_DIRS_FILE, help="Path to _data_dirs.yml"
)
args = parser.parse_args()
+2 -2
View File
@@ -63,12 +63,12 @@ from functools import lru_cache
from pathlib import Path
from model.platforms import inheritance_chain
from model.registry import data_dir_registry_at, load_platform_registry
from core.paths import REPO_ROOT
from core.paths import DATA_DIRS_FILE, REPO_ROOT
LOG_DIR = REPO_ROOT / "tmp" / "refresh_stale"
CHECK_FRESHNESS = REPO_ROOT / "scripts" / "check_freshness.py"
PLATFORMS_REGISTRY = REPO_ROOT / "platforms" / "_registry.yml"
DATA_DIRS_REGISTRY = REPO_ROOT / "platforms" / "_data_dirs.yml"
DATA_DIRS_REGISTRY = REPO_ROOT / DATA_DIRS_FILE
AUTO_AREAS = ("platforms", "native", "targets", "data", "catalogs")
# A rom-folder pin is moved by hand in platforms/romfolders/_sources/,
+4 -7
View File
@@ -10,10 +10,11 @@ from collections.abc import Iterable
from pathlib import Path
from typing import NamedTuple
from core.paths import EMULATORS_DIR
from core.paths import DATA_DIRS_FILE, EMULATORS_DIR
from core.hashing import file_digest
from core.sizes import size_text
from model.composition import composition_tier
from model.registry import data_dir_registry_at
from model.largefiles import (
LARGE_FILES_RELEASE,
LARGE_FILES_REPO,
@@ -235,14 +236,10 @@ def profile_descriptions(emulators_dir: str = EMULATORS_DIR) -> dict[str, str]:
return found
def registry_bundles(registry_path: str = "platforms/_data_dirs.yml") -> dict[str, str]:
def registry_bundles(registry_path: str = DATA_DIRS_FILE) -> dict[str, str]:
"""Asset name -> description for data directories served from the release."""
from model.safeparse import yaml_load
with open(registry_path, encoding="utf-8") as handle:
registry = yaml_load(handle) or {}
bundles: dict[str, str] = {}
for entry in (registry.get("data_directories") or registry).values():
for entry in data_dir_registry_at(registry_path, required=True).values():
if not isinstance(entry, dict):
continue
url = str(entry.get("source_url") or "")
+1 -2
View File
@@ -161,8 +161,7 @@ def gather_thanks(run: Run | None = None, repo: str = REPO) -> list[str]:
("Help in issues", helped)):
if people:
names = [f"@{login}" for login in sorted(people, key=str.casefold)]
listed = names[0] if len(names) == 1 else f"{', '.join(names[:-1])} and {names[-1]}"
lines.append(f"- **{label}**: {listed}.")
lines.append(f"- **{label}**: {series(names)}.")
return lines
+7 -8
View File
@@ -2,10 +2,12 @@
from __future__ import annotations
from core.memo import DerivedView
from resolve.validation import read_by_build
_directory_members_cache: dict[int, tuple[dict, dict[str, dict[str, str]]]] = {}
# The members found under each tail, kept per by_path_suffix index.
_directory_members_cache: DerivedView[dict[str, dict[str, str]]] = DerivedView(lambda _index: {})
def directory_members(db: dict, directory: str) -> dict[str, str]:
@@ -24,12 +26,9 @@ def directory_members(db: dict, directory: str) -> dict[str, str]:
if not tail:
return {}
by_path_suffix = db.get("indexes", {}).get("by_path_suffix", {})
cached = _directory_members_cache.get(id(by_path_suffix))
if cached is None or cached[0] is not by_path_suffix:
cached = (by_path_suffix, {})
_directory_members_cache[id(by_path_suffix)] = cached
if tail in cached[1]:
return cached[1][tail]
found = _directory_members_cache(by_path_suffix)
if tail in found:
return found[tail]
prefix = f"{tail}/"
infix = f"/{prefix}"
@@ -54,7 +53,7 @@ def directory_members(db: dict, directory: str) -> dict[str, str]:
if one_tree and one_content
else {}
)
cached[1][tail] = members
found[tail] = members
return members
+11 -9
View File
@@ -16,6 +16,7 @@ except ImportError:
yaml = None
from core.hashing import compute_hashes, parse_hash_list, stream_hashes
from core.memo import DerivedView
from model.nodedup import in_nodedup_dir
from model.platforms import load_platform_config
from model.profiles import load_emulator_profiles
@@ -846,19 +847,20 @@ def placement(
return Placement(tuple(sorted(homes)))
_HELD_DIRECTORIES: dict[int, frozenset[str]] = {}
def _directories_of(files: dict) -> frozenset[str]:
return frozenset(
path.rsplit("/", 1)[0] + "/"
for record in files.values()
if "/" in (path := record.get("path") or "") and "/.variants/" not in path
)
_held_view = DerivedView(_directories_of)
def _held_directories(db: dict | None) -> frozenset[str]:
"""Every directory a file of the database sits in, .variants/ aside."""
key = id(db)
if key not in _HELD_DIRECTORIES:
_HELD_DIRECTORIES[key] = frozenset(
path.rsplit("/", 1)[0] + "/"
for record in (db or {}).get("files", {}).values()
if "/" in (path := record.get("path") or "") and "/.variants/" not in path
)
return _HELD_DIRECTORIES[key]
return _held_view((db or {}).get("files", {}))
def _directory_tail(db: dict | None, directory: str) -> str:
+2 -2
View File
@@ -18,6 +18,7 @@ from typing import Any
from model.profiles import PROFILE_BACKUP_SUFFIX
from core.artifacts import write_text_atomic
from model.safeparse import yaml_load
from model.sources import source_yaml_file
_MAME_RELEASE_RE = re.compile(r"^0\.\d+")
@@ -350,8 +351,7 @@ def _diff_fbneo(
def _load_yaml(path: str) -> dict[str, Any]:
with open(path, encoding="utf-8") as f:
return yaml_load(f) or {}
return source_yaml_file(path) or {}
def _load_json(path: str) -> dict[str, Any]:
+3 -3
View File
@@ -31,7 +31,8 @@ from core.upstream import (
)
from core.upstream import download as upstream_download
from core.upstream import forge_headers as upstream_headers
from model.safeparse import require_yaml, yaml_load
from model.safeparse import require_yaml
from model.sources import source_yaml_file
try:
import yaml
@@ -612,8 +613,7 @@ def _keep_existing(config: dict, output_path: Path) -> None:
"""Merge into existing YAML: preserve fields the scraper doesn't generate
(data_directories, case_insensitive_fs, manually added metadata).
The scraper replaces systems + files, everything else is preserved."""
with open(output_path) as f:
existing = yaml_load(f) or {}
existing = source_yaml_file(output_path) or {}
# Preserve existing keys not generated by the scraper.
# Only keys present in the NEW config are considered scraper-generated.
# Everything else in the existing file is preserved.
+2 -3
View File
@@ -12,11 +12,10 @@ import ast
import re
import sys
from collections.abc import Callable, Iterator
from pathlib import Path
from model.database import load_database
from core.paths import PLATFORMS_DIR, REPO_ROOT
from core.paths import DB_FILE, PLATFORMS_DIR, REPO_ROOT
from model.targets import load_target_config, target_overrides
from core.hashing import cut_md5_owner
from model.safeparse import yaml_load_upstream
@@ -315,7 +314,7 @@ _MD5_RE = re.compile(r"^[a-fA-F0-9]+$")
def _load_md5_index() -> dict[str, str]:
"""Load by_md5 index from database.json for prefix resolution."""
db_path = Path(__file__).resolve().parents[2] / "database.json"
db_path = REPO_ROOT / DB_FILE
if not db_path.exists():
return {}
return load_database(str(db_path)).get("indexes", {}).get("by_md5", {})
+3 -3
View File
@@ -9,6 +9,7 @@ import urllib.error
import urllib.parse
from core.upstream import remote_etag as get_remote_etag
from core.paths import DATA_DIRS_FILE
from model.registry import data_dir_registry_at, load_versions
from .base_scraper import fetch_text
@@ -18,7 +19,6 @@ log = logging.getLogger(__name__)
BUILDBOT_SYSTEM_URL = "https://buildbot.libretro.com/assets/system/"
INDEX_URL = BUILDBOT_SYSTEM_URL + ".index"
DEFAULT_REGISTRY = "platforms/_data_dirs.yml"
def fetch_index() -> set[str]:
@@ -27,7 +27,7 @@ def fetch_index() -> set[str]:
def load_tracked_entries(
registry_path: str = DEFAULT_REGISTRY,
registry_path: str = DATA_DIRS_FILE,
) -> dict[str, tuple[str, str]]:
"""Load buildbot entries from _data_dirs.yml.
@@ -43,7 +43,7 @@ def load_tracked_entries(
return entries
def check(registry_path: str = DEFAULT_REGISTRY) -> dict:
def check(registry_path: str = DATA_DIRS_FILE) -> dict:
"""Run the buildbot check. Returns structured report."""
try:
index_zips = fetch_index()
+4 -3
View File
@@ -25,6 +25,8 @@ from model.platforms import load_platform_config
from model.profiles import source_yaml_paths
from core.artifacts import write_text_atomic
from model.safeparse import yaml_load
from model.sources import source_yaml_file
from core.cli import SourceUnreadable
from core import upstream
@@ -123,8 +125,7 @@ def _find_mame_profiles() -> list[Path]:
profiles: list[Path] = []
for path in source_yaml_paths(_EMULATORS_DIR):
try:
with open(path, encoding="utf-8") as f:
data = yaml_load(f)
data = source_yaml_file(path)
if not isinstance(data, dict):
continue
upstream = data.get("upstream", "")
@@ -149,7 +150,7 @@ def _find_mame_profiles() -> list[Path]:
)
):
profiles.append(path)
except (yaml.YAMLError, OSError) as exc:
except (SourceUnreadable, OSError) as exc:
# Skipped, a broken mame.yml left the list and the refresh
# reported success without touching it.
raise RuntimeError(f"cannot read {path}: {exc}") from exc
+2 -3
View File
@@ -24,7 +24,7 @@ if (_SCRIPTS_DIR := str(Path(__file__).resolve().parents[2])) not in sys.path:
sys.path.insert(0, _SCRIPTS_DIR)
from core import upstream
from model.safeparse import yaml_load
from model.sources import source_yaml_file
CACHE_DIR = upstream.CACHE_DIR
@@ -160,8 +160,7 @@ def load_sources(directory: Path) -> dict[str, dict]:
"""Each setup's declared sources and facts, keyed by its file name."""
out: dict[str, dict] = {}
for path in sorted(Path(directory).glob("*.yml")):
with path.open(encoding="utf-8") as handle:
out[path.stem] = yaml_load(handle) or {}
out[path.stem] = source_yaml_file(path) or {}
return out
+4 -5
View File
@@ -14,6 +14,7 @@ from pathlib import Path
from xml.sax.saxutils import escape
from model.registry import load_platform_registry
from model.sources import source_yaml_file
from core.paths import REPO_ROOT
from core.text import count_text
from model import siteinputs
@@ -453,13 +454,11 @@ def emulator_names() -> dict[str, str]:
@cache
def _emulator_names_in(emulators_dir: str) -> dict[str, str]:
import yaml
names: dict[str, str] = {}
for _, emulator in CHAIN_EXAMPLES:
with open(Path(emulators_dir) / f"{emulator}.yml", encoding="utf-8") as handle:
label = str(yaml.safe_load(handle).get("emulator", emulator))
names[emulator] = re.sub(r"\s*\(.*\)$", "", label)
profile = source_yaml_file(Path(emulators_dir) / f"{emulator}.yml") or {}
label = str(profile.get("emulator", emulator))
names[emulator] = re.sub(r"\s*\(.*\)$", "", label)
return names
+3 -5
View File
@@ -9,6 +9,7 @@ from dataclasses import dataclass
from core.hashing import declared_hash_lists
from core.text import series
from model.database import sha1_at
from model.platforms import native_layer
from model.profiles import is_emulator
from resolve.cores import resolve_platform_cores
@@ -104,11 +105,8 @@ def _copy_cell(path: str, algos: list[str], db: dict | None) -> str:
"""The file a path holds, with its hashes in the algorithms declared."""
if not path:
return "-"
record: dict = next(
(rec | {"sha1": sha1} for sha1, rec in (db or {}).get("files", {}).items()
if rec.get("path") == path),
{},
)
sha1 = sha1_at(db or {}, path)
record: dict = (db or {})["files"][sha1] | {"sha1": sha1} if sha1 else {}
hashes = {algo: [str(record[algo]).lower()] for algo in algos if record.get(algo)}
shown = f"[{code_span(path)}]({fetch_url(path)})"
return f"{shown}<br>{_hash_cell(hashes)}" if hashes else shown
+2 -2
View File
@@ -26,7 +26,7 @@ from model.guides import PACKAGE_COMMAND, install_command
from model.largefiles import LARGE_FILES_CACHE, load_registered_paths
from model.platforms import load_platform_config
from model.profiles import load_emulator_profiles, unique_emulator_profiles
from model.registry import list_registered_platforms, load_platform_registry
from model.registry import VERSIONS_FILE, list_registered_platforms, load_platform_registry
from model.systems import system_index
from packs.coverage import verify_platform
from resolve.cores import resolve_platform_cores
@@ -144,7 +144,7 @@ def _coverage_inputs(db_path: Path, platforms_dir: str, emulators_dir: str) -> s
for path in sorted(p for p in root.resolve().rglob(pattern) if p.is_file()):
add_file(path)
for path in (REPO_ROOT / ".gitignore", REPO_ROOT / "_mame_clones.json",
REPO_ROOT / "data" / ".versions.json"):
REPO_ROOT / VERSIONS_FILE):
add_file(path)
digest.update(b"offline\0" + (b"1" if os.environ.get("RETROBIOS_OFFLINE") else b"0") + b"\n")
large = Path(LARGE_FILES_CACHE).resolve()
+2 -4
View File
@@ -14,6 +14,7 @@ from pathlib import Path
from core.childenv import is_secret, safe_env
from core.hostguard import LOCK_HELD_ENV
from core.paths import REPO_ROOT
from model.sources import source_yaml_file
JOBS_FILE = REPO_ROOT / "automation" / "jobs.yml"
@@ -204,10 +205,7 @@ def parse_jobs(data: dict) -> dict[str, Job]:
def load_jobs(path: Path = JOBS_FILE) -> dict[str, Job]:
import yaml
with path.open(encoding="utf-8") as handle:
return parse_jobs(yaml.safe_load(handle) or {})
return parse_jobs(source_yaml_file(path) or {})
# Running a job
+2 -15
View File
@@ -26,8 +26,7 @@ from pathlib import Path
sys.path.insert(0, os.path.dirname(__file__))
from core.paths import DB_FILE
from model.database import load_database
from model.database import load_optional_database
from core.cli import add_repo_inputs, require_directory
try:
@@ -138,18 +137,6 @@ def place(results: list[ValidationResult]) -> list[str]:
return placed
def _load_database_if_any(path: str) -> dict | None:
"""The database, optional only where the default is meant.
A mistyped --db read as "no database" and every file passed its
duplicate and placement checks unchecked. A damaged one did the same
after a warning.
"""
if path == DB_FILE and not os.path.exists(path):
return None
return load_database(path)
def main() -> None:
parser = argparse.ArgumentParser(allow_abbrev=False, description="Validate BIOS file contributions")
parser.add_argument("files", nargs="*", help="Files to validate")
@@ -188,7 +175,7 @@ def main() -> None:
print("[]")
return
db = _load_database_if_any(args.db)
db = load_optional_database(args.db)
require_directory(args.platforms_dir, "--platforms-dir")
platform_hashes = load_platform_hashes(args.platforms_dir, db)
profile_hashes = load_profile_hashes(args.emulators_dir, db)
+2 -6
View File
@@ -1048,13 +1048,9 @@ class UnknownRegionSaysWhatToType(unittest.TestCase):
self.assertIn("Short forms: jp", message)
def test_the_installer_says_the_same(self):
import importlib.util
from installer_build.module import installer_module
spec = importlib.util.spec_from_file_location(
"install_under_test", Path(__file__).resolve().parents[1] / "install.py"
)
install = importlib.util.module_from_spec(spec)
spec.loader.exec_module(install)
install = installer_module()
with self.assertRaises(ValueError) as caught:
install.canonical_region("europ")
self.assertIn("Close matches: europe", str(caught.exception))
+3 -4
View File
@@ -11,7 +11,6 @@ from __future__ import annotations
import tests
import importlib.util
import json
import random
import re
@@ -19,11 +18,11 @@ import tempfile
import unittest
from pathlib import Path
from installer_build.module import installer_module
REPO_ROOT = Path(__file__).resolve().parents[1]
_spec = importlib.util.spec_from_file_location("install", REPO_ROOT / "install.py")
install = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(install)
install = installer_module()
PICKER = REPO_ROOT / "website" / "src" / "components" / "FilePicker.astro"
+2 -9
View File
@@ -43,12 +43,12 @@ import re
import unittest
from pathlib import Path
import yaml
import importlib.util
from sitegen import diagrams
from model.guides import INSTALL_SH
from tests import sitepages
from installer_build import port
from installer_build.module import installer_module
from release.check import SUMS, Asset, compare_release
REPO_ROOT = Path(__file__).resolve().parents[1]
@@ -932,13 +932,6 @@ class NoBackslashInProseCode(unittest.TestCase):
self.assertNotRegex(line, r"`[^`]*\\\|[^`]*`")
def _install_module():
spec = importlib.util.spec_from_file_location("install_r4wiki", REPO_ROOT / "install.py")
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
class EventsTranscript(unittest.TestCase):
"""D10: the events table had no sample of what a run writes."""
@@ -948,7 +941,7 @@ class EventsTranscript(unittest.TestCase):
self.assertIsNotNone(block)
lines = block.group(1).splitlines()
self.assertEqual(len(lines), 5)
keys = _install_module().EVENT_KEYS
keys = installer_module().EVENT_KEYS
events = [json.loads(line) for line in lines]
for event in events:
with self.subTest(event=event["event"]):
+20
View File
@@ -250,5 +250,25 @@ class OfflinePipelineVerifiesOffline(unittest.TestCase):
self.assertIn('verify_cmd.append("--offline")', block)
class RegistryBundlesReadTheRegistry(unittest.TestCase):
"""registry_bundles read _data_dirs.yml by its own copy of the registry
reader: a missing file ended on FileNotFoundError and a syntax error
named no line."""
def test_bundles_and_a_missing_registry(self):
from core.cli import InputMissing
from release.assets import RELEASE_DOWNLOAD, registry_bundles
with tempfile.TemporaryDirectory() as tmp:
path = Path(tmp, "_data_dirs.yml")
path.write_text(yaml.safe_dump({"data_directories": {
"served": {"source_url": f"{RELEASE_DOWNLOAD}tree.zip", "description": "A tree"},
"upstream": {"source_url": "https://example.org/x.zip"},
}}), encoding="utf-8")
self.assertEqual(registry_bundles(str(path)), {"tree.zip": "A tree"})
with self.assertRaises(InputMissing):
registry_bundles(str(Path(tmp, "absent.yml")))
if __name__ == "__main__":
unittest.main()