"""Atomic file writes. A reader must never observe a partially written file. Every write goes to a temporary file in the destination directory, is flushed and fsynced, and is then moved into place with an atomic rename. On failure the temporary file is removed and any existing destination file is left untouched. """ from __future__ import annotations import json import os import tempfile from pathlib import Path __all__ = ["atomic_write_bytes", "atomic_write_json", "atomic_write_text"] def atomic_write_bytes(path: Path, data: bytes) -> None: """Atomically write ``data`` to ``path``, creating parent directories.""" path.parent.mkdir(parents=True, exist_ok=True) fd, tmp_name = tempfile.mkstemp(prefix=f".{path.name}.", suffix=".tmp", dir=path.parent) tmp_path = Path(tmp_name) try: with os.fdopen(fd, "wb") as handle: handle.write(data) handle.flush() os.fsync(handle.fileno()) tmp_path.replace(path) except BaseException: tmp_path.unlink(missing_ok=True) raise def atomic_write_text(path: Path, text: str, encoding: str = "utf-8") -> None: """Atomically write ``text`` to ``path`` with the given encoding.""" atomic_write_bytes(path, text.encode(encoding)) def atomic_write_json(path: Path, obj: object) -> None: """Atomically write ``obj`` as pretty, key-sorted UTF-8 JSON with a trailing newline. Raises: TypeError: if ``obj`` is not JSON-serialisable (nothing is written). """ text = json.dumps(obj, ensure_ascii=False, indent=2, sort_keys=True) + "\n" atomic_write_text(path, text)