Skip to content

Commit 11af75f

Browse files
Make Editor file write atomic via tempfile + os.replace
Write to a temporary file in the same directory then os.replace() onto the target, so the file is never left half-written on crash or disk-full.
1 parent 1bee8eb commit 11af75f

1 file changed

Lines changed: 16 additions & 1 deletion

File tree

src/yamltrip/editor.py

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,9 @@
22

33
from __future__ import annotations
44

5+
import contextlib
6+
import os
7+
import tempfile
58
from pathlib import Path
69
from typing import TYPE_CHECKING, Any
710

@@ -62,7 +65,19 @@ def __exit__(
6265
if current_source != self._original_source:
6366
msg = f"File was modified externally: {self._path}"
6467
raise RuntimeError(msg)
65-
self._path.write_text(self._document.dumps(), encoding="utf-8")
68+
content = self._document.dumps()
69+
fd, tmp = tempfile.mkstemp(dir=self._path.parent, suffix=".tmp")
70+
try:
71+
os.write(fd, content.encode("utf-8"))
72+
os.close(fd)
73+
fd = -1
74+
os.replace(tmp, self._path)
75+
except BaseException:
76+
if fd >= 0:
77+
os.close(fd)
78+
with contextlib.suppress(OSError):
79+
os.unlink(tmp)
80+
raise
6681
self._original = None
6782
self._document = None
6883
self._original_source = None

0 commit comments

Comments
 (0)