Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 16 additions & 2 deletions src/specify_cli/events.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
import sys
import subprocess
import platform
import tempfile
from pathlib import Path
from typing import TYPE_CHECKING, Any

Expand Down Expand Up @@ -2010,10 +2011,23 @@ def _load_user_json(path: Path) -> dict | None:


def _safe_write_json(dst: Path, data: dict) -> None:
"""Write *data* as JSON to *dst* after validating the destination (#12)."""
"""Write *data* as JSON to *dst* atomically after validating the destination (#12)."""
_ensure_safe_destination(dst)
dst.parent.mkdir(parents=True, exist_ok=True)
dst.write_text(json.dumps(data, indent=2) + "\n", encoding="utf-8")
fd, tmp = tempfile.mkstemp(
dir=str(dst.parent), prefix=f".{dst.name}.", suffix=".tmp"
)
try:
with os.fdopen(fd, "w", encoding="utf-8") as f:
json.dump(data, f, indent=2)
f.write("\n")
os.replace(tmp, dst)
except BaseException:
try:
os.unlink(tmp)
except OSError:
pass
raise


def _ensure_safe_destination(dst: Path) -> None:
Expand Down