From 00eadf052746213a93ce1ac0051642a9487d63aa Mon Sep 17 00:00:00 2001 From: shen Date: Thu, 29 Oct 2026 21:22:04 +0800 Subject: [PATCH] feat: safely rename documents and update project references --- docs/architecture.md | 2 + mdhelper/history.py | 4 + mdhelper/main_window.py | 66 ++++++++++++++++- mdhelper/rename_references.py | 127 ++++++++++++++++++++++++++++++++ tests/test_rename_references.py | 64 ++++++++++++++++ 5 files changed, 260 insertions(+), 3 deletions(-) create mode 100644 mdhelper/rename_references.py create mode 100644 tests/test_rename_references.py diff --git a/docs/architecture.md b/docs/architecture.md index b86e58f..0a4e9e6 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -54,3 +54,5 @@ MHTML 的浏览器加载与归档转换分开。`mhtml_archive.py` 分别处理 `doc_check.py` 使用统一资源分析器检查全项目本地引用和实际渲染锚点;调用者可传入编辑器快照、取消信号和进度回调。`document_check_dialog.py` 只在用户打开时启动后台扫描,通过主窗口的源码定位入口打开结果,不参与启动流程。 +`rename_references.py` 分离重命名计划、差异确认和文件事务。资源编辑复用源区间分析器,保护代码块和引用标题;提交前验证原文件,备份到本地应用数据目录,失败后逆序回滚。主窗口仅同步标签、草稿和导航记录。 + diff --git a/mdhelper/history.py b/mdhelper/history.py index a175ca5..cf037fd 100644 --- a/mdhelper/history.py +++ b/mdhelper/history.py @@ -27,6 +27,10 @@ class NavigationHistory: if 0 <= self._index < len(self._items): self._items[self._index] = item + def rename_path(self, old: Path, new: Path) -> None: + self._items = [HistoryItem(new if item.path == old else item.path, item.fragment, item.scroll_y) + for item in self._items] + @property def current(self) -> HistoryItem | None: if 0 <= self._index < len(self._items): diff --git a/mdhelper/main_window.py b/mdhelper/main_window.py index d572cd9..6747e7d 100644 --- a/mdhelper/main_window.py +++ b/mdhelper/main_window.py @@ -1822,15 +1822,14 @@ class MainWindow(QMainWindow): try: if target_path != source_path: - if not self._close_tab_indexes(self._tab_indexes_for_paths({source_path}), show_welcome=True): + if not self._rename_with_references(source_path, target_path): self._new_file_rename_item = None self._new_file_rename_path = None self._tree_rename_is_new = False self._refresh_document_entries(force=True) self.status_label.setText("已取消重命名") return - source_path.rename(target_path) - except OSError as exc: + except (OSError, ValueError, UnicodeError) as exc: LOGGER.exception("Failed to rename new Markdown file: %s -> %s", source_path, target_path) QMessageBox.warning(self, "重命名失败", f"无法修改文件名:\n{target_path}\n\n{exc}") self._retry_new_file_rename(item, source_path.name) @@ -1845,6 +1844,67 @@ class MainWindow(QMainWindow): action_label = "已新建" if is_new_file else "已重命名" self.status_label.setText(f"{action_label}:{self._display_path(target_path)}") + def _rename_with_references(self, source: Path, target: Path) -> bool: + from .rename_references import plan_rename, confirm_rename, execute_rename + source, target = source.resolve(), target.resolve() + plan = plan_rename(self.project_root, source, target, self._editor_sources()) + for index in range(self.tabs.count()): + widget = self.tabs.widget(index) + if isinstance(widget, RichMarkdownEditorDialog) and widget.session.path in plan.buffers: + if widget.session.signature != self._file_signature(widget.session.path): + raise OSError(f"{widget.session.path.name} 已被外部修改,请先保存并处理冲突。") + if not confirm_rename(self, plan): + return False + if any(self._editor_sources().get(path) != text for path, text in plan.buffers.items()): + raise OSError("编辑内容在预览后变化,请重新重命名。") + affected = set(plan.originals) | {target} + self.internal_save_paths.update(affected) + try: + backup = execute_rename(plan) + except Exception: + self.internal_save_paths.difference_update(affected) + raise + for index in range(self.tabs.count()): + widget = self.tabs.widget(index) + old_path = document_path(widget) + if old_path == source: + widget.setProperty("current_file", str(target)) + self.tabs.setTabText(index, target.name) + state = getattr(widget, "workspace_state", None) + if state is not None: + state.path = str(target) + if isinstance(widget, RichMarkdownEditorDialog) and old_path in plan.originals: + path = target if old_path == source else old_path + text = plan.replacements.get(old_path, plan.originals[old_path]).decode("utf-8-sig") + widget.replace_source_undoable(text) + widget.mark_saved(path, text, self._file_signature(path)) + self._clear_editor_draft(old_path) + reader = self._reader_from_tab(widget) + if reader is not None: + if old_path == source: + reader.setProperty("current_file", str(target)) + self._tab_history(reader).rename_path(source, target) + if old_path in plan.originals: + self._refresh_tab_appearance(widget) + self.recent_files = [target if path == source else path for path in self.recent_files] + for bookmark in self.bookmarks: + if bookmark.get("path") == str(source): + bookmark["path"] = str(target) + if str(source) in self.scroll_positions: + self.scroll_positions[str(target)] = self.scroll_positions.pop(str(source)) + if str(source) in self.editor_drafts: + self.editor_drafts[str(target)] = self.editor_drafts.pop(str(source)) + if self.current_file == source: + self.current_file = target + self.workspaces.save(self.project_root, *self._workspace_snapshot()) + self._update_recent_menu() + self._update_bookmarks_menu() + self._save_preferences() + self._update_watched_paths() + QTimer.singleShot(1000, self, lambda: self.internal_save_paths.difference_update(affected)) + LOGGER.info("Rename backup: %s", backup) + return True + def _on_tree_name_editor_closed(self, editor: QWidget, hint: object) -> None: if self._new_file_rename_item is not None: QTimer.singleShot(0, self._finish_unchanged_new_file_rename) diff --git a/mdhelper/rename_references.py b/mdhelper/rename_references.py new file mode 100644 index 0000000..be5c12c --- /dev/null +++ b/mdhelper/rename_references.py @@ -0,0 +1,127 @@ +"""Plan reference edits before mutating files; retain a recovery copy for each transaction.""" +from __future__ import annotations + +import difflib +import json +import os +import time +import uuid +from dataclasses import dataclass +from pathlib import Path +from urllib.parse import quote, urlsplit, urlunsplit + +from .document_resources import analyze_document, apply_source_edits, resolve_local_reference +from .document_tree import discover_documents +from .file_versions import atomic_write + + +@dataclass +class RenamePlan: + source: Path + target: Path + originals: dict[Path, bytes] + replacements: dict[Path, bytes] + buffers: dict[Path, str] + changes: list[str] + + +def plan_rename(root: Path, source: Path, target: Path, buffers=None) -> RenamePlan: + root, source, target = root.resolve(), source.resolve(), target.resolve() + if not source.is_relative_to(root) or not target.is_relative_to(root): + raise ValueError("重命名目标必须位于当前项目内。") + if target.exists(): + raise FileExistsError(target) + buffers = buffers or {} + originals = {source: source.read_bytes()} + replacements, snapshots, changes = {}, {}, [] + for entry in discover_documents(root, ("markdown",)): + path = entry.path + raw = path.read_bytes() + text = buffers.get(path, raw.decode("utf-8-sig")) + new_path = target if path == source else path + edits = [] + for reference in analyze_document(text).references: + resolved = resolve_local_reference(path, reference.url) + if resolved is None: + continue + moved = target if resolved == source else resolved + if moved == resolved and new_path.parent == path.parent: + continue + url = urlsplit(reference.url) + if url.scheme == "file": + new_url = urlsplit(moved.as_uri())._replace(query=url.query, fragment=url.fragment) + else: + relative = quote(Path(os.path.relpath(moved, new_path.parent)).as_posix(), safe="/.-_~") + new_url = url._replace(path=relative) + edits.append(reference.edit_url(urlunsplit(new_url))) + updated = apply_source_edits(text, edits) + if updated != text or (path == source and path in buffers): + originals[path] = raw + # Keep BOM and line endings when no editor snapshot replaces the source. + replacements[path] = (b"\xef\xbb\xbf" if raw.startswith(b"\xef\xbb\xbf") and path not in buffers else b"") + updated.encode("utf-8") + if path in buffers: + snapshots[path] = text + changes.append("".join(difflib.unified_diff(raw.decode("utf-8-sig").splitlines(True), updated.splitlines(True), + fromfile=str(path.relative_to(root)), tofile=str(new_path.relative_to(root))))) + return RenamePlan(source, target, originals, replacements, snapshots, changes) + + +def execute_rename(plan: RenamePlan, backup_root: Path | None = None) -> Path: + if plan.target.exists(): + raise FileExistsError(plan.target) + for path, original in plan.originals.items(): + if path.read_bytes() != original: + raise OSError(f"文件在预览后已变化,请重新重命名:{path.name}") + base = backup_root or Path(os.environ.get("LOCALAPPDATA", str(Path.home()))) / "MDHelper" / "rename-backups" + backup = base / (time.strftime("%Y%m%d-%H%M%S-") + uuid.uuid4().hex[:8]) + manifest = {"source": str(plan.source), "target": str(plan.target), "files": {}} + for index, (path, original) in enumerate(plan.originals.items()): + name = f"{index}.bak" + atomic_write(backup / name, original) + manifest["files"][name] = str(path) + atomic_write(backup / "manifest.json", json.dumps(manifest, ensure_ascii=False, indent=2).encode("utf-8")) + written, renamed = [], False + try: + plan.source.rename(plan.target) + renamed = True + for path, data in plan.replacements.items(): + destination = plan.target if path == plan.source else path + atomic_write(destination, data) + written.append(path) + except OSError as exc: + failures = [] + for path in reversed(written): + try: + atomic_write(plan.target if path == plan.source else path, plan.originals[path]) + except OSError as rollback_error: + failures.append(str(rollback_error)) + if renamed: + try: + plan.target.rename(plan.source) + except OSError as rollback_error: + failures.append(str(rollback_error)) + if failures: + raise OSError(f"重命名失败,自动恢复未完全成功。备份位于 {backup}:{';'.join(failures)}") from exc + raise OSError(f"重命名失败,文件已恢复。备份位于 {backup}:{exc}") from exc + return backup + + +def confirm_rename(parent, plan: RenamePlan) -> bool: + if not plan.replacements: + return True + from PySide6.QtWidgets import QDialog, QDialogButtonBox, QLabel, QPlainTextEdit, QVBoxLayout + dialog = QDialog(parent) + dialog.setWindowTitle("重命名并更新引用") + dialog.resize(950, 620) + layout = QVBoxLayout(dialog) + layout.addWidget(QLabel(f"{plan.source.name} → {plan.target.name}\n将更新 {len(plan.replacements)} 个文件;包含相关编辑器的未保存内容。操作前自动备份,失败时恢复。")) + preview = QPlainTextEdit() + preview.setReadOnly(True) + preview.setPlainText("\n".join(plan.changes)) + layout.addWidget(preview) + buttons = QDialogButtonBox(QDialogButtonBox.StandardButton.Cancel) + buttons.addButton("重命名并保存上述更改", QDialogButtonBox.ButtonRole.AcceptRole) + buttons.accepted.connect(dialog.accept) + buttons.rejected.connect(dialog.reject) + layout.addWidget(buttons) + return dialog.exec() == QDialog.DialogCode.Accepted diff --git a/tests/test_rename_references.py b/tests/test_rename_references.py new file mode 100644 index 0000000..1967e2c --- /dev/null +++ b/tests/test_rename_references.py @@ -0,0 +1,64 @@ +from pathlib import Path +import pytest +from PySide6.QtCore import QSettings +from mdhelper import main_window, rename_references as renaming + + +def fixture_documents(tmp_path): + old, new, ref = tmp_path / 'old.md', tmp_path / 'new name.md', tmp_path / 'ref.md' + old.write_text('# Title\n[self](old.md#title)', encoding='utf-8') + ref.write_text('[go][id]\n\n[id]: old.md#title "tip"\n\n`[literal](old.md)`\n\nHTML', encoding='utf-8') + return old, new, ref + + +def test_reference_rewrite_preserves_code_titles_fragments_and_backups(tmp_path): + old, new, ref = fixture_documents(tmp_path) + originals = {p: p.read_bytes() for p in (old, ref)} + plan = renaming.plan_rename(tmp_path, old, new) + backup = renaming.execute_rename(plan, tmp_path / 'backups') + assert not old.exists() and '[self](new%20name.md#title)' in new.read_text() + content = ref.read_text() + assert '[go](new%20name.md#title "tip")' in content + assert '`[literal](old.md)`' in content and 'new%20name.md?q=1#title' in content + assert {p.read_bytes() for p in backup.glob('*.bak')} == set(originals.values()) + + +def test_changed_disk_aborts_and_partial_write_rolls_back(tmp_path, monkeypatch): + old, new, ref = fixture_documents(tmp_path) + plan = renaming.plan_rename(tmp_path, old, new) + ref.write_text('external') + with pytest.raises(OSError, match='已变化'): renaming.execute_rename(plan, tmp_path / 'backups') + assert old.exists() and not new.exists() and ref.read_text() == 'external' + old, new, ref = fixture_documents(tmp_path) + plan = renaming.plan_rename(tmp_path, old, new) + write = renaming.atomic_write + def fail(path, data): + if path == ref: raise OSError('simulated permission error') + write(path, data) + monkeypatch.setattr(renaming, 'atomic_write', fail) + with pytest.raises(OSError, match='文件已恢复'): renaming.execute_rename(plan, tmp_path / 'backups') + assert not new.exists() + for path, data in plan.originals.items(): assert path.read_bytes() == data + + +def test_gui_rename_keeps_buffers_tabs_and_navigation(qt_application, tmp_path, monkeypatch): + old, new, ref = fixture_documents(tmp_path) + settings = QSettings(str(tmp_path / 'settings.ini'), QSettings.Format.IniFormat) + monkeypatch.setattr(main_window, 'QSettings', lambda *_: settings) + monkeypatch.setattr(renaming, 'confirm_rename', lambda *_: True) + monkeypatch.setenv('LOCALAPPDATA', str(tmp_path / 'user-data')) + window = main_window.MainWindow(tmp_path) + try: + window.open_document(old); window.edit_current_markdown() + editor = window.tabs.currentWidget() + editor.replace_source_undoable(editor.source_text() + '\nUnsaved content') + window.bookmarks = [{'path': str(old), 'fragment': 'title', 'label': 'Title'}] + assert window._rename_with_references(old, new) + assert editor.session.path == new and not editor.has_unsaved_changes() + assert 'Unsaved content' in new.read_text() and 'new%20name.md' in ref.read_text() + assert window.current_file == new and window.bookmarks[0]['path'] == str(new) + assert old not in window.recent_files and new in window.recent_files + states, _ = window.workspaces.load(tmp_path) + assert states[0].path == str(new) + finally: + window.close()