perf: replace automatic backups with manual backup reminders

This commit is contained in:
阿白叔 committed 2026-11-03 16:44:30 +08:00
1 parent 7527800128
commit c85696080d
26 files changed
+385 -102

No files matched your search

+11 -15
View File
@@ -128,7 +128,7 @@ def recover_from_backup(request, source, *, progress=None, verifier=None, idle_c
installed = False
record = {'operation': 'same_cbb_complete_project_restore', 'source': str(source),
'library': str(library), 'block': request.block_name, 'installed': False,
'validation_library': str(validation_dir/library.name)}
'validation_library': str(validation_dir/library.name), 'backup_policy': 'manual'}
def emit(stage, message, **details):
if progress:
progress({'stage': stage, 'block': request.block_name, 'message': message, **details})
@@ -165,22 +165,17 @@ def recover_from_backup(request, source, *, progress=None, verifier=None, idle_c
library_size = sum(info.st_size for info in _scan(library_root).values() if stat.S_ISREG(info.st_mode))
source_size = sum(info.st_size for info in _scan(source.parent).values() if stat.S_ISREG(info.st_mode))
same_drive = root.anchor.casefold() == validation_dir.anchor.casefold()
required = library_size * (2 if same_drive else 1) + source_size * 3
required = (library_size + source_size * 2) if same_drive else 0
if (shutil.disk_usage(root).free < required
or shutil.disk_usage(validation_base).free < library_size + source_size * 2):
raise ValueError('磁盘空间不足:需要容纳中心库回退副本和验证副本。')
or shutil.disk_usage(validation_base).free < library_size + source_size * 2
or shutil.disk_usage(library_root).free < source_size):
raise ValueError('磁盘空间不足:需要容纳隔离验证库和待安装工程。')
(root/'recovery-request.json').write_text(json.dumps(record, ensure_ascii=False, indent=2), encoding='utf-8')
emit('backup', '正在保留完整中心库副本…')
emit('prepare_source', '正在准备隔离验证库;应用不自动创建回退备份…')
library_scope = ManifestScope.library(request.block_name, library.name)
original_manifest = _copy_verified(library_root, root/'library-before', scope=library_scope,
progress=copy_progress('backup', '正在保留中心库副本:'))
(root/'library-before-manifest.json').write_text(json.dumps(original_manifest, indent=2), encoding='utf-8')
emit('prepare_source', '正在准备备份验证副本…')
source_manifest = _copy_verified(source.parent, root/'source-before',
progress=copy_progress('prepare_source', '正在保留备份工程副本:'))
(root/'source-before-manifest.json').write_text(json.dumps(source_manifest, indent=2), encoding='utf-8')
_copy_verified(root/'library-before', validation_dir, scope=library_scope,
original_manifest = _copy_verified(library_root, validation_dir, scope=library_scope,
progress=copy_progress('prepare_source', '正在准备验证库:'))
(root/'library-baseline-manifest.json').write_text(json.dumps(original_manifest, indent=2), encoding='utf-8')
staged_library = validation_dir/library.name
staged_work = staged_library.parent/'ReusableBlocksLP'/request.block_name/'Work'
# Both paths are newly created private copies; originals are retained.
@@ -188,8 +183,9 @@ def recover_from_backup(request, source, *, progress=None, verifier=None, idle_c
if not resolved_work.is_relative_to(validation_dir.resolve()):
raise ValueError('验证副本工程路径越界。')
shutil.rmtree(resolved_work)
_copy_verified(root/'source-before', staged_work,
source_manifest = _copy_verified(source.parent, staged_work,
progress=copy_progress('prepare_source', '正在准备备份验证工程:'))
(root/'source-manifest.json').write_text(json.dumps(source_manifest, indent=2), encoding='utf-8')
staged_project = staged_work/source.name
staged_pcb = staged_work/source_pcb.relative_to(source.parent)
_align_library(staged_project, staged_pcb, staged_library)
@@ -239,7 +235,7 @@ def recover_from_backup(request, source, *, progress=None, verifier=None, idle_c
if final.status == 'PASS' and (final.library_flag != 'GREEN' or not final.safe_to_continue):
final = replace(final, status='FAIL', stderr='目标工程恢复后的 Ready 状态未确认。')
if final.status != 'PASS':
final = replace(final, stderr=(final.stderr + '\n原工程和完整库副本已保留,请查看恢复记录。').strip())
final = replace(final, stderr=(final.stderr + '\n原 Work 已改名保留;应用未创建完整库备份,请查看恢复记录并使用手动备份。').strip())
return save(final)
except Exception as error:
return save(VerifyResult('FAIL' if installed else 'BLOCKED', stderr=str(error),
+1 -1
View File
@@ -197,7 +197,7 @@ def run_existing_address_maintenance(request, *, verify, progress=None):
with attempt.open('x', encoding='utf-8') as stream:
json.dump({'intent': 'explicit_maintenance', 'target': asdict(target),
'maintenance_context': context}, stream, default=str, ensure_ascii=False)
emit('native_repair_start', detail='先完整备份工程与地址记录,再由官方工具检查/修复')
emit('native_repair_start', detail='核对占用后由官方工具检查/修复;应用不自动备份')
# Repeat immediately before dispatch; worker repeats after complete
# backup and before launching its native process as well.
with maintenance_target_guard(request, context): pass
+11 -10
View File
@@ -7,7 +7,8 @@ import re
from uuid import uuid4
from .library_lock import LibraryLock, LibraryBusy
from .scoped_manifest import ManifestScope, build_manifest, copy_verified, hash_file, scan_tree
from .scoped_manifest import (ManifestScope, build_manifest, build_exclusive_library_manifest,
copy_verified, hash_file, scan_tree)
@dataclass(frozen=True)
@@ -179,14 +180,14 @@ def run_management(request, *, adapter=None, verifier=None, idle_check=None, pro
history.append({'stage': stage, 'time': datetime.now(timezone.utc).isoformat(), **details})
if report:
_write_json(report, {**asdict(request), 'stage': stage, 'status': 'RUNNING',
'safe_to_continue': False, 'history': history})
'safe_to_continue': False, 'history': history, 'backup_policy': 'manual'})
if progress:
progress({'stage': stage, 'block': request.name, 'operation': request.operation, **details})
def finish(status, detail='', safe=True):
result = ManagementResult(request.operation, request.library, request.name, request.partition,
request.source, request.auto_verify, 'complete', status, safe, detail, report)
if report:
_write_json(report, {**asdict(result), 'history': history})
_write_json(report, {**asdict(result), 'history': history, 'backup_policy': 'manual'})
return result
from .com_runtime import initialize_com, uninitialize_com
initialized = initialize_com()
@@ -202,7 +203,7 @@ def run_management(request, *, adapter=None, verifier=None, idle_check=None, pro
raise ValueError('中心库必须为现有 LMC 文件。')
evidence = Path(request.evidence_dir).resolve()
if evidence.is_relative_to(library_root) or library_root.is_relative_to(evidence):
raise ValueError('操作记录与备份必须位于目标中心库之外,且不能包含目标库。')
raise ValueError('操作记录与暂存目录必须位于目标中心库之外,且不能包含目标库。')
capability = adapter.capabilities().get(request.operation, Capability(False, '未验证的原生接口'))
if not capability.supported:
return finish('UNSUPPORTED', capability.reason)
@@ -258,9 +259,9 @@ def run_management(request, *, adapter=None, verifier=None, idle_check=None, pro
# Native/project owners must be idle before snapshot or mutation.
idle_check(library, target_project, target_pcb)
scope = ManifestScope.library(request.name, library.name)
checkpoint('backup')
original = copy_verified(library_root, root/'library-before', scope=scope, progress=progress)
_write_json(root/'library-before-manifest.json', original)
checkpoint('baseline')
original = build_exclusive_library_manifest(library_root, scope=scope, progress=progress)
_write_json(root/'library-baseline-manifest.json', original)
staged = request
identity = None
if source:
@@ -279,8 +280,8 @@ def run_management(request, *, adapter=None, verifier=None, idle_check=None, pro
if not owner_safe or proof.identity is None:
return finish('UPLOAD_FAILED', proof.detail, owner_safe)
identity = proof.identity
if build_manifest(library_root, scope=scope) != original:
raise OSError('备份后中心库内容变化,停止写入。')
if build_exclusive_library_manifest(library_root, scope=scope, progress=progress) != original:
raise OSError('内容基线记录后中心库发生变化,停止写入。')
if request.operation in ('remove', 'update'):
checkpoint('native_remove')
mutated = True; owner_safe = False
@@ -299,7 +300,7 @@ def run_management(request, *, adapter=None, verifier=None, idle_check=None, pro
removed = True
checkpoint('removed')
if request.operation == 'remove':
return finish('REMOVED', '已备份并由原生操作移除,重新读取目录确认不存在。')
return finish('REMOVED', '已由原生操作移除,重新读取目录确认不存在;应用未创建备份。')
checkpoint('native_add')
mutated = True; owner_safe = False
native = adapter.add(staged, root/'add')
@@ -1,4 +1,4 @@
"""Prepared Add authority bound to the engine checkpoint, snapshot and live lease."""
"""Prepared Add authority bound to the engine checkpoint, baseline and live lease."""
import json
import os
from pathlib import Path
@@ -6,7 +6,7 @@ import threading
from uuid import uuid4
from .management import _write_json, engineering_identity
from .scoped_manifest import build_manifest, ManifestScope
from .scoped_manifest import build_manifest
def _read(path):
@@ -62,18 +62,16 @@ def prepare_transaction(request, root, expected_identity, *, mentor_home, fixtur
if (checkpoint.get('status') != 'RUNNING' or checkpoint.get('stage') != 'prepare_identity'
or Path(checkpoint['library']).resolve() != library
or checkpoint['name'] != request.name or checkpoint['partition'] != request.partition
or not {'backup', 'stage_source'}.issubset(stages)):
raise ValueError('Native Add requires the engine backup/staging checkpoint.')
backup = _read(root/'library-before-manifest.json')
if build_manifest(root/'library-before', scope=ManifestScope.library(request.name, library.name)) != backup:
raise ValueError('Management backup has not been verified.')
or not {'baseline', 'stage_source'}.issubset(stages)):
raise ValueError('Native Add requires the engine baseline/staging checkpoint.')
library_baseline = _read(root/'library-baseline-manifest.json')
baseline = _read(root/'source-identity/identity.json')
if baseline.get('safe_to_continue') is not True or baseline.get('identity') != expected_identity:
raise ValueError('Native source identity evidence is missing or changed.')
record = {**current_lease(library), 'nonce': uuid4().hex, 'library': str(library),
'name': request.name, 'partition': request.partition, 'top_level_block': request.top_level_block,
'source_name': source.name, 'source_identity': engineering_identity(source),
'source_manifest': build_manifest(source.parent), 'backup_manifest': backup,
'source_manifest': build_manifest(source.parent), 'library_baseline': library_baseline,
'expected_identity': expected_identity, 'fixture': fixture}
_authorize(record, mentor_home)
_write_json(root/'native-add-prepared.json', record)
@@ -105,11 +103,10 @@ def validate_transaction(job, root, *, check_source=True):
_authorize(record, job['mentor_home'])
baseline = _read(root/'source-identity/identity.json')
if (baseline.get('safe_to_continue') is not True or baseline.get('identity') != record['expected_identity']
or build_manifest(root/'library-before', scope=ManifestScope.library(record['name'], library.name))
!= record['backup_manifest']
or _read(root/'library-baseline-manifest.json') != record['library_baseline']
or check_source and (build_manifest(source.parent) != record['source_manifest']
or engineering_identity(source) != record['source_identity'])):
raise ValueError('Native Add baseline, backup or staged source proof changed.')
raise ValueError('Native Add library baseline or staged source proof changed.')
process = win32api.OpenProcess(win32con.PROCESS_DUP_HANDLE, False, record['supervisor_pid'])
duplicate = None
try:
+3 -16
View File
@@ -621,28 +621,15 @@ def execute_job(job, emit):
pcb_before = {pid for pid, _, _ in pcb_processes()}
if pcb_before:
raise RuntimeError(f'PCB_SESSION_ACTIVE: 已有 PCB 会话,请正常关闭后再校验: {sorted(pcb_before)}')
# Do not recursively snapshot a live CBB over SMB immediately before
# launching Mentor. The backup is evidence only; on Win10 a timed-out
# robocopy can retain network handles/oplocks and make Verify nondeterministic.
# Backups are user-managed on local and network libraries alike.
mapped_drive = str(job.get('mapped_drive') or '')
mapped_remote_root = str(job.get('mapped_remote_root') or '')
if mapped_drive and mapped_remote_root:
from .network_path import ensure_mapped_drive_visible
mapping = ensure_mapped_drive_visible(mapped_drive, mapped_remote_root)
emit(stage='mapped_drive_context', **mapping)
emit(stage='backup', block=job['block_name'])
if is_network_backed_path(block_root, mapped_drive=mapped_drive):
backup = {'status': 'SKIPPED',
'detail': '网络盘 CBB 跳过递归备份,避免 robocopy 与 Mentor 竞争 SMB 文件锁'}
emit(stage='backup_skipped', reason='network_source', source=str(block_root))
else:
backup_budget = backup_timeout_seconds(block_root)
emit(stage='backup_budget', timeout_seconds=backup_budget)
backup = best_effort_backup(block_root, root/'backup'/block_root.name,
timeout_seconds=backup_budget, emit=emit)
emit(stage='backup_done', status=backup.get('status'), detail=backup.get('detail'))
# Backup is evidence only, never a prerequisite for launching PCB. Volatile
# database/log directories are intentionally excluded to avoid file locks.
emit(stage='backup_skipped', reason='manual_backup_policy', source=str(block_root),
detail='应用不自动备份;请在操作前手动备份。')
from .icdb_ownership import database_directories, unreleased_addresses
for database in database_directories(job['lmc_file'], job['project'], job['pcb']):
icdb_address = prepare_icdb_address(database, root, emit=emit)
+1 -1
View File
@@ -101,7 +101,7 @@ class NativeManagementAdapter:
'add': Capability(not add_reason and _PRODUCTION_ADD_VALIDATED, add_reason or
'已验证 EE7.9.5 原生导入及完整工程复读;仅 ASCII 名称、Logical-Physical 和 DxDesigner 库。'),
'update': Capability(not add_reason and _PRODUCTION_ADD_VALIDATED and _PRODUCTION_UPDATE_VALIDATED,
add_reason or '已验证同名原生替换:完整备份后移除并重新导入,失败时保留恢复证据。'),
add_reason or '已验证同名原生替换:移除并重新导入;操作前请手动备份。'),
}
def _worker(self, job, evidence):
+15 -2
View File
@@ -1,4 +1,4 @@
"""Backed-up, single-attempt recovery through the installed native tool."""
"""Single-attempt recovery through the installed native tool."""
from dataclasses import dataclass
import hashlib
import json
@@ -48,6 +48,19 @@ def _hash(path):
return digest.hexdigest()
def check_repair_access(target):
"""Preserve the former pre-copy ownership checks without copying data."""
import win32con, win32file, pywintypes
from .scoped_manifest import scan_tree
scan_tree(target.project.parent) # Reject links before native traversal.
try:
handle = win32file.CreateFile(str(target.database/'icdb.dat'), win32con.GENERIC_READ, 0, None,
win32con.OPEN_EXISTING, win32con.FILE_ATTRIBUTE_NORMAL, None)
except pywintypes.error as error:
raise OSError(f'REPAIR_DATABASE_IN_USE: 无法独占读取数据库:{error}') from error
handle.Close()
def backup_project(target, destination):
"""Keep every original file, holding icdb.dat exclusively during the copy."""
import win32con, win32file, pywintypes
@@ -130,7 +143,7 @@ def attempt_recovery(request, diagnosis, evidence_root, *, progress=None):
target = select_repair_target(request, diagnosis)
if progress:
progress({'stage': 'native_repair_start', 'block': request.block_name,
'detail': '正在备份并尝试原生数据库修复', 'project': str(target.project)})
'detail': '正在核对占用并尝试原生数据库修复;应用不自动备份', 'project': str(target.project)})
from .mentor_adapter import pcb_processes, _process_details
if pcb_processes() or _process_details('LibraryManager.exe'):
raise ValueError('REPAIR_DATABASE_IN_USE: 原生 PCB/Library Manager 会话尚未退出')
+5 -4
View File
@@ -182,7 +182,7 @@ def _native_evidence(project, database, pid, started_ns, baseline, *, output_tex
def repair_worker_main(job_path):
import win32con, win32gui
from .native_repair import RepairTarget, backup_project
from .native_repair import RepairTarget, check_repair_access
from .mentor_paths import discover_sdd_home
from .icdb_recovery import snapshot_log
job = json.loads(Path(job_path).read_text('utf-8'))
@@ -222,10 +222,11 @@ def repair_worker_main(job_path):
if (checked['target'].project.resolve() != project.resolve()
or checked['target'].database.resolve() != database.resolve()):
raise ValueError('MAINTENANCE_TARGET_UNCONFIRMED')
backup_project(RepairTarget(project, database), root/'complete-backup')
emit(stage='complete_backup_verified', path=str(root/'complete-backup'))
check_repair_access(RepairTarget(project, database))
emit(stage='backup_skipped', reason='manual_backup_policy',
detail='应用不自动备份;Mentor 原生修复仍可能生成自身备份。')
if Path(job['cancel_signal']).exists():
raise ValueError('REPAIR_CANCELLED_AFTER_BACKUP')
raise ValueError('REPAIR_CANCELLED_BEFORE_LAUNCH')
if maintenance_context is not None:
with maintenance_target_guard(maintenance_request, maintenance_context): pass
baseline = snapshot_log(project.parent/'Log Files/ProjectBackupLog.txt')
+37
View File
@@ -227,6 +227,43 @@ def build_manifest(root, *, scope=None, exclude=None, progress=None, hash_functi
return _manifest(scope, files)
def build_exclusive_library_manifest(root, *, scope, progress=None):
"""Check every native database is idle while hashing, without making a copy."""
import win32con, win32file, pywintypes
root = Path(root)
entries = scan_tree(root) # Preserve full-library link and ownership checks.
with ExitStack() as stack:
handles = {}
for path, metadata in entries.items():
if stat.S_ISREG(metadata.st_mode) and (path.suffix.casefold() == '.lmc'
or path.name.casefold() == 'icdb.dat'):
try:
handle = win32file.CreateFile(str(path), win32con.GENERIC_READ, 0, None,
win32con.OPEN_EXISTING, win32con.FILE_ATTRIBUTE_NORMAL, None)
except pywintypes.error as error:
raise OSError(f'LIBRARY_DATABASE_IN_USE: 无法独占读取 {path}:{error}') from error
handles[path] = handle
stack.callback(handle.Close)
def digest(path):
if path not in handles:
return hash_file(path)
value = hashlib.sha256()
while True:
try:
_, data = win32file.ReadFile(handles[path], 1024 * 1024)
except pywintypes.error as error:
if error.winerror == 38: # ERROR_HANDLE_EOF
break
raise
if not data:
break
value.update(data)
return value.hexdigest()
return build_manifest(root, scope=scope, progress=progress, hash_function=digest)
def copy_verified(source, destination, *, scope=None, progress=None, hash_function=hash_file):
"""Copy the whole tree, validate all metadata, SHA256 only scoped primary files.
@@ -0,0 +1,5 @@
"""Shared wording for user-managed backups before write operations."""
MANUAL_BACKUP_NOTICE = (
'应用不会自动备份。请先手动备份中心库及相关工程,并确认备份可用于恢复。'
)
@@ -3,9 +3,10 @@ from pathlib import Path
from PySide6.QtCore import QObject, QThreadPool, Signal
from PySide6.QtWidgets import (QComboBox, QDialog, QFileDialog, QFormLayout,
QHBoxLayout, QLabel, QLineEdit, QPushButton)
QHBoxLayout, QLabel, QLineEdit, QPushButton, QMessageBox)
from .workers import ServiceWorker
from .backup_notice import MANUAL_BACKUP_NOTICE
class RecoverySignals(QObject):
@@ -37,7 +38,7 @@ class BackupRecoveryDialog(QDialog):
self.restore_button.clicked.connect(self._restore)
self.close_button = QPushButton('关闭')
self.close_button.clicked.connect(self.reject)
self.status_label = QLabel('使用所选备份版本恢复同名 CBB。先在库副本中验证,原工程与完整库副本会保留;需要额外磁盘空间。')
self.status_label = QLabel(MANUAL_BACKUP_NOTICE + ' 所选备份先在隔离库中验证;安装时旧 Work 仅改名保留。')
self.status_label.setWordWrap(True)
layout = QFormLayout(self)
layout.addRow('目标 CBB', self.block_combo)
@@ -77,6 +78,11 @@ class BackupRecoveryDialog(QDialog):
except Exception as error:
self.status_label.setText(str(error))
return
if QMessageBox.question(self, '确认从备份恢复',
f'{MANUAL_BACKUP_NOTICE}\n\n目标库:{request.lmc_file}\nCBB:{name}\n来源:{source}'
'\n\n将创建用于校验的隔离库副本,校验通过后替换目标工程。确认继续?',
QMessageBox.Yes | QMessageBox.No, QMessageBox.No) != QMessageBox.Yes:
return
self.busy = True
self._set_enabled(False)
self.status_label.setText('正在准备恢复…')
+17 -7
View File
@@ -190,7 +190,7 @@ class MainWindow(QWidget):
maintenance_layout = QVBoxLayout(maintenance)
maintenance_row = QHBoxLayout()
maintenance_row.addWidget(self.icdb_repair_button)
description = QLabel('处理可见非 READY 项;有勾选时仅处理勾选中的可用项。未确认不等于损坏。\n确认工程数据库失联后先备份再修复;无法确认会话安全时停止。')
description = QLabel('处理可见非 READY 项;有勾选时仅处理勾选中的可用项。未确认不等于损坏。\n操作前请手动备份;应用不自动备份。无法确认会话安全时停止。')
description.setWordWrap(True)
maintenance_row.addWidget(description, 1)
maintenance_layout.addLayout(maintenance_row)
@@ -589,20 +589,31 @@ class MainWindow(QWidget):
return [record.name for record in self.selected_records()]
def verify_selected(self):
self._run(self._eligible_names(checked_only=True))
self._confirm_verify(self._eligible_names(checked_only=True))
def verify_all(self):
self._run(self._eligible_names())
self._confirm_verify(self._eligible_names())
def _confirm_verify(self, names):
from .backup_notice import MANUAL_BACKUP_NOTICE
if self.busy or not self.loaded_path or self._maintenance_recovery_view or not names:
return
if QMessageBox.question(self, '确认批量校验',
f'{MANUAL_BACKUP_NOTICE}\n\n目标库:{self.loaded_path}\n'
f'将校验 {len(names)} 个可见非 READY CBB 并保存结果。确认继续?',
QMessageBox.Yes | QMessageBox.No, QMessageBox.No) == QMessageBox.Yes:
self._run(names)
def repair_icdb_all(self):
from .backup_notice import MANUAL_BACKUP_NOTICE
if self.busy or not self.loaded_path: return
names = self._maintenance_names()
if not names: return
answer = QMessageBox.question(self, '非 READY ICDB 检查与修复',
f'当前中心库:{self.loaded_path}\n\n'
f'{MANUAL_BACKUP_NOTICE}\nMentor 原生修复可能生成自身备份。\n\n当前中心库:{self.loaded_path}\n\n'
f'将检查 {len(names)} 个可见非 READY CBB'
f'{"(仅勾选项)" if self.selected_records() else ""}。未确认状态不等于损坏。\n'
'无地址阻止时逐项校验;已有工程地址记录时先核对所有者和独占访问、完整备份,'
'无地址阻止时逐项校验;已有工程地址记录时先核对所有者和独占访问,'
'再由官方工具确认未占用并检查/修复。不会删除地址文件。\n'
'仅本地固定磁盘:严格确认修复并重新独占检查后,可一次确认本次异常退出的读写访问提示。'
'网络盘、UNC 或链接路径不自动确认该提示。\n'
@@ -802,8 +813,7 @@ class MainWindow(QWidget):
self._icdb_completed += 1
self.icdb_progress.setValue(self._icdb_completed)
phases = {'icdb_check_start': '检查工程数据库与校验状态',
'native_repair_start': '准备完整备份与原生修复',
'complete_backup_verified': '完整备份已校验',
'native_repair_start': '核对占用并准备原生修复',
'native_repair_requested': '正在原生修复',
'native_repair_confirmed': '正在原生修复',
'native_repair_finished': '原生修复已结束,正在核对结果'}
+12 -8
View File
@@ -8,6 +8,7 @@ from PySide6.QtWidgets import (QCheckBox, QDialog, QFileDialog, QHBoxLayout, QLa
QMessageBox, QPushButton, QTableWidget, QTableWidgetItem, QTextEdit, QVBoxLayout)
from .workers import ServiceWorker
from .backup_notice import MANUAL_BACKUP_NOTICE
from ..management import run_management_batch, validate_name
RESULT_LABELS = {
@@ -18,10 +19,11 @@ RESULT_LABELS = {
}
STAGE_LABELS = {
'prepare_identity': '正在核对来源工程内容',
'catalog_before': '正在核对原生目录', 'backup': '正在备份完整中心库',
'catalog_before': '正在核对原生目录', 'baseline': '正在记录中心库内容基线',
'stage_source': '正在复制并检查来源工程', 'native_remove': '正在原生移除',
'removed': '原条目已移除', 'native_add': '正在原生上传', 'uploaded': '上传身份已确认',
'verify': '正在校验上传结果', 'verified': '校验已返回', 'copy': '正在复制备份',
'verify': '正在校验上传结果', 'verified': '校验已返回', 'copy': '正在准备来源副本',
'hash': '正在校验主要文件',
}
@@ -57,7 +59,7 @@ class ManagementDialog(QDialog):
self.auto_verify = QCheckBox('本批次上传后自动校验')
self.auto_verify.setChecked(self.template.auto_verify)
self.auto_verify.setVisible(self.operation != 'remove')
self.status_label = QLabel('先预览目标和来源;完整备份保存在目标库之外。更新会先移除再重新导入,失败时保留恢复证据。')
self.status_label = QLabel(MANUAL_BACKUP_NOTICE + ' 更新会先移除再重新导入,失败时请使用手动备份恢复。')
self.status_label.setWordWrap(True)
self.output = QTextEdit(); self.output.setReadOnly(True)
self.execute_button = QPushButton('预览并确认执行…')
@@ -66,7 +68,7 @@ class ManagementDialog(QDialog):
self.stop_button.clicked.connect(self.stop.set)
self.close_button = QPushButton('关闭'); self.close_button.clicked.connect(self.reject)
layout = QVBoxLayout(self)
layout.addWidget(QLabel(f'目标库:{self.template.library}\n备份/证据:{self.template.evidence_dir}'))
layout.addWidget(QLabel(f'目标库:{self.template.library}\n操作记录:{self.template.evidence_dir}'))
layout.addWidget(self.table)
layout.addWidget(self.sources_button); layout.addWidget(self.auto_verify)
layout.addWidget(self.status_label); layout.addWidget(self.output)
@@ -127,12 +129,12 @@ class ManagementDialog(QDialog):
except ValueError as error:
self.status_label.setText(str(error)); return
preview = '\n'.join(f'{r.partition} / {r.name}' + (f' ← {r.source}' if r.source else '') for r in requests)
description = ('同名更新先备份,再原生移除并重新导入;导入失败需要人工恢复。' if self.operation == 'update'
else '移除前保留完整工程和中心库备份。' if self.operation == 'remove'
description = ('同名更新会原生移除并重新导入;导入失败需要使用手动备份恢复。' if self.operation == 'update'
else '将通过原生操作移除所列 CBB;恢复时需要使用手动备份。' if self.operation == 'remove'
else '新增同名冲突会拒绝覆盖,完整来源工程将先复制到暂存区。')
answer = QMessageBox.question(self, '确认管理操作',
f'{description}\n\n目标库:{self.template.library}\n{preview}\n\n'
f'完整备份与检查点:{self.template.evidence_dir}\n确认执行?', QMessageBox.Yes | QMessageBox.No,
f'{MANUAL_BACKUP_NOTICE}\n{description}\n\n目标库:{self.template.library}\n{preview}\n\n'
f'操作记录与检查点:{self.template.evidence_dir}\n确认继续执行?', QMessageBox.Yes | QMessageBox.No,
QMessageBox.No)
if answer != QMessageBox.Yes:
return
@@ -156,6 +158,8 @@ class ManagementDialog(QDialog):
text = f'{event.get("block", "")} {STAGE_LABELS.get(stage, RESULT_LABELS.get(stage, stage))}'
if 'copied_files' in event:
text += f' {event["copied_files"]}/{event.get("total_files", "?")}'
elif 'hashed_files' in event:
text += f' {event["hashed_files"]}/{event.get("total_files", "?")} · {event.get("hashed_bytes", 0)} 字节'
self.status_label.setText(text)
def _result(self, results):