feat: compare and merge external save conflicts safely
This commit is contained in:
@@ -56,3 +56,5 @@ MHTML 的浏览器加载与归档转换分开。`mhtml_archive.py` 分别处理
|
||||
|
||||
`rename_references.py` 分离重命名计划、差异确认和文件事务。资源编辑复用源区间分析器,保护代码块和引用标题;提交前验证原文件,备份到本地应用数据目录,失败后逆序回滚。主窗口仅同步标签、草稿和导航记录。
|
||||
|
||||
`save_conflict.py` 将逐段合并算法与保存冲突对话框封装在一起。编辑器保存流程传入原始、编辑和磁盘版本;确认后再次核对磁盘字节,再交给现有带历史版本的原子保存流程。取消或二次冲突均保留编辑区。
|
||||
|
||||
|
||||
+29
-1
@@ -2107,6 +2107,23 @@ class MainWindow(QMainWindow):
|
||||
self.status_label.setText("编辑内容未变化")
|
||||
return True
|
||||
|
||||
reviewed_disk = None
|
||||
if target_path == original_path and expected_signature != self._file_signature(target_path):
|
||||
from .save_conflict import resolve_save_conflict
|
||||
try:
|
||||
disk_bytes = target_path.read_bytes() if target_path.exists() else None
|
||||
disk_text = disk_bytes.decode("utf-8-sig") if disk_bytes is not None else ""
|
||||
except (OSError, UnicodeError) as exc:
|
||||
QMessageBox.warning(self, "无法比较文件", str(exc))
|
||||
return False
|
||||
merged = resolve_save_conflict(self, target_path, source, disk_text, editor.session.saved_source,
|
||||
deleted=disk_bytes is None)
|
||||
if merged is None:
|
||||
self.status_label.setText("已取消保存,编辑内容保留")
|
||||
return False
|
||||
source = merged
|
||||
reviewed_disk = (disk_bytes,)
|
||||
|
||||
if target_path.parent != original_path.parent:
|
||||
try:
|
||||
source = self.documents.prepare_save(source, original_path, target_path)
|
||||
@@ -2120,6 +2137,7 @@ class MainWindow(QMainWindow):
|
||||
expected_signature=expected_signature if target_path == original_path else None,
|
||||
original_path=original_path,
|
||||
reload_current=False,
|
||||
reviewed_disk=reviewed_disk,
|
||||
)
|
||||
if not ok:
|
||||
return False
|
||||
@@ -2178,13 +2196,23 @@ class MainWindow(QMainWindow):
|
||||
expected_signature: tuple[int, int] | None = None,
|
||||
original_path: Path | None = None,
|
||||
reload_current: bool = True,
|
||||
reviewed_disk: tuple[bytes | None] | None = None,
|
||||
) -> bool:
|
||||
path = path.resolve()
|
||||
if path.suffix.lower() not in {".md", ".markdown"}:
|
||||
QMessageBox.warning(self, "保存失败", "只能保存 Markdown 文档。")
|
||||
return False
|
||||
|
||||
if expected_signature is not None and path.exists() and self._file_signature(path) != expected_signature:
|
||||
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
|
||||
elif expected_signature is not None and path.exists() and self._file_signature(path) != expected_signature:
|
||||
choice = QMessageBox.warning(
|
||||
self,
|
||||
"文件已被外部修改",
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
"""Explicit, line-based conflict choices; the editor's version is always the default."""
|
||||
from __future__ import annotations
|
||||
|
||||
from difflib import SequenceMatcher
|
||||
|
||||
|
||||
class ConflictComparison:
|
||||
def __init__(self, current: str, disk: str):
|
||||
self.current = current.splitlines(keepends=True)
|
||||
self.disk = disk.splitlines(keepends=True)
|
||||
self.parts = SequenceMatcher(None, self.current, self.disk, autojunk=False).get_opcodes()
|
||||
self.changes = [part for part in self.parts if part[0] != "equal"]
|
||||
|
||||
def merge(self, disk_choices=()) -> str:
|
||||
chosen, result, change = set(disk_choices), [], 0
|
||||
for tag, a, b, c, d in self.parts:
|
||||
if tag == "equal":
|
||||
result.extend(self.current[a:b])
|
||||
else:
|
||||
result.extend(self.disk[c:d] if change in chosen else self.current[a:b])
|
||||
change += 1
|
||||
return "".join(result)
|
||||
|
||||
|
||||
def resolve_save_conflict(parent, path, current: str, disk: str, baseline: str, deleted=False) -> str | None:
|
||||
from PySide6.QtCore import Qt
|
||||
from PySide6.QtGui import QColor, QTextCursor
|
||||
from PySide6.QtWidgets import (QDialog, QDialogButtonBox, QHBoxLayout, QLabel, QListWidget,
|
||||
QListWidgetItem, QPlainTextEdit, QPushButton, QSplitter, QTextEdit, QVBoxLayout)
|
||||
comparison = ConflictComparison(current, disk)
|
||||
dialog = QDialog(parent)
|
||||
dialog.setWindowTitle(f"保存冲突 — {path.name}")
|
||||
dialog.resize(1150, 800)
|
||||
layout = QVBoxLayout(dialog)
|
||||
layout.addWidget(QLabel(("磁盘文件已删除。" if deleted else "磁盘文件已被外部修改。") +
|
||||
"勾选差异段落可采用磁盘内容;未勾选保留编辑内容。下方合并结果可继续编辑。"))
|
||||
panels = QSplitter(Qt.Orientation.Horizontal)
|
||||
editors = []
|
||||
for title, source in (("当前编辑内容", current), ("磁盘内容", disk)):
|
||||
from PySide6.QtWidgets import QWidget
|
||||
container = QWidget(); column = QVBoxLayout(container)
|
||||
column.addWidget(QLabel(title))
|
||||
editor = QPlainTextEdit(source); editor.setReadOnly(True)
|
||||
column.addWidget(editor); editors.append(editor); panels.addWidget(container)
|
||||
layout.addWidget(panels, 3)
|
||||
changes = QListWidget(); changes.setMaximumHeight(140)
|
||||
for index, (_, a, b, c, d) in enumerate(comparison.changes):
|
||||
item = QListWidgetItem(f"差异 {index + 1}:编辑区第 {a + 1}–{max(a + 1, b)} 行 ↔ 磁盘第 {c + 1}–{max(c + 1, d)} 行(勾选采用磁盘段落)")
|
||||
item.setFlags(item.flags() | Qt.ItemFlag.ItemIsUserCheckable)
|
||||
item.setCheckState(Qt.CheckState.Unchecked)
|
||||
changes.addItem(item)
|
||||
layout.addWidget(changes)
|
||||
for side, editor in enumerate(editors):
|
||||
selections = []
|
||||
for part in comparison.changes:
|
||||
start, end = part[1:3] if side == 0 else part[3:5]
|
||||
for line in range(start, max(start + 1, end)):
|
||||
block = editor.document().findBlockByNumber(line)
|
||||
if not block.isValid(): continue
|
||||
selection = QTextEdit.ExtraSelection()
|
||||
selection.cursor = QTextCursor(block)
|
||||
selection.cursor.select(QTextCursor.SelectionType.LineUnderCursor)
|
||||
selection.format.setBackground(QColor("#fff0bb" if side == 0 else "#d7f4dd"))
|
||||
selections.append(selection)
|
||||
editor.setExtraSelections(selections)
|
||||
layout.addWidget(QLabel("合并结果(更改勾选会重新生成此处内容)"))
|
||||
result = QPlainTextEdit(current); layout.addWidget(result, 2)
|
||||
def update_result():
|
||||
result.setPlainText(comparison.merge(i for i in range(changes.count()) if changes.item(i).checkState() == Qt.CheckState.Checked))
|
||||
changes.itemChanged.connect(update_result)
|
||||
def locate(row):
|
||||
if row < 0: return
|
||||
part = comparison.changes[row]
|
||||
for editor, line in zip(editors, (part[1], part[3])):
|
||||
block = editor.document().findBlockByNumber(line)
|
||||
if block.isValid():
|
||||
editor.setTextCursor(QTextCursor(block)); editor.centerCursor()
|
||||
changes.currentRowChanged.connect(locate)
|
||||
buttons = QDialogButtonBox(QDialogButtonBox.StandardButton.Cancel)
|
||||
buttons.addButton("保存合并结果", QDialogButtonBox.ButtonRole.AcceptRole)
|
||||
overwrite = buttons.addButton("用全部编辑内容覆盖", QDialogButtonBox.ButtonRole.ActionRole)
|
||||
original = buttons.addButton("查看上次保存内容", QDialogButtonBox.ButtonRole.ActionRole)
|
||||
def show_baseline():
|
||||
view = QDialog(dialog); view.setWindowTitle("上次保存内容(只读)"); view.resize(750, 500)
|
||||
box = QVBoxLayout(view); text = QPlainTextEdit(baseline); text.setReadOnly(True); box.addWidget(text)
|
||||
view.exec()
|
||||
original.clicked.connect(show_baseline)
|
||||
overwrite.clicked.connect(lambda: (result.setPlainText(current), dialog.accept()))
|
||||
buttons.accepted.connect(dialog.accept); buttons.rejected.connect(dialog.reject)
|
||||
layout.addWidget(buttons)
|
||||
return result.toPlainText() if dialog.exec() == QDialog.DialogCode.Accepted else None
|
||||
@@ -137,7 +137,9 @@ def test_save_as_changes_draft_ownership_only_after_success(editing, monkeypatch
|
||||
assert original.read_text() == "# Original"
|
||||
|
||||
|
||||
def test_save_recreates_externally_deleted_file(editing):
|
||||
def test_save_recreates_externally_deleted_file(editing, monkeypatch):
|
||||
from mdhelper import save_conflict
|
||||
monkeypatch.setattr(save_conflict, "resolve_save_conflict", lambda parent, path, source, *args, **kwargs: source)
|
||||
window, editor, path = editing
|
||||
editor.replace_source_undoable("recovered")
|
||||
path.unlink()
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
import pytest
|
||||
from PySide6.QtCore import QSettings, QTimer, Qt
|
||||
from PySide6.QtWidgets import QApplication, QDialog, QListWidget
|
||||
from mdhelper import main_window, save_conflict
|
||||
|
||||
|
||||
def test_chunk_choices_preserve_insertions_deletions_and_final_newline():
|
||||
comparison = save_conflict.ConflictComparison('A\nlocal\nB\nremove\nC', 'A\nremote\nB\nC\nadded\n')
|
||||
assert comparison.merge() == 'A\nlocal\nB\nremove\nC'
|
||||
assert comparison.merge(range(len(comparison.changes))) == 'A\nremote\nB\nC\nadded\n'
|
||||
assert comparison.merge([0]).startswith('A\nremote\nB\nremove')
|
||||
assert save_conflict.ConflictComparison('', 'new').merge([0]) == 'new'
|
||||
|
||||
|
||||
def test_comparison_dialog_uses_selected_disk_chunk(qt_application, tmp_path):
|
||||
def choose():
|
||||
dialog = QApplication.activeModalWidget()
|
||||
dialog.findChild(QListWidget).item(0).setCheckState(Qt.CheckState.Checked)
|
||||
dialog.accept()
|
||||
QTimer.singleShot(30, choose)
|
||||
assert save_conflict.resolve_save_conflict(None, tmp_path / 'note.md', 'a\nlocal\n', 'a\nremote\n', 'a\nbase\n') == 'a\nremote\n'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('decision', ['cancel', 'merge', 'race', 'deleted'])
|
||||
def test_editor_conflict_protects_both_versions(qt_application, tmp_path, monkeypatch, decision):
|
||||
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(main_window.QMessageBox, 'warning', lambda *_: None)
|
||||
path = tmp_path / 'note.md'; path.write_text('base')
|
||||
window = main_window.MainWindow(tmp_path)
|
||||
try:
|
||||
window.open_document(path); window.edit_current_markdown()
|
||||
editor = window.tabs.currentWidget(); editor.replace_source_undoable('local')
|
||||
if decision == 'deleted': path.unlink()
|
||||
else: path.write_text('external modification')
|
||||
def choose(*args, **kwargs):
|
||||
if decision == 'cancel': return None
|
||||
if decision == 'race': path.write_text('newer external change')
|
||||
return 'merged result'
|
||||
monkeypatch.setattr(save_conflict, 'resolve_save_conflict', choose)
|
||||
saved = window._save_editor_tab(editor, path, editor.source_text(), editor.session.signature)
|
||||
assert saved == (decision in {'merge', 'deleted'})
|
||||
if saved:
|
||||
assert path.read_text() == editor.source_text() == editor.session.saved_source == 'merged result'
|
||||
assert not editor.has_unsaved_changes()
|
||||
else:
|
||||
assert editor.source_text() == 'local'
|
||||
assert path.read_text() == ('newer external change' if decision == 'race' else 'external modification')
|
||||
editor.mark_saved(path, editor.source_text(), window._file_signature(path))
|
||||
finally:
|
||||
window.close()
|
||||
Reference in New Issue
Block a user