diff --git a/src/specify_cli/events.py b/src/specify_cli/events.py index d3002fe805..aec830700b 100644 --- a/src/specify_cli/events.py +++ b/src/specify_cli/events.py @@ -17,6 +17,7 @@ import sys import subprocess import platform +import tempfile from pathlib import Path from typing import TYPE_CHECKING, Any @@ -1727,7 +1728,19 @@ def _merge_toml_fragment(dst: Path, fragment: str) -> None: flags=re.DOTALL, ) dst.parent.mkdir(parents=True, exist_ok=True) - dst.write_text(existing.rstrip() + "\n\n" + fragment + "\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: + f.write(existing.rstrip() + "\n\n" + fragment + "\n") + os.replace(tmp, dst) + except BaseException: + try: + os.unlink(tmp) + except OSError: + pass + raise def _remove_toml_entries(dst: Path) -> bool: @@ -1757,7 +1770,19 @@ def _remove_toml_entries(dst: Path) -> bool: if not stripped: dst.unlink(missing_ok=True) return True - dst.write_text(cleaned, 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: + f.write(cleaned) + os.replace(tmp, dst) + except BaseException: + try: + os.unlink(tmp) + except OSError: + pass + raise return False