diff --git a/scripts/model/platforms.py b/scripts/model/platforms.py index 9973d0878..686d0b857 100644 --- a/scripts/model/platforms.py +++ b/scripts/model/platforms.py @@ -10,7 +10,7 @@ except ImportError: yaml = None from core.paths import PLATFORMS_DIR, comparable_destination -from model.sources import source_yaml +from model.sources import source_yaml_file _shared_yml_cache: dict[str, dict] = {} @@ -31,8 +31,7 @@ def _inherited_yaml(platform_name: str, platforms_dir: str) -> tuple[dict, list[ if not os.path.exists(config_file): raise FileNotFoundError(f"Platform config not found: {config_file}") - with open(config_file) as f: - config = source_yaml(f) or {} + config = source_yaml_file(config_file) or {} if "inherits" not in config: return config, [platform_name] @@ -61,8 +60,7 @@ def _cached_platform_yaml(path: str) -> dict: """A registry or shared-group file, parsed once per real path.""" real = os.path.realpath(path) if real not in _shared_yml_cache: - with open(path) as f: - _shared_yml_cache[real] = source_yaml(f) or {} + _shared_yml_cache[real] = source_yaml_file(path) or {} return _shared_yml_cache[real] @@ -172,12 +170,11 @@ def _attach_rom_folders(config: dict, platform_name: str, platforms_dir: str) -> romfolders = os.path.join(platforms_dir, "romfolders", f"{platform_name}.yml") if not os.path.exists(romfolders): return - with open(romfolders) as f: - roms_root = (source_yaml(f) or {}).get("roms_root") + data = source_yaml_file(romfolders) or {} + roms_root = data.get("roms_root") if isinstance(roms_root, dict): config["_roms_root"] = roms_root - with open(romfolders) as f: - folders = (source_yaml(f) or {}).get("folders") + folders = data.get("folders") if isinstance(folders, list): config["_rom_folders"] = [row for row in folders if isinstance(row, dict)] diff --git a/scripts/model/profiles.py b/scripts/model/profiles.py index be4d706a8..59901684d 100644 --- a/scripts/model/profiles.py +++ b/scripts/model/profiles.py @@ -14,7 +14,7 @@ except ImportError: from core.cli import InputMissing, suggest_names from model.alternatives import derive_member_requirements -from model.sources import source_yaml +from model.sources import source_yaml_file from model.systems import norm_system_id, system_index from core.paths import REPO_ROOT @@ -243,8 +243,7 @@ def load_emulator_profiles( # source-paths.json, both exiting 0. raise InputMissing(f"no emulator profile directory at {emulators_dir}") for f in source_yaml_paths(emu_path): - with open(f) as fh: - profile = source_yaml(fh) or {} + profile = source_yaml_file(f) or {} if "emulator" not in profile: continue _normalize_hash_fields(profile) diff --git a/scripts/model/registry.py b/scripts/model/registry.py index ad8743c84..556371136 100644 --- a/scripts/model/registry.py +++ b/scripts/model/registry.py @@ -8,7 +8,7 @@ from pathlib import Path from core.paths import PLATFORMS_DIR from core.cli import InputMissing -from model.sources import source_yaml +from model.sources import source_yaml_file def load_data_dir_registry(platforms_dir: str = PLATFORMS_DIR) -> dict: @@ -16,8 +16,7 @@ def load_data_dir_registry(platforms_dir: str = PLATFORMS_DIR) -> dict: registry_path = os.path.join(platforms_dir, "_data_dirs.yml") if not os.path.exists(registry_path): return {} - with open(registry_path) as f: - data = source_yaml(f) or {} + data = source_yaml_file(registry_path) or {} return data.get("data_directories", {}) @@ -32,8 +31,7 @@ def load_platform_registry(platforms_dir: str | Path = PLATFORMS_DIR, required: if required: raise InputMissing(f"{registry_path} not found") return {} - with open(registry_path, encoding="utf-8") as f: - return (source_yaml(f) or {}).get("platforms") or {} + return (source_yaml_file(registry_path) or {}).get("platforms") or {} def list_registered_platforms(platforms_dir: str = PLATFORMS_DIR) -> list[str]: @@ -49,8 +47,7 @@ def list_registered_platforms(platforms_dir: str = PLATFORMS_DIR) -> list[str]: registry_path = os.path.join(platforms_dir, "_registry.yml") if not os.path.exists(registry_path): raise InputMissing(f"no platform registry at {registry_path}") - with open(registry_path) as f: - registry = source_yaml(f) or {} + registry = source_yaml_file(registry_path) or {} platforms = [] for name, meta in sorted(registry.get("platforms", {}).items()): config_path = os.path.join(platforms_dir, meta.get("config", f"{name}.yml")) diff --git a/scripts/model/romfolders.py b/scripts/model/romfolders.py index efcfc1a06..0bdbd37c7 100644 --- a/scripts/model/romfolders.py +++ b/scripts/model/romfolders.py @@ -21,7 +21,7 @@ from model.systems import norm_system_id from model.registry import list_registered_platforms from model.profiles import load_emulator_profiles, preferred_profile, upstream_profile_index from model.platforms import load_platform_config, native_layer -from model.safeparse import yaml_load +from model.sources import source_yaml_file ROMFOLDERS_DIR = Path("platforms") / "romfolders" SOURCES_DIR = ROMFOLDERS_DIR / "_sources" @@ -47,8 +47,7 @@ def setup_paths(directory: Path = ROMFOLDERS_DIR) -> list[Path]: def load_setup(path: Path) -> dict: - with Path(path).open(encoding="utf-8") as handle: - return yaml_load(handle) + return source_yaml_file(path) def load_setups(directory: Path = ROMFOLDERS_DIR) -> dict[str, dict]: diff --git a/scripts/model/sourcerevision.py b/scripts/model/sourcerevision.py index 7f9f351b3..053dd239b 100644 --- a/scripts/model/sourcerevision.py +++ b/scripts/model/sourcerevision.py @@ -10,7 +10,7 @@ from __future__ import annotations import re from pathlib import Path -from model.safeparse import yaml_load +from model.sources import source_yaml_file # Each pattern captures the revision. A trailing file path is optional: a # tree URL names the whole repository at a commit (RetroDECK, MinUI). @@ -57,8 +57,7 @@ def platform_revision(platform_file: Path, repo: str = "", commit: bool = False) the platform's BIOS list: moving to a new release is a rescrape of the platform first. """ - with platform_file.open(encoding="utf-8") as handle: - source = str((yaml_load(handle) or {}).get("source") or "") + source = str((source_yaml_file(platform_file) or {}).get("source") or "") try: return required_revision(source, repo, commit) except ValueError as exc: diff --git a/scripts/model/sources.py b/scripts/model/sources.py index f36acc5b4..aa3215060 100644 --- a/scripts/model/sources.py +++ b/scripts/model/sources.py @@ -2,6 +2,7 @@ from __future__ import annotations +import os from typing import Any, TextIO try: @@ -32,3 +33,9 @@ def source_yaml(stream: TextIO) -> Any: f"{where}: {problem}. Check it with: " "python scripts/validate_schemas.py --source-only" ) from None + + +def source_yaml_file(path: str | os.PathLike[str]) -> Any: + """source_yaml on a file of ours, read as UTF-8 whatever the locale.""" + with open(path, encoding="utf-8") as handle: + return source_yaml(handle) diff --git a/scripts/model/targets.py b/scripts/model/targets.py index 179e4eedc..a35028182 100644 --- a/scripts/model/targets.py +++ b/scripts/model/targets.py @@ -9,15 +9,14 @@ from pathlib import Path from core.paths import PLATFORMS_DIR from core.cli import SourceUnreadable, suggest_names -from model.sources import source_yaml +from model.sources import source_yaml_file def _target_overrides(platform_name: str, targets_dir: str) -> dict: overrides_file = os.path.join(targets_dir, "_overrides.yml") if not os.path.exists(overrides_file): return {} - with open(overrides_file) as f: - all_overrides = source_yaml(f) or {} + all_overrides = source_yaml_file(overrides_file) or {} return all_overrides.get(platform_name, {}).get("targets", {}) @@ -37,8 +36,7 @@ def platform_files_target(platform: str, target: str, platforms_dir: str = PLATF target_file = os.path.join(targets_dir, f"{platform}.yml") if not os.path.exists(target_file): return False - with open(target_file) as f: - targets = (source_yaml(f) or {}).get("targets", {}) + targets = (source_yaml_file(target_file) or {}).get("targets", {}) return target in _target_alias_index(targets, _target_overrides(platform, targets_dir)) @@ -57,8 +55,7 @@ def canonical_target_name( target_file = os.path.join(targets_dir, f"{platform_name}.yml") if not os.path.exists(target_file): continue - with open(target_file) as f: - targets = (source_yaml(f) or {}).get("targets", {}) + targets = (source_yaml_file(target_file) or {}).get("targets", {}) canonical = _target_alias_index( targets, _target_overrides(platform_name, targets_dir) ).get(target) @@ -111,8 +108,7 @@ def load_target_config( f"{platform_name} has no hardware targets: drop --target " f"(platforms with targets: {', '.join(with_targets)})" ) - with open(target_file) as f: - data = source_yaml(f) or {} + data = source_yaml_file(target_file) or {} targets = data.get("targets", {}) overrides = _target_overrides(platform_name, targets_dir) @@ -182,8 +178,7 @@ def list_available_targets( target_file = os.path.join(targets_dir, f"{platform_name}.yml") if not os.path.exists(target_file): return [] - with open(target_file) as f: - data = source_yaml(f) or {} + data = source_yaml_file(target_file) or {} # The count --target filters on: overrides applied, as load_target_config # applies them. The scraped list counted Batocera's machine variants and @@ -285,8 +280,7 @@ def _unknown_target_message(target: str, platforms: list[str], platforms_dir: st target_file = os.path.join(targets_dir, f"{platform}.yml") if not os.path.exists(target_file): continue - with open(target_file) as f: - targets = (source_yaml(f) or {}).get("targets", {}) + targets = (source_yaml_file(target_file) or {}).get("targets", {}) overrides = _target_overrides(platform, targets_dir) for name in _target_alias_index(targets, overrides): owners.setdefault(name, []).append(platform) diff --git a/scripts/packs/datadirs.py b/scripts/packs/datadirs.py index 7ad8815c4..28a5cd5f7 100644 --- a/scripts/packs/datadirs.py +++ b/scripts/packs/datadirs.py @@ -23,7 +23,7 @@ except ImportError: 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.sources import source_yaml_file from model.registry import VERSIONS_FILE, load_versions @@ -46,8 +46,7 @@ def load_registry(registry_path: str = DEFAULT_REGISTRY) -> dict[str, dict]: path = Path(registry_path) if not path.exists(): raise InputMissing(f"Registry not found: {registry_path}") - with open(path) as f: - data = yaml_load(f) or {} + data = source_yaml_file(path) or {} return data.get("data_directories", {}) diff --git a/scripts/resolve/grouping.py b/scripts/resolve/grouping.py index 645858115..a56b8b0e5 100644 --- a/scripts/resolve/grouping.py +++ b/scripts/resolve/grouping.py @@ -7,7 +7,7 @@ import json import os from model.platforms import load_platform_config -from model.sources import source_yaml +from model.sources import source_yaml_file from resolve.layout import CORE_DIR_PREFIX from resolve.standalone import standalone_set @@ -33,8 +33,7 @@ def group_identical_platforms( for platform in platforms: try: raw_path = os.path.join(platforms_dir, f"{platform}.yml") - with open(raw_path) as f: - raw = source_yaml(f) or {} + raw = source_yaml_file(raw_path) or {} inherits[platform] = "inherits" in raw config = load_platform_config(platform, platforms_dir) except FileNotFoundError: diff --git a/tests/test_tool_messages.py b/tests/test_tool_messages.py index 8da13a6e0..8f236f849 100644 --- a/tests/test_tool_messages.py +++ b/tests/test_tool_messages.py @@ -150,6 +150,22 @@ class ADamagedProfileNamesItself(unittest.TestCase): "--source-only" ]) + def test_every_source_reader_names_the_file_and_line(self): + """The rom folders, source revision and data directory readers + parsed with yaml_load and stopped on a raw yaml traceback.""" + from model.romfolders import load_setup + from model.sourcerevision import platform_revision + from packs.datadirs import load_registry + + with tempfile.TemporaryDirectory(dir=REPO_ROOT / "tmp") as folder: + bad = Path(folder) / "bad.yml" + bad.write_text("source: a\nb: [\n", encoding="utf-8") + for read in (load_setup, platform_revision, lambda p: load_registry(str(p))): + with self.subTest(read=read), self.assertRaisesRegex( + SourceUnreadable, rf"{re.escape(str(bad))}:\d+: " + ): + read(bad) + def test_a_damaged_file_is_not_an_absent_one(self): """Ten callers skip a platform whose file is absent (except FileNotFoundError): a damaged one has to stop them instead."""