From 82d3f595defb43390d7424e21547949e2f3fa297 Mon Sep 17 00:00:00 2001 From: Abdessamad Derraz <3028866+Abdess@users.noreply.github.com> Date: Sat, 21 Nov 2026 04:35:26 +0100 Subject: [PATCH] refactor: read data/.versions.json in one place --- scripts/model/registry.py | 8 ++++---- scripts/packs/datadirs.py | 22 ++++------------------ scripts/packs/datatrees.py | 7 ++----- scripts/sitegen/lookup.py | 6 ++---- tests/test_refresh_data_dirs.py | 3 ++- 5 files changed, 14 insertions(+), 32 deletions(-) diff --git a/scripts/model/registry.py b/scripts/model/registry.py index 73ffdb239..575f4b0e1 100644 --- a/scripts/model/registry.py +++ b/scripts/model/registry.py @@ -87,9 +87,9 @@ def list_release_pack_platforms(platforms_dir: str = PLATFORMS_DIR) -> list[str] VERSIONS_FILE = "data/.versions.json" -def load_versions(versions_path: str = VERSIONS_FILE) -> dict[str, dict]: +def load_versions(versions_path: str | os.PathLike[str] = VERSIONS_FILE) -> dict[str, dict]: + """What refresh_data_dirs recorded of each tree's last fetch.""" path = Path(versions_path) - if not path.exists(): + if not path.is_file(): return {} - with open(path) as f: - return json.load(f) + return json.loads(path.read_text(encoding="utf-8")) diff --git a/scripts/packs/datadirs.py b/scripts/packs/datadirs.py index 44bffcda9..45055f337 100644 --- a/scripts/packs/datadirs.py +++ b/scripts/packs/datadirs.py @@ -15,7 +15,7 @@ import zipfile from collections.abc import Callable, Iterator from pathlib import Path -from core.artifacts import file_lock as _file_lock, set_plain_mode +from core.artifacts import file_lock as _file_lock, write_text_atomic from core.github import github_token from model.registry import VERSIONS_FILE, load_versions @@ -113,24 +113,10 @@ def _save_versions( """Write the version file whole or not at all. Truncating in place let a concurrent reader load an empty file and die - on JSONDecodeError. The scratch file sits beside the target so the - rename stays on one filesystem. + on JSONDecodeError. """ - path = Path(versions_path) - path.parent.mkdir(parents=True, exist_ok=True) - handle, scratch = tempfile.mkstemp( - dir=path.parent, prefix=f".{path.name}.", suffix=".tmp" - ) - try: - with os.fdopen(handle, "w") as f: - json.dump(versions, f, indent=2, sort_keys=True) - f.write("\n") - set_plain_mode(scratch) - os.replace(scratch, path) - except BaseException: - with contextlib.suppress(OSError): - os.unlink(scratch) - raise + Path(versions_path).parent.mkdir(parents=True, exist_ok=True) + write_text_atomic(versions_path, json.dumps(versions, indent=2, sort_keys=True) + "\n") def _record_version(key: str, record: dict, versions_path: str) -> None: diff --git a/scripts/packs/datatrees.py b/scripts/packs/datatrees.py index 488c3d162..c093bea07 100644 --- a/scripts/packs/datatrees.py +++ b/scripts/packs/datatrees.py @@ -2,7 +2,6 @@ from __future__ import annotations -import json import os import re import zipfile @@ -13,6 +12,7 @@ from typing import TYPE_CHECKING, TypedDict from core.hashing import compute_hashes from core.options import reject_unknown from model.declarations import declared_root +from model.registry import load_versions from model.profiles import entry_system_ids, installed_data_refs from model.systems import norm_system_id from packs.archive import PackRecord, Placed, add_pack_member @@ -340,10 +340,7 @@ def _recorded_version(ref: str, entry: dict, versions: dict[str, dict[str, dict] return {} recorded = Path(cache).parent / ".versions.json" if str(recorded) not in versions: - try: - versions[str(recorded)] = json.loads(recorded.read_text()) - except FileNotFoundError: - versions[str(recorded)] = {} + versions[str(recorded)] = load_versions(recorded) found = versions[str(recorded)].get(ref) return found if isinstance(found, dict) else {} diff --git a/scripts/sitegen/lookup.py b/scripts/sitegen/lookup.py index 6788829b7..feb05c6ad 100644 --- a/scripts/sitegen/lookup.py +++ b/scripts/sitegen/lookup.py @@ -12,6 +12,7 @@ from pathlib import Path from core.hashing import parse_hash_list from model import siteinputs from model.collection import manufacturer_slug +from model.registry import load_versions from model.systemnames import system_name from packs.crossref import FileConsumers from sitegen.cards import PROVENANCE_LABELS, emulator_card_anchor, emulator_file_anchors @@ -121,10 +122,7 @@ def data_directory_members(install_dir: Path = REPO_ROOT / "install") -> dict[st def data_directory_revisions(data_dir: Path = REPO_ROOT / "data") -> dict[str, dict]: """The revision each data directory was fetched at, as refresh_data_dirs records it.""" - path = data_dir / ".versions.json" - if not path.is_file(): - return {} - return json.loads(path.read_text(encoding="utf-8")) + return load_versions(data_dir / ".versions.json") _GIT_COMMIT = re.compile(r"[0-9a-f]{40}") diff --git a/tests/test_refresh_data_dirs.py b/tests/test_refresh_data_dirs.py index c959273f9..a954f4c8d 100644 --- a/tests/test_refresh_data_dirs.py +++ b/tests/test_refresh_data_dirs.py @@ -173,7 +173,8 @@ class RefreshConcurrency(unittest.TestCase): def test_version_file_is_never_left_truncated(self): Path(self.versions).parent.mkdir(parents=True) Path(self.versions).write_text(json.dumps({"keep": {"sha": "1"}})) - with mock.patch.object(datadirs.json, "dump", side_effect=OSError("disk full")), self.assertRaises(OSError): + with mock.patch("core.artifacts.os.replace", side_effect=OSError("disk full")), \ + self.assertRaises(OSError): datadirs._save_versions({"keep": {"sha": "2"}}, self.versions) self.assertEqual(json.loads(Path(self.versions).read_text()), {"keep": {"sha": "1"}})