diff --git a/mdhelper/document_session.py b/mdhelper/document_session.py index 8ada24d..ffda823 100644 --- a/mdhelper/document_session.py +++ b/mdhelper/document_session.py @@ -8,7 +8,7 @@ from enum import Enum from pathlib import Path from typing import Callable, Protocol -from .file_versions import VersionStore +from .file_versions import VersionStore, _UNCHECKED FileSignature = tuple[int, int] | None DRAFTS_KEY = "editor/drafts" @@ -46,8 +46,8 @@ class DocumentStore: return relocate_images(source, original, target) @staticmethod - def save(path: Path, source: str) -> None: - VersionStore().save(path, source) + def save(path: Path, source: str, *, expected=_UNCHECKED) -> None: + VersionStore().save(path, source, expected=expected) class DraftStore: diff --git a/mdhelper/file_versions.py b/mdhelper/file_versions.py index 0e7ac02..951bae8 100644 --- a/mdhelper/file_versions.py +++ b/mdhelper/file_versions.py @@ -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() diff --git a/mdhelper/main_window.py b/mdhelper/main_window.py index bebf0fc..81d38b4 100644 --- a/mdhelper/main_window.py +++ b/mdhelper/main_window.py @@ -1,6 +1,7 @@ from __future__ import annotations import html +import hashlib import copy import time import json @@ -2109,8 +2110,10 @@ class MainWindow(QMainWindow): original_path = editor.session.path target_path = target_path.resolve() disk_source = None + disk_bytes = None try: - disk_source = self._read_markdown_source(original_path) + disk_bytes = original_path.read_bytes() + disk_source = disk_bytes.decode('utf-8').replace('\r\n', '\n').replace('\r', '\n') unchanged = target_path == original_path and source == disk_source except (OSError, UnicodeError): unchanged = False @@ -2120,7 +2123,15 @@ class MainWindow(QMainWindow): self.status_label.setText("编辑内容未变化") return True - reviewed_disk = None + # Carry the compared bytes all the way to the protected replacement. + # In particular, image relocation must not open a new overwrite window. + try: + reviewed_disk = (disk_bytes,) if target_path == original_path else (target_path.read_bytes(),) + except FileNotFoundError: + reviewed_disk = (None,) + except OSError as exc: + QMessageBox.warning(self, "保存失败", str(exc)) + return False if target_path == original_path and (expected_signature != self._file_signature(target_path) or disk_source != editor.session.saved_source): from .save_conflict import resolve_save_conflict @@ -2217,12 +2228,14 @@ class MainWindow(QMainWindow): QMessageBox.warning(self, "保存失败", "只能保存 Markdown 文档。") return False + try: + actual = path.read_bytes() + except FileNotFoundError: + actual = None + except OSError as exc: + QMessageBox.warning(self, "保存失败", str(exc)) + return False if reviewed_disk is not None: - try: - actual = path.read_bytes() if path.exists() else None - except OSError as exc: - QMessageBox.warning(self, "保存失败", str(exc)) - return False if actual != reviewed_disk[0]: QMessageBox.warning(self, "文件再次变化", "比较期间磁盘文件再次变化,本次保存已取消。请重新保存以查看最新差异。") return False @@ -2240,7 +2253,8 @@ class MainWindow(QMainWindow): self.internal_save_paths.add(path) try: - self.documents.save(path, source) + expected = hashlib.sha256(actual).hexdigest() if actual is not None else None + self.documents.save(path, source, expected=expected) except OSError as exc: self.internal_save_paths.discard(path) LOGGER.exception("Failed to save Markdown source: %s", path) @@ -4524,7 +4538,7 @@ class MainWindow(QMainWindow): state = host.workspace_state path = Path(state.path) if not path.is_file(): - host.welcome_view.setPlainText(f"文件已不存在:\n{path}") + self._workspace_load_failed(host, f"文件已不存在:\n{path}") return # Replacing a restored reader with its editor must not activate and # load the neighbouring background tab during the intermediate removal. @@ -4538,6 +4552,10 @@ class MainWindow(QMainWindow): self.current_file = path if path.suffix.lower() in {".md", ".markdown"} or is_code_document(path): self.open_document(path, add_history=False, scroll_y=state.scroll) + if host.reader_view.property('current_file') != str(path): + host.workspace_state = state + self._workspace_load_failed(host, f"无法加载文档:\n{path}\n请检查文件后重新选择此标签。") + return elif path.suffix.lower() in {".html", ".htm", ".xhtml"}: self._open_webpage_file_now(path) else: @@ -4555,6 +4573,20 @@ class MainWindow(QMainWindow): QTimer.singleShot(0, editor, lambda: editor.editor.verticalScrollBar().setValue(state.source_scroll)) self._on_tab_changed(self.tabs.currentIndex()) + def _workspace_load_failed(self, host, message: str) -> None: + # Keep the lazy state for a later retry, but never leave actions pointing + # at the document that was active before the failed tab was selected. + self.current_file = None + self.current_fragment = self.pending_fragment = self.pending_find_text = '' + self.pending_scroll_y = None + host.welcome_view.setPlainText(message) + host.stack.setCurrentWidget(host.welcome_view) + self.setWindowTitle(f'{Path(host.workspace_state.path).name} - MDHelper') + self.status_label.setText(message.splitlines()[0]) + self.toc_tree.clear() + self._update_watched_paths() + self._update_actions() + @property def editor_drafts(self) -> dict: diff --git a/tests/test_content_revision_058.py b/tests/test_content_revision_058.py new file mode 100644 index 0000000..93e8123 --- /dev/null +++ b/tests/test_content_revision_058.py @@ -0,0 +1,82 @@ +"""Ordinary saves must protect the exact disk version reviewed by the editor.""" +from pathlib import Path +import pytest +from PySide6.QtCore import QSettings +from PySide6.QtWidgets import QMessageBox +from mdhelper import file_versions as files, main_window +from mdhelper.document_session import DocumentStore + + +@pytest.mark.parametrize('boundary', ['store', 'flush', 'replace']) +def test_editor_save_conflict_preserves_external_file_and_unsaved_buffer(qt_application, tmp_path, monkeypatch, boundary): + settings = QSettings(str(tmp_path/'settings.ini'), QSettings.Format.IniFormat) + monkeypatch.setattr(main_window, 'QSettings', lambda *_: settings) + monkeypatch.setenv('MDHELPER_HISTORY_DIR', str(tmp_path/'history')) + monkeypatch.setattr(QMessageBox, 'warning', lambda *args: QMessageBox.StandardButton.Cancel) + path = tmp_path/'note.md'; path.write_bytes(b'Original') + window = main_window.MainWindow(tmp_path) + try: + window.open_document(path); window.edit_current_markdown() + editor = window.tabs.currentWidget() + editor.replace_source_undoable('Editor contents') + external = b'External saved at commit' + injected = False + def change(): + nonlocal injected + if not injected: + injected = True; path.write_bytes(external) + if boundary == 'store': + save = DocumentStore.save + def race(target, source, **kwargs): + change(); return save(target, source, **kwargs) + monkeypatch.setattr(DocumentStore, 'save', staticmethod(race)) + elif boundary == 'flush': + fsync = files.os.fsync + def race(descriptor): + fsync(descriptor); change() + monkeypatch.setattr(files.os, 'fsync', race) + else: + replace = files._replace_with_backup + def race(temporary, target, backup): + if target == path: change() + replace(temporary, target, backup) + monkeypatch.setattr(files, '_replace_with_backup', race) + assert not window._save_editor_tab(editor, path, editor.source_text(), editor.file_signature) + assert injected and path.read_bytes() == external + assert editor.has_unsaved_changes() and editor.source_text() == 'Editor contents' + assert editor.session.saved_source == 'Original' + assert path not in window.internal_save_paths + if boundary == 'replace': + assert external in [p.read_bytes() for p in tmp_path.glob('.*.conflict-*.bak')] + finally: + monkeypatch.setattr(QMessageBox, 'question', lambda *args: QMessageBox.StandardButton.Discard) + window.close() + + +def test_new_editor_save_cannot_overwrite_concurrent_creation(tmp_path, monkeypatch): + path = tmp_path/'new.md' + rename = files.os.rename + def race(source, target): + if Path(target) == path: path.write_bytes(b'External creation') + rename(source, target) + monkeypatch.setattr(files.os, 'rename', race) + with pytest.raises(FileExistsError): files.VersionStore(tmp_path/'history').save(path, 'Editor') + assert path.read_bytes() == b'External creation' + + +def test_save_as_checks_destination_snapshot_before_image_relocation(qt_application, tmp_path, monkeypatch): + settings = QSettings(str(tmp_path/'settings.ini'), QSettings.Format.IniFormat) + monkeypatch.setattr(main_window, 'QSettings', lambda *_: settings) + monkeypatch.setattr(QMessageBox, 'warning', lambda *args: QMessageBox.StandardButton.Cancel) + source = tmp_path/'original.md'; source.write_text('Original') + target = tmp_path/'other'/'new.md'; target.parent.mkdir() + def relocate(text, original, destination): + destination.write_text('External creation'); return text + monkeypatch.setattr(DocumentStore, 'prepare_save', staticmethod(relocate)) + window = main_window.MainWindow(tmp_path) + try: + window.open_document(source); window.edit_current_markdown() + editor = window.tabs.currentWidget() + assert not window._save_editor_tab(editor, target, 'Editor', editor.file_signature) + assert target.read_text() == 'External creation' and editor.session.path == source + finally: window.close() diff --git a/tests/test_editor_improvements.py b/tests/test_editor_improvements.py index b71cffa..33e4ccc 100644 --- a/tests/test_editor_improvements.py +++ b/tests/test_editor_improvements.py @@ -76,12 +76,9 @@ def test_failed_atomic_save_keeps_original_and_history(tmp_path, monkeypatch): from mdhelper import file_versions path = tmp_path / "note.md"; path.write_bytes(b"original\r\n") store = VersionStore(tmp_path / "history") - replace = file_versions.os.replace - def failure(source, destination): - if Path(destination) == path: - raise OSError("simulated sharing violation") - replace(source, destination) - monkeypatch.setattr(file_versions.os, "replace", failure) + def failure(source, destination, backup): + raise OSError("simulated sharing violation") + monkeypatch.setattr(file_versions, "_replace_with_backup", failure) with pytest.raises(OSError): store.save(path, "changed") assert path.read_bytes() == b"original\r\n" diff --git a/tests/test_reliability.py b/tests/test_reliability.py index ee0a399..aa58881 100644 --- a/tests/test_reliability.py +++ b/tests/test_reliability.py @@ -59,7 +59,7 @@ def test_failed_close_save_keeps_window_and_recoverable_draft(editing, monkeypat editor.replace_source_undoable("not saved") monkeypatch.setattr(QMessageBox, "question", lambda *args: QMessageBox.StandardButton.Save) from mdhelper.file_versions import VersionStore - def fail(*args): + def fail(*args, **kwargs): raise OSError("simulated disk failure") monkeypatch.setattr(VersionStore, "save", fail) assert not window.close() diff --git a/tests/test_workspace_revision_058.py b/tests/test_workspace_revision_058.py new file mode 100644 index 0000000..161dc56 --- /dev/null +++ b/tests/test_workspace_revision_058.py @@ -0,0 +1,53 @@ +"""A failed lazy tab must not expose another document to editing/export actions.""" +import pytest +from PySide6.QtCore import QSettings +from PySide6.QtWidgets import QMessageBox +from mdhelper import main_window +from mdhelper.workspace_state import WorkspaceStore, TabState +from mdhelper.tab_controller import document_path +from test_workspace_state import wait_until + + +@pytest.mark.parametrize('failure', ['deleted', 'invalid_utf8', 'unreadable']) +def test_failed_lazy_tab_clears_current_document_and_can_retry(qt_application, tmp_path, monkeypatch, failure): + settings = QSettings(str(tmp_path/'settings.ini'), QSettings.Format.IniFormat) + monkeypatch.setattr(main_window, 'QSettings', lambda *_: settings) + monkeypatch.setattr(QMessageBox, 'warning', lambda *args: QMessageBox.StandardButton.Cancel) + monkeypatch.setattr(QMessageBox, 'critical', lambda *args: QMessageBox.StandardButton.Ok) + monkeypatch.setattr(QMessageBox, 'information', lambda *args: QMessageBox.StandardButton.Ok) + first, second = tmp_path/'first.md', tmp_path/'second.md' + first.write_text('# First'); second.write_text('# Second') + WorkspaceStore(settings).save(tmp_path, [TabState(str(first)), TabState(str(second))], 0) + window = main_window.MainWindow(tmp_path, defer_startup=True) + try: + window.prepare_reader_before_show(); window._restore_workspace() + host = window.tabs.widget(1) + render = window._render_document_file + if failure == 'deleted': second.unlink() + elif failure == 'invalid_utf8': second.write_bytes(b'\xff') + else: + def fail(path): + if path == second: raise PermissionError('Sharing violation') + return render(path) + monkeypatch.setattr(window, '_render_document_file', fail) + window.tabs.setCurrentIndex(1) + assert window.current_file is None and window._export_snapshot() is None + assert not window.edit_current_action.isEnabled() and window.toc_tree.topLevelItemCount() == 0 + assert host.workspace_state.path == str(second) + assert host.stack.currentWidget() is host.welcome_view + assert window.windowTitle() == 'second.md - MDHelper' + window.edit_current_markdown() + assert window.tabs.currentWidget() is host and window.tabs.count() == 2 + window.tabs.setCurrentIndex(0) + assert window.current_file == first + second.write_text('# Second\n\nRecovered text', encoding='utf8') + monkeypatch.setattr(window, '_render_document_file', render) + window.tabs.setCurrentIndex(1) + wait_until(qt_application, lambda: host.stack.currentWidget() is host.reader_view) + text=[]; host.reader_view.page().toPlainText(text.append) + wait_until(qt_application, lambda: bool(text)) + assert 'Recovered text' in text[0] + assert window.current_file == second and window.edit_current_action.isEnabled() + window.edit_current_markdown() + assert document_path(window.tabs.currentWidget()) == second + finally: window.close()