linux
This commit is contained in:
1 parent
f6f1ae20c2
commit
efd4e1dcf4
43 files changed
+25641
No files matched your search
@@ -0,0 +1,27 @@
|
||||
"""Atomic local JSON snapshots; callers must handle write failures explicitly."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def atomic_write_json(path: Path, payload) -> None:
|
||||
"""Flush a new snapshot before replacing the old file, or leave the old file intact."""
|
||||
path = Path(path)
|
||||
encoded = json.dumps(payload, ensure_ascii=False, allow_nan=False).encode("utf-8")
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
fd, temporary = tempfile.mkstemp(prefix=path.name + ".", suffix=".tmp", dir=path.parent)
|
||||
try:
|
||||
with os.fdopen(fd, "wb") as stream:
|
||||
stream.write(encoded)
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
os.replace(temporary, path)
|
||||
finally:
|
||||
try:
|
||||
os.unlink(temporary)
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
Reference in new issue
Block a user