Skip to content
Closed
Show file tree
Hide file tree
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
7 changes: 4 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -110,9 +110,10 @@ All yamltrip errors inherit from `YAMLTripError`:
(`doc.has_anchors()`) but not resolved during value extraction.
- **Large integers may lose precision.** YAML integers outside the signed
64-bit range (i64) may become `float` during deserialization.
- **Editor write-back is not atomic.** `Editor` detects external file changes
between enter and exit, but the check-then-write is racy. Do not use it
with concurrent writers.
- **Editor write-back is best-effort atomic.** `Editor` writes to a
temporary file then does an `os.replace`, so the target file is never
left half-written. External modifications between enter and exit are
detected, but the check is not locked against concurrent writers.

## Design Decisions

Expand Down
17 changes: 16 additions & 1 deletion src/yamltrip/editor.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@

from __future__ import annotations

import contextlib
import os
import tempfile
from pathlib import Path
from typing import TYPE_CHECKING, Any

Expand Down Expand Up @@ -62,7 +65,19 @@ def __exit__(
if current_source != self._original_source:
msg = f"File was modified externally: {self._path}"
raise RuntimeError(msg)
self._path.write_text(self._document.dumps(), encoding="utf-8")
content = self._document.dumps()
fd, tmp = tempfile.mkstemp(dir=self._path.parent, suffix=".tmp")
try:
os.write(fd, content.encode("utf-8"))
os.close(fd)
fd = -1
os.replace(tmp, self._path)
except BaseException:
if fd >= 0:
os.close(fd)
with contextlib.suppress(OSError):
os.unlink(tmp)
raise
self._original = None
self._document = None
self._original_source = None
Expand Down
Loading