fix: protect editor saves and clear failed restored tab state

This commit is contained in:
2026-11-05 21:38:35 +08:00
parent a3bef33988
commit 0e072eed3b
7 changed files with 192 additions and 22 deletions
+9 -3
View File
@@ -125,9 +125,15 @@ class VersionStore:
def versions(self, path: Path) -> list[Path]:
return sorted(self.directory(path).glob("*.md"), reverse=True)
def save(self, path: Path, source: str) -> None:
def save(self, path: Path, source: str, *, expected=_UNCHECKED) -> None:
data = source.encode("utf-8")
previous = path.read_bytes() if path.exists() else None
try:
previous = path.read_bytes()
except FileNotFoundError:
previous = None
snapshot = hashlib.sha256(previous).hexdigest() if previous is not None else None
if expected is not _UNCHECKED and snapshot != expected:
raise OSError(f'文件在比较后再次变化,已取消保存:{path}')
if previous == data:
return
if previous is not None:
@@ -136,7 +142,7 @@ class VersionStore:
name = time.strftime("%Y%m%d-%H%M%S") + f"-{time.time_ns() % 1_000_000_000:09d}-{uuid.uuid4().hex[:6]}.md"
atomic_write(self.directory(path) / name, previous)
# A failed replacement leaves the original file and its history intact.
atomic_write(path, data)
atomic_write(path, data, expected=snapshot)
for expired in self.versions(path)[self.limit:]:
try:
expired.unlink()