diff --git a/scripts/check_freshness.py b/scripts/check_freshness.py index cb5de1a18..30f068f1e 100644 --- a/scripts/check_freshness.py +++ b/scripts/check_freshness.py @@ -63,8 +63,9 @@ from installer_build import pins as installer_build_pins from packs import datadirs from core import upstream from core.cli import InputMissing, add_repo_inputs, require_directory, suggest_names +from model.platforms import inheritance_chain from model.targets import apply_target_overrides, platform_overrides, read_target_overrides -from model.registry import list_registered_platforms, load_platform_registry +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 @@ -488,18 +489,11 @@ def published_export_state( def _transcribed_at(platforms_dir: Path, platform: str) -> float: """Last rewrite of the platform file or of any file it inherits.""" - newest = 0.0 - seen: set[str] = set() - name: str | None = platform - while name and name not in seen: - seen.add(name) - path = platforms_dir / f"{name}.yml" - if not path.is_file(): - break - newest = max(newest, path.stat().st_mtime) - with path.open(encoding="utf-8") as fh: - name = (yaml_load(fh) or {}).get("inherits") - return newest + return max( + ((platforms_dir / f"{name}.yml").stat().st_mtime + for name in inheritance_chain(platform, platforms_dir)), + default=0.0, + ) # How the truth model settles two cores' hashes: generate_truth reports it, @@ -1016,7 +1010,7 @@ def check_coreinfo( def check_data(offline: bool) -> list[Finding]: if offline: return [Finding("data", "_data_dirs.yml", SKIPPED, detail="offline")] - registry = datadirs.load_registry(str(REPO_ROOT / "platforms" / "_data_dirs.yml")) + registry = load_data_dir_registry(REPO_ROOT / "platforms", required=True) sink = io.StringIO() with contextlib.redirect_stdout(sink): results = datadirs.refresh_all(registry, dry_run=True) diff --git a/scripts/generate_pack.py b/scripts/generate_pack.py index 2e0eca553..4d101e9a7 100644 --- a/scripts/generate_pack.py +++ b/scripts/generate_pack.py @@ -1309,10 +1309,9 @@ def _requested_platforms(args: argparse.Namespace, parser: argparse.ArgumentPars def _refresh_data_directories(args: argparse.Namespace, data_registry: dict) -> None: """Bring the data directory caches up to date before a build reads them.""" - from packs.datadirs import load_registry, refresh_all + from packs.datadirs import refresh_all - registry = load_registry(os.path.join(args.platforms_dir, "_data_dirs.yml")) - results = refresh_all(registry, force=args.refresh_data) + results = refresh_all(data_registry, force=args.refresh_data) updated = sum(1 for v in results.values() if v) if updated: print(f"Refreshed {updated} data director{'ies' if updated > 1 else 'y'}") diff --git a/scripts/model/platforms.py b/scripts/model/platforms.py index 38daad666..fd0bceb82 100644 --- a/scripts/model/platforms.py +++ b/scripts/model/platforms.py @@ -48,6 +48,23 @@ def _inherited_yaml(platform_name: str, platforms_dir: str) -> tuple[dict, list[ return merged, [platform_name, *chain] +def inheritance_chain(platform: str, platforms_dir: str | os.PathLike[str]) -> list[str]: + """The platform and every platform its file inherits from, nearest first. + + Stops at a file that does not exist or at a name already walked. + """ + chain: list[str] = [] + name: str | None = platform + while name and name not in chain: + path = os.path.join(platforms_dir, f"{name}.yml") + if not os.path.isfile(path): + break + chain.append(name) + inherits = (source_yaml_file(path) or {}).get("inherits") + name = str(inherits) if inherits else None + return chain + + def _cached_platform_yaml(path: str) -> dict: """A registry or shared-group file, parsed once per real path.""" real = os.path.realpath(path) diff --git a/scripts/model/registry.py b/scripts/model/registry.py index 556371136..73ffdb239 100644 --- a/scripts/model/registry.py +++ b/scripts/model/registry.py @@ -11,13 +11,22 @@ from core.cli import InputMissing from model.sources import source_yaml_file -def load_data_dir_registry(platforms_dir: str = PLATFORMS_DIR) -> dict: - """Load the data directory registry from _data_dirs.yml.""" - registry_path = os.path.join(platforms_dir, "_data_dirs.yml") +def data_dir_registry_at(registry_path: str | os.PathLike[str], required: bool = False) -> dict: + """The `data_directories:` mapping of a data directory registry file. + + An absent file is an empty registry, or with ``required`` an input the + command cannot run without. + """ if not os.path.exists(registry_path): + if required: + raise InputMissing(f"Registry not found: {registry_path}") return {} - data = source_yaml_file(registry_path) or {} - return data.get("data_directories", {}) + return (source_yaml_file(registry_path) or {}).get("data_directories") or {} + + +def load_data_dir_registry(platforms_dir: str | Path = PLATFORMS_DIR, required: bool = False) -> dict: + """Load the data directory registry from _data_dirs.yml.""" + 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: diff --git a/scripts/packs/datadirs.py b/scripts/packs/datadirs.py index c4fffec08..44bffcda9 100644 --- a/scripts/packs/datadirs.py +++ b/scripts/packs/datadirs.py @@ -16,9 +16,7 @@ from collections.abc import Callable, Iterator from pathlib import Path 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.sources import source_yaml_file from model.registry import VERSIONS_FILE, load_versions @@ -35,14 +33,6 @@ DOWNLOAD_RETRY_WAITS = (5, 20) _TRANSIENT = (urllib.error.URLError, OSError, tarfile.TarError, zipfile.BadZipFile, EOFError) -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}") - data = source_yaml_file(path) or {} - return data.get("data_directories", {}) - - def cache_lock( cache_dir: str | Path, shared: bool = False ) -> contextlib.AbstractContextManager[None]: diff --git a/scripts/refresh_data_dirs.py b/scripts/refresh_data_dirs.py index d9947df86..2cb2bdf20 100644 --- a/scripts/refresh_data_dirs.py +++ b/scripts/refresh_data_dirs.py @@ -18,7 +18,8 @@ import os from core.cli import suggest_names from model.cliargs import platform_arg, require_platform -from packs.datadirs import DEFAULT_REGISTRY, load_registry, log, refresh_all, refresh_entry +from model.registry import data_dir_registry_at +from packs.datadirs import DEFAULT_REGISTRY, log, refresh_all, refresh_entry def summarize(outcomes: dict[str, bool | None], dry_run: bool) -> str: @@ -59,7 +60,7 @@ def main() -> None: if args.platform: # The registry sits in the platforms directory it serves. require_platform(args.platform, os.path.dirname(args.registry) or ".") - registry = load_registry(args.registry) + registry = data_dir_registry_at(args.registry, required=True) if args.key: if args.key not in registry: diff --git a/scripts/refresh_stale.py b/scripts/refresh_stale.py index 8ac193e76..4430e119a 100755 --- a/scripts/refresh_stale.py +++ b/scripts/refresh_stale.py @@ -61,7 +61,8 @@ from concurrent.futures import FIRST_COMPLETED, ThreadPoolExecutor, wait from dataclasses import dataclass from functools import lru_cache from pathlib import Path -from model.registry import load_platform_registry +from model.platforms import inheritance_chain +from model.registry import data_dir_registry_at, load_platform_registry from core.paths import REPO_ROOT LOG_DIR = REPO_ROOT / "tmp" / "refresh_stale" @@ -106,17 +107,11 @@ def _load_platform_registry() -> dict[str, dict]: def _platform_parents(registry: dict[str, dict]) -> dict[str, str]: """Platform to the platform its YAML inherits from.""" - import yaml - parents: dict[str, str] = {} for name in registry: - path = REPO_ROOT / "platforms" / f"{name}.yml" - if not path.is_file(): - continue - with path.open(encoding="utf-8") as fh: - parent = (yaml.safe_load(fh) or {}).get("inherits") - if parent: - parents[name] = str(parent) + chain = inheritance_chain(name, REPO_ROOT / "platforms") + if len(chain) > 1: + parents[name] = chain[1] return parents @@ -131,10 +126,7 @@ def _ancestors(platform: str, parents: dict[str, str]) -> set[str]: @lru_cache(maxsize=1) def _data_dir_keys() -> frozenset[str]: """The entries refresh_data_dirs.py --key accepts.""" - import yaml - - with DATA_DIRS_REGISTRY.open(encoding="utf-8") as fh: - return frozenset((yaml.safe_load(fh) or {}).get("data_directories") or {}) + return frozenset(data_dir_registry_at(DATA_DIRS_REGISTRY, required=True)) def _run_check_freshness(areas: tuple[str, ...], extra: list[str]) -> list[dict]: diff --git a/scripts/scraper/buildbot_system.py b/scripts/scraper/buildbot_system.py index f5e60ef1e..d4f42bfe9 100644 --- a/scripts/scraper/buildbot_system.py +++ b/scripts/scraper/buildbot_system.py @@ -9,8 +9,7 @@ import urllib.error import urllib.parse import urllib.request -from model.safeparse import yaml_load -from model.registry import load_versions +from model.registry import data_dir_registry_at, load_versions from .base_scraper import fetch_text @@ -36,10 +35,8 @@ def load_tracked_entries( Returns {decoded_zip_name: (key, source_url)}. """ - with open(registry_path) as f: - data = yaml_load(f) or {} entries: dict[str, tuple[str, str]] = {} - for key, entry in data.get("data_directories", {}).items(): + for key, entry in data_dir_registry_at(registry_path, required=True).items(): url = entry.get("source_url", "") if "buildbot.libretro.com/assets/system" not in url: continue diff --git a/scripts/validate_schemas.py b/scripts/validate_schemas.py index c59ad7659..a37488b27 100644 --- a/scripts/validate_schemas.py +++ b/scripts/validate_schemas.py @@ -13,7 +13,7 @@ from pathlib import Path, PurePosixPath import yaml -from model.registry import load_platform_registry +from model.registry import load_data_dir_registry, load_platform_registry from model.profiles import source_yaml_paths from model.safeparse import yaml_load from core.paths import PLATFORMS_DIR, REPO_ROOT @@ -475,9 +475,7 @@ def _unknown_data_dir_refs() -> list[str]: every run printed "not cached" while refresh_data_dirs had nothing to refresh. """ - registry_path = REPO_ROOT / "platforms" / "_data_dirs.yml" - with registry_path.open(encoding="utf-8") as handle: - registered = set((yaml_load(handle) or {}).get("data_directories", {})) + registered = set(load_data_dir_registry(REPO_ROOT / "platforms", required=True)) out: list[str] = [] for directory in (REPO_ROOT / "emulators", REPO_ROOT / "platforms"): for path in source_yaml_paths(directory): diff --git a/tests/test_check_freshness.py b/tests/test_check_freshness.py index 73aa8dc7a..993ab54fd 100644 --- a/tests/test_check_freshness.py +++ b/tests/test_check_freshness.py @@ -90,6 +90,21 @@ class NativeCacheTests(unittest.TestCase): self.assertEqual(cf._transcribed_at(platforms, "child"), 300.0) self.assertEqual(cf._transcribed_at(platforms, "parent"), 300.0) + def test_a_repeated_inherits_key_is_refused(self): + """refresh_stale read inherits: with yaml.safe_load, which kept the + second of two keys the platform loader refuses.""" + import refresh_stale + from core.cli import SourceUnreadable + + platforms = self.cache / "platforms" + platforms.mkdir() + (platforms / "child.yml").write_text( + "inherits: a\ninherits: b\n", encoding="utf-8" + ) + with mock.patch.object(refresh_stale, "REPO_ROOT", self.cache), \ + self.assertRaisesRegex(SourceUnreadable, "duplicate key 'inherits'"): + refresh_stale._platform_parents({"child": {}}) + def test_every_registered_platform_with_an_exporter_gets_a_row(self): rows = cf.check_native(REPO_ROOT / "platforms", self.cache, self.cache / "truth") self.assertTrue(rows) diff --git a/tests/test_refresh_data_dirs.py b/tests/test_refresh_data_dirs.py index 93fb106b7..c959273f9 100644 --- a/tests/test_refresh_data_dirs.py +++ b/tests/test_refresh_data_dirs.py @@ -22,7 +22,7 @@ from unittest import mock import refresh_data_dirs as rdd from packs import datadirs -from model.registry import load_versions +from model.registry import load_data_dir_registry, load_versions from packs.archive import Placed from packs.datatrees import data_directory_members @@ -394,7 +394,7 @@ class ASourceThatMovesIsPinnedOrFollowed(unittest.TestCase): def test_every_forge_source_takes_a_commit(self): """archive/refs/heads/ is no address: a forge source must be written so the commit the refresh reads can replace its branch.""" - registry = datadirs.load_registry(str(REPO_ROOT / "platforms" / "_data_dirs.yml")) + registry = load_data_dir_registry(REPO_ROOT / "platforms", required=True) for key, entry in registry.items(): if not datadirs.revisioned(entry): continue diff --git a/tests/test_tool_messages.py b/tests/test_tool_messages.py index 8f236f849..9783d0dd1 100644 --- a/tests/test_tool_messages.py +++ b/tests/test_tool_messages.py @@ -155,12 +155,12 @@ class ADamagedProfileNamesItself(unittest.TestCase): 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 + from model.registry import data_dir_registry_at 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))): + for read in (load_setup, platform_revision, data_dir_registry_at): with self.subTest(read=read), self.assertRaisesRegex( SourceUnreadable, rf"{re.escape(str(bad))}:\d+: " ):