refactor: read data/.versions.json in one place

This commit is contained in:
Abdessamad Derraz committed 2026-11-21 05:59:51 +01:00
1 parent 67cb99606d
commit 82d3f595de
5 files changed
+14 -32

No files matched your search

+4 -4
View File
@@ -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"))
+4 -18
View File
@@ -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:
+2 -5
View File
@@ -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 {}
+2 -4
View File
@@ -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}")
+2 -1
View File
@@ -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"}})