Files
MDHelper/mdhelper/file_versions.py
T

198 lines
8.2 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Atomic writes and bounded, per-document local version history."""
from __future__ import annotations
import hashlib
import os
import tempfile
import time
import uuid
from pathlib import Path
_UNCHECKED = object()
def fingerprint(path: Path):
try:
with path.open('rb') as stream:
digest = hashlib.sha256()
for block in iter(lambda: stream.read(1024 * 1024), b''): digest.update(block)
return digest.hexdigest()
except FileNotFoundError:
return None
def _replace_with_backup(temporary: Path, path: Path, backup: Path) -> None:
"""Retain the exact file displaced at the commit boundary, not an earlier copy."""
if os.name != 'nt':
# Never silently fall back to an unchecked overwrite on another platform.
raise OSError('当前平台不支持受保护的文件替换。')
import ctypes
from ctypes import wintypes
replace = ctypes.WinDLL('kernel32', use_last_error=True).ReplaceFileW
replace.argtypes = [wintypes.LPCWSTR] * 3 + [wintypes.DWORD, wintypes.LPVOID, wintypes.LPVOID]
replace.restype = wintypes.BOOL
if not replace(str(path), str(temporary), str(backup), 0, None, None):
raise ctypes.WinError(ctypes.get_last_error())
def _recovery_path(path: Path) -> Path:
return path.with_name(f'.{path.name}.conflict-{uuid.uuid4().hex}.bak')
def _checked_replace(temporary: Path, path: Path, expected: str | None) -> None:
if fingerprint(path) != expected:
raise OSError(f'文件发生变化,已停止替换:{path}')
if expected is None:
# Creating the directory entry must fail if another process got there first.
# Windows rename is exclusive and also works on volumes without hardlinks.
if os.name == 'nt': os.rename(temporary, path)
else: os.link(temporary, path)
return
backup = _recovery_path(path)
try:
published = fingerprint(temporary)
_replace_with_backup(temporary, path, backup)
if fingerprint(backup) == expected:
try:
backup.unlink()
except OSError:
pass # A retained backup must not turn a committed write into failure.
return
# Retain the conflicting version even if another process saves again
# during recovery. Every displaced file has its own recovery name.
if fingerprint(path) == published:
descriptor, restore_name = tempfile.mkstemp(dir=path.parent, suffix='.tmp')
restore = Path(restore_name)
try:
with os.fdopen(descriptor, 'wb') as stream:
stream.write(backup.read_bytes())
displaced = _recovery_path(path)
_replace_with_backup(restore, path, displaced)
if fingerprint(displaced) == published:
displaced.unlink()
finally:
restore.unlink(missing_ok=True)
raise OSError(f'文件在替换时发生变化,已保留冲突版本:{backup}')
except OSError as exc:
if backup.exists():
raise OSError(f'文件替换未完成,恢复副本位于 {backup}:{exc}') from exc
raise
def checked_remove(path: Path, expected: str) -> None:
"""Rollback a newly created output without deleting a concurrent save."""
if fingerprint(path) != expected:
raise OSError(f'文件已被外部修改,保留当前内容:{path}')
recovery = _recovery_path(path)
path.rename(recovery)
if fingerprint(recovery) == expected:
recovery.unlink()
else:
try:
os.link(recovery, path) # Exclusive restore; never overwrite a newer file.
except OSError:
pass
raise OSError(f'文件在恢复时发生变化,保留副本:{recovery}')
def atomic_write(path: Path, data: bytes, *, expected=_UNCHECKED) -> None:
path = path.resolve()
path.parent.mkdir(parents=True, exist_ok=True)
descriptor, temporary = tempfile.mkstemp(prefix=f".{path.name}.", suffix=".tmp", dir=path.parent)
try:
with os.fdopen(descriptor, "wb") as stream:
stream.write(data)
stream.flush()
os.fsync(stream.fileno())
if expected is _UNCHECKED:
os.replace(temporary, path)
else:
_checked_replace(Path(temporary), path, expected)
finally:
Path(temporary).unlink(missing_ok=True)
class VersionStore:
def __init__(self, root: Path | None = None, limit: int = 20) -> None:
base = Path(os.environ.get("LOCALAPPDATA", str(Path.home() / ".local" / "share")))
self.root = root or Path(os.environ.get("MDHELPER_HISTORY_DIR", str(base / "MDHelper" / "history")))
self.limit = max(1, limit)
def directory(self, path: Path) -> Path:
key = hashlib.sha256(os.path.normcase(str(path.resolve())).encode("utf-8")).hexdigest()
return self.root / key
def versions(self, path: Path) -> list[Path]:
return sorted(self.directory(path).glob("*.md"), reverse=True)
def save(self, path: Path, source: str) -> None:
data = source.encode("utf-8")
previous = path.read_bytes() if path.exists() else None
if previous == data:
return
if previous is not None:
versions = self.versions(path)
if not versions or versions[0].read_bytes() != previous:
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)
for expired in self.versions(path)[self.limit:]:
try:
expired.unlink()
except OSError:
pass # History housekeeping must not turn a successful save into a failure.
def show_version_history(parent: object, path: Path, current: str) -> str | None:
import difflib
from PySide6.QtWidgets import (QDialog, QDialogButtonBox, QHBoxLayout, QLabel,
QListWidget, QPlainTextEdit, QSplitter, QVBoxLayout)
from PySide6.QtCore import Qt
versions = VersionStore().versions(path)
dialog = QDialog(parent)
dialog.setWindowTitle(f"历史版本 — {path.name}")
dialog.resize(1000, 650)
layout = QVBoxLayout(dialog)
layout.addWidget(QLabel("保留最近 20 个保存前版本。恢复只替换编辑区内容,可撤销;按保存后才写入原文件。"))
splitter = QSplitter(Qt.Orientation.Horizontal)
listing = QListWidget()
preview = QPlainTextEdit()
preview.setReadOnly(True)
splitter.addWidget(listing)
splitter.addWidget(preview)
splitter.setSizes([240, 760])
layout.addWidget(splitter)
buttons = QDialogButtonBox(QDialogButtonBox.StandardButton.Cancel)
restore = buttons.addButton("恢复到编辑区", QDialogButtonBox.ButtonRole.AcceptRole)
restore.setEnabled(False)
buttons.accepted.connect(dialog.accept)
buttons.rejected.connect(dialog.reject)
layout.addWidget(buttons)
contents: dict[int, str] = {}
for version in versions:
stamp = version.name[:15]
listing.addItem(f"{stamp[:4]}-{stamp[4:6]}-{stamp[6:8]} {stamp[9:11]}:{stamp[11:13]}:{stamp[13:15]}")
def selected(row: int) -> None:
restore.setEnabled(False)
if row < 0:
return
try:
source = versions[row].read_text(encoding="utf-8-sig")
contents[row] = source
diff = "\n".join(difflib.unified_diff(current.splitlines(), source.splitlines(),
fromfile="当前编辑内容", tofile="选中的历史版本", lineterm=""))
preview.setPlainText(diff or "此版本与当前编辑内容相同。")
restore.setEnabled(True)
except (OSError, UnicodeError) as exc:
preview.setPlainText(f"无法读取此版本:{exc}")
listing.currentRowChanged.connect(selected)
if versions:
listing.setCurrentRow(0)
else:
preview.setPlainText("暂无历史版本。文件内容改变并保存后,会自动保留保存前的内容。")
return contents.get(listing.currentRow()) if dialog.exec() == QDialog.DialogCode.Accepted else None