diff --git a/scripts/core/artifacts.py b/scripts/core/artifacts.py index d2b0ba8f1..fab1b004b 100644 --- a/scripts/core/artifacts.py +++ b/scripts/core/artifacts.py @@ -101,22 +101,30 @@ def set_plain_mode(path: str | os.PathLike) -> None: os.chmod(path, plain_file_mode()) -def write_text_atomic(path: str, content: str) -> None: - """Write a whole file or nothing. +@contextlib.contextmanager +def atomic_scratch( + path: str | os.PathLike, suffix: str = ".tmp", plain_mode: bool = True +) -> Iterator[str]: + """A unique scratch file beside path, renamed onto it once filled. Truncate-then-write leaves a half-written artifact behind an interrupt: a partial database.json, manifest or README.md is committed-looking and - silently wrong. The scratch file sits beside the target so the rename - stays on one filesystem, which is what makes it atomic. + silently wrong. A fixed scratch name let two runs interleave their bytes + in one file of the right size, which the rename then promoted. The + scratch sits beside the target so the rename stays on one filesystem, + which is what makes it atomic. plain_mode=False keeps the mode the + filler gave the scratch (a copy2 of the source). """ + path = os.fspath(path) directory = os.path.dirname(os.path.abspath(path)) handle, scratch = tempfile.mkstemp( - dir=directory, prefix=f".{os.path.basename(path)}.", suffix=".tmp" + dir=directory, prefix=f".{os.path.basename(path)}.", suffix=suffix ) + os.close(handle) try: - with os.fdopen(handle, "w", encoding="utf-8") as f: - f.write(content) - set_plain_mode(scratch) + yield scratch + if plain_mode: + set_plain_mode(scratch) os.replace(scratch, path) except BaseException: with contextlib.suppress(OSError): @@ -124,21 +132,16 @@ def write_text_atomic(path: str, content: str) -> None: raise -def write_bytes_atomic(path: str, content: bytes) -> None: - """Write a whole binary file or nothing, as write_text_atomic does.""" - directory = os.path.dirname(os.path.abspath(path)) - handle, scratch = tempfile.mkstemp( - dir=directory, prefix=f".{os.path.basename(path)}.", suffix=".tmp" - ) - try: - with os.fdopen(handle, "wb") as f: - f.write(content) - set_plain_mode(scratch) - os.replace(scratch, path) - except BaseException: - with contextlib.suppress(OSError): - os.unlink(scratch) - raise +def write_text_atomic(path: str | os.PathLike, content: str) -> None: + """Write a whole file or nothing.""" + with atomic_scratch(path) as scratch, open(scratch, "w", encoding="utf-8") as f: + f.write(content) + + +def write_bytes_atomic(path: str | os.PathLike, content: bytes) -> None: + """Write a whole binary file or nothing.""" + with atomic_scratch(path) as scratch, open(scratch, "wb") as f: + f.write(content) @contextlib.contextmanager @@ -167,40 +170,16 @@ def copy_file_atomic(source: str, path: str) -> None: """Copy a file into place whole or not at all, metadata included.""" import shutil - directory = os.path.dirname(os.path.abspath(path)) - handle, scratch = tempfile.mkstemp( - dir=directory, prefix=f".{os.path.basename(path)}.", suffix=".tmp" - ) - os.close(handle) - try: + with atomic_scratch(path, plain_mode=False) as scratch: shutil.copy2(source, scratch) - os.replace(scratch, path) - except BaseException: - with contextlib.suppress(OSError): - os.unlink(scratch) - raise def copy_stream_atomic(stream: BinaryIO, path: str) -> None: - """Stream a download into place whole or not at all. - - A fixed scratch name let two runs interleave their bytes in one file of - the right size, which the rename then promoted.""" + """Stream a download into place whole or not at all.""" import shutil - directory = os.path.dirname(os.path.abspath(path)) - handle, scratch = tempfile.mkstemp( - dir=directory, prefix=f".{os.path.basename(path)}.", suffix=".tmp" - ) - try: - with os.fdopen(handle, "wb") as f: - shutil.copyfileobj(stream, f) - set_plain_mode(scratch) - os.replace(scratch, path) - except BaseException: - with contextlib.suppress(OSError): - os.unlink(scratch) - raise + with atomic_scratch(path) as scratch, open(scratch, "wb") as f: + shutil.copyfileobj(stream, f) def _strip_timestamps(text: str) -> str: diff --git a/scripts/core/statefile.py b/scripts/core/statefile.py index 055b1d690..b72f95367 100644 --- a/scripts/core/statefile.py +++ b/scripts/core/statefile.py @@ -4,9 +4,10 @@ from __future__ import annotations import datetime as dt import json -import os from pathlib import Path +from core.artifacts import write_text_atomic + def now_iso() -> str: return dt.datetime.now(dt.timezone.utc).replace(microsecond=0).isoformat() @@ -14,6 +15,4 @@ def now_iso() -> str: def save_state(path: Path, state: dict) -> None: path.parent.mkdir(parents=True, exist_ok=True) - scratch = path.with_suffix(".tmp") - scratch.write_text(json.dumps(state, indent=2, sort_keys=True) + "\n", encoding="utf-8") - os.replace(scratch, path) + write_text_atomic(path, json.dumps(state, indent=2, sort_keys=True) + "\n") diff --git a/scripts/core/upstream.py b/scripts/core/upstream.py index b56f1c0ee..d137e8a55 100644 --- a/scripts/core/upstream.py +++ b/scripts/core/upstream.py @@ -25,7 +25,7 @@ from dataclasses import dataclass from datetime import datetime from pathlib import Path -from core.artifacts import set_plain_mode +from core.artifacts import write_text_atomic USER_AGENT = "retrobios-profile-sync/1.0" # Where fetched upstream files live, shared by every reader of this cache. @@ -401,15 +401,7 @@ def write_cache(target: Path, text: str) -> None: target.parent.mkdir(parents=True, exist_ok=True) except (FileExistsError, NotADirectoryError): return - fd, scratch = tempfile.mkstemp(dir=str(target.parent), suffix=".part") - try: - with os.fdopen(fd, "w", encoding="utf-8") as fh: - fh.write(text) - set_plain_mode(scratch) - os.replace(scratch, target) - except OSError: - Path(scratch).unlink(missing_ok=True) - raise + write_text_atomic(target, text) def fetch_file( diff --git a/scripts/core/ziptools.py b/scripts/core/ziptools.py index 2ffcd4d1c..322b084ba 100644 --- a/scripts/core/ziptools.py +++ b/scripts/core/ziptools.py @@ -15,7 +15,7 @@ import sys import tempfile import zipfile -from core.artifacts import process_umask, set_plain_mode +from core.artifacts import process_umask, write_text_atomic from core.hashing import MAX_HASHED_MEMBER, md5sum from core.paths import REPO_ROOT @@ -141,17 +141,11 @@ def _read_member_cache(path: str) -> dict[str, list[list]]: def _write_member_cache(path: str, data: dict[str, list[list]]) -> None: import json - os.makedirs(os.path.dirname(path), exist_ok=True) - fd, scratch = tempfile.mkstemp(dir=os.path.dirname(path), suffix=".tmp") try: - with os.fdopen(fd, "w", encoding="utf-8") as fh: - json.dump(data, fh, separators=(",", ":")) - set_plain_mode(scratch) - os.replace(scratch, path) + os.makedirs(os.path.dirname(path), exist_ok=True) + write_text_atomic(path, json.dumps(data, separators=(",", ":"))) except OSError as exc: print(f"warning: could not write {path}: {exc}", file=sys.stderr) - if os.path.exists(scratch): - os.unlink(scratch) def _members_md5(path: str) -> list[list] | None: diff --git a/scripts/packs/archive.py b/scripts/packs/archive.py index bcb7cafa6..3d4c5a441 100644 --- a/scripts/packs/archive.py +++ b/scripts/packs/archive.py @@ -5,13 +5,11 @@ from __future__ import annotations import contextlib import os import shutil -import tempfile import zipfile from collections.abc import Iterator from dataclasses import dataclass, field -from pathlib import Path -from core.artifacts import set_plain_mode +from core.artifacts import atomic_scratch from core.hashing import compute_hashes from core.paths import comparable_destination, sanitize_pack_path from packs.paths import has_path_conflict, register_path, placement_block @@ -120,19 +118,9 @@ def writing_pack(zip_path: str) -> Iterator[zipfile.ZipFile]: readable ZIP holding part of the files, which the run then checked and summed as the pack. """ - directory = os.path.dirname(zip_path) or "." - fd, scratch = tempfile.mkstemp( - prefix=f".{os.path.basename(zip_path)}.", suffix=".partial", dir=directory - ) - os.close(fd) - try: - with zipfile.ZipFile(scratch, "w", zipfile.ZIP_DEFLATED) as zf: - yield zf - set_plain_mode(scratch) - os.replace(scratch, zip_path) - except BaseException: - Path(scratch).unlink(missing_ok=True) - raise + with atomic_scratch(zip_path, suffix=".partial") as scratch, \ + zipfile.ZipFile(scratch, "w", zipfile.ZIP_DEFLATED) as zf: + yield zf # What the builder writes into a platform pack beside the files it carries. diff --git a/scripts/packs/finalize.py b/scripts/packs/finalize.py index 3c16511ce..8e1a1353d 100644 --- a/scripts/packs/finalize.py +++ b/scripts/packs/finalize.py @@ -6,15 +6,13 @@ import json import os import shutil import sys -import tempfile import zipfile from collections.abc import Iterable from dataclasses import dataclass -from pathlib import Path from typing import TYPE_CHECKING, TypedDict from core.paths import EMULATORS_DIR, PLATFORMS_DIR -from core.artifacts import set_plain_mode +from core.artifacts import atomic_scratch from core.options import reject_unknown from model.registry import list_registered_platforms from model.targets import load_target_config @@ -53,12 +51,7 @@ def inject_manifest(zip_path: str, manifest: dict) -> None: with zipfile.ZipFile(zip_path, "r") as zf: has_manifest = "manifest.json" in zf.namelist() - directory = os.path.dirname(zip_path) or "." - fd, scratch = tempfile.mkstemp( - prefix=f".{os.path.basename(zip_path)}.", suffix=".partial", dir=directory - ) - os.close(fd) - try: + with atomic_scratch(zip_path, suffix=".partial") as scratch: if not has_manifest: # Append to a copy. Append mode defaults to ZIP_STORED, which # would leave the manifest uncompressed and give the same pack @@ -74,11 +67,6 @@ def inject_manifest(zip_path: str, manifest: dict) -> None: continue dst.writestr(item, src.read(item.filename)) write_generated_member(dst, "manifest.json", manifest_json) - set_plain_mode(scratch) - os.replace(scratch, zip_path) - except BaseException: - Path(scratch).unlink(missing_ok=True) - raise def _target_cores_for( diff --git a/tests/test_atomic_artifacts.py b/tests/test_atomic_artifacts.py index bca980eb5..2f0eb0b75 100644 --- a/tests/test_atomic_artifacts.py +++ b/tests/test_atomic_artifacts.py @@ -49,6 +49,20 @@ class WholeOrNothing(unittest.TestCase): artifacts.copy_file_atomic(str(source), str(target)) self.assertEqual(os.listdir(target.parent), []) + def test_state_files_share_no_scratch_and_leave_none(self): + """save_state wrote through a fixed .tmp: state.json and + state.yaml shared one scratch, and an interrupted write left it.""" + from core.statefile import save_state + + target = self.dir / "state.json" + (self.dir / "state.tmp").write_text("other writer") + save_state(target, {"a": 1}) + self.assertEqual(target.read_text(), '{\n "a": 1\n}\n') + self.assertEqual((self.dir / "state.tmp").read_text(), "other writer") + with mock.patch("os.replace", side_effect=OSError("cut")), self.assertRaises(OSError): + save_state(target, {"a": 2}) + self.assertEqual(sorted(os.listdir(self.dir)), ["state.json", "state.tmp"]) + class EveryWriterGoesThroughIt(unittest.TestCase): def test_manifests_record_and_restore_use_the_atomic_helpers(self): @@ -232,11 +246,7 @@ class ScratchFilesGetThePlainMode(unittest.TestCase): self.assertIn("manifest.json", zf.namelist()) def test_every_renamed_scratch_gets_the_mode(self): - """A function that renames a mkstemp file into place sets its mode. - - copy_file_atomic is the one exception: copy2 gives the scratch the - source file's own mode. - """ + """A function that renames a mkstemp file into place sets its mode.""" import ast def name_of(node: ast.AST) -> str | None: @@ -252,8 +262,6 @@ class ScratchFilesGetThePlainMode(unittest.TestCase): for func in ast.walk(tree): if not isinstance(func, (ast.FunctionDef, ast.AsyncFunctionDef)): continue - if func.name == "copy_file_atomic": - continue scratches: set[str] = set() for node in ast.walk(func): if (isinstance(node, ast.Assign) and isinstance(node.value, ast.Call)