"""Plan reference edits before mutating files; retain a recovery copy for each transaction.""" from __future__ import annotations import difflib import hashlib 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) def check_originals(): for path, original in plan.originals.items(): if path.read_bytes() != original: raise OSError(f"文件在预览后已变化,请重新重命名:{path.name}") check_originals() 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: check_originals() plan.source.rename(plan.target) renamed = True for path, data in plan.replacements.items(): destination = plan.target if path == plan.source else path if destination.read_bytes() != plan.originals[path]: raise OSError(f"文件在重命名期间已变化,保留当前内容:{destination.name}") atomic_write(destination, data, expected=hashlib.sha256(plan.originals[path]).hexdigest()) written.append(path) except OSError as exc: failures = [] for path in reversed(written): try: destination = plan.target if path == plan.source else path if destination.read_bytes() != plan.replacements[path]: raise OSError(f"文件已被外部修改,保留当前内容:{destination.name}") atomic_write(destination, plan.originals[path], expected=hashlib.sha256(plan.replacements[path]).hexdigest()) except OSError as rollback_error: failures.append(str(rollback_error)) if renamed: try: if plan.source.exists(): raise FileExistsError(plan.source) 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