refactor: route atomic writes through one helper

This commit is contained in:
Abdessamad Derraz committed 2026-11-21 06:00:14 +01:00
1 parent 856883f690
commit 434d660647
7 files changed
+59 -111

No files matched your search

+30 -51
View File
@@ -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:
+3 -4
View File
@@ -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")
+2 -10
View File
@@ -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(
+3 -9
View File
@@ -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: