🎨 Optimize code

This commit is contained in:
2025-06-22 15:08:38 +08:00
parent 35c89e086e
commit eb9b037f8e
22 changed files with 937 additions and 1906 deletions

View File

@@ -9,6 +9,7 @@ import (
"path/filepath"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/wailsapp/wails/v3/pkg/services/log"
@@ -18,25 +19,26 @@ import (
type MigrationStatus string
const (
MigrationStatusMigrating MigrationStatus = "migrating" // 迁移中
MigrationStatusCompleted MigrationStatus = "completed" // 完成
MigrationStatusFailed MigrationStatus = "failed" // 失败
MigrationStatusMigrating MigrationStatus = "migrating"
MigrationStatusCompleted MigrationStatus = "completed"
MigrationStatusFailed MigrationStatus = "failed"
)
// MigrationProgress 迁移进度信息
type MigrationProgress struct {
Status MigrationStatus `json:"status"` // 迁移状态
Progress float64 `json:"progress"` // 进度百分比 (0-100)
Error string `json:"error,omitempty"` // 错误信息
Status MigrationStatus `json:"status"`
Progress float64 `json:"progress"`
Error string `json:"error,omitempty"`
}
// MigrationService 迁移服务
type MigrationService struct {
logger *log.LoggerService
mu sync.RWMutex
currentProgress MigrationProgress
cancelFunc context.CancelFunc
ctx context.Context
logger *log.LoggerService
mu sync.RWMutex
progress atomic.Value // stores MigrationProgress
ctx context.Context
cancel context.CancelFunc
}
// NewMigrationService 创建迁移服务
@@ -45,27 +47,27 @@ func NewMigrationService(logger *log.LoggerService) *MigrationService {
logger = log.New()
}
return &MigrationService{
ms := &MigrationService{
logger: logger,
currentProgress: MigrationProgress{
Status: MigrationStatusCompleted, // 初始状态为完成
Progress: 0,
},
}
// 初始化进度
ms.progress.Store(MigrationProgress{
Status: MigrationStatusCompleted,
Progress: 0,
})
return ms
}
// GetProgress 获取当前进度
func (ms *MigrationService) GetProgress() MigrationProgress {
ms.mu.RLock()
defer ms.mu.RUnlock()
return ms.currentProgress
return ms.progress.Load().(MigrationProgress)
}
// updateProgress 更新进度
func (ms *MigrationService) updateProgress(progress MigrationProgress) {
ms.mu.Lock()
ms.currentProgress = progress
ms.mu.Unlock()
ms.progress.Store(progress)
}
// MigrateDirectory 迁移目录
@@ -74,71 +76,83 @@ func (ms *MigrationService) MigrateDirectory(srcPath, dstPath string) error {
ctx, cancel := context.WithCancel(context.Background())
ms.mu.Lock()
ms.ctx = ctx
ms.cancelFunc = cancel
ms.cancel = cancel
ms.mu.Unlock()
defer func() {
ms.mu.Lock()
ms.cancelFunc = nil
ms.cancel = nil
ms.ctx = nil
ms.mu.Unlock()
}()
ms.logger.Info("Migration: Starting directory migration", "from", srcPath, "to", dstPath)
// 初始化进度
progress := MigrationProgress{
ms.updateProgress(MigrationProgress{
Status: MigrationStatusMigrating,
Progress: 0,
}
ms.updateProgress(progress)
})
// 预检查
if err := ms.preCheck(srcPath, dstPath); err != nil {
if err == errNoMigrationNeeded {
ms.updateProgress(MigrationProgress{
Status: MigrationStatusCompleted,
Progress: 100,
})
return nil
}
return ms.failWithError(err)
}
// 执行原子迁移
if err := ms.atomicMove(ctx, srcPath, dstPath); err != nil {
return ms.failWithError(err)
}
// 迁移完成
ms.updateProgress(MigrationProgress{
Status: MigrationStatusCompleted,
Progress: 100,
})
return nil
}
var errNoMigrationNeeded = fmt.Errorf("no migration needed")
// preCheck 预检查
func (ms *MigrationService) preCheck(srcPath, dstPath string) error {
// 检查源目录是否存在
if _, err := os.Stat(srcPath); os.IsNotExist(err) {
progress.Status = MigrationStatusCompleted
progress.Progress = 100
ms.updateProgress(progress)
return nil
return errNoMigrationNeeded
}
// 如果路径相同,不需要迁移
srcAbs, _ := filepath.Abs(srcPath)
dstAbs, _ := filepath.Abs(dstPath)
if srcAbs == dstAbs {
progress.Status = MigrationStatusCompleted
progress.Progress = 100
ms.updateProgress(progress)
return nil
return errNoMigrationNeeded
}
// 检查目标路径是否是源路径的子目录
if ms.isSubDirectory(srcAbs, dstAbs) {
progress.Status = MigrationStatusFailed
progress.Error = "Target path cannot be a subdirectory of source path"
ms.updateProgress(progress)
return fmt.Errorf("target path cannot be a subdirectory of source path")
}
// 执行原子迁移
err := ms.atomicMove(ctx, srcPath, dstPath, &progress)
if err != nil {
progress.Status = MigrationStatusFailed
progress.Error = err.Error()
ms.updateProgress(progress)
return err
}
// 迁移完成
progress.Status = MigrationStatusCompleted
progress.Progress = 100
ms.updateProgress(progress)
ms.logger.Info("Migration: Directory migration completed", "from", srcPath, "to", dstPath)
return nil
}
// failWithError 失败并记录错误
func (ms *MigrationService) failWithError(err error) error {
ms.updateProgress(MigrationProgress{
Status: MigrationStatusFailed,
Error: err.Error(),
})
return err
}
// atomicMove 原子移动目录
func (ms *MigrationService) atomicMove(ctx context.Context, srcPath, dstPath string, progress *MigrationProgress) error {
func (ms *MigrationService) atomicMove(ctx context.Context, srcPath, dstPath string) error {
// 检查是否取消
select {
case <-ctx.Done():
@@ -147,68 +161,84 @@ func (ms *MigrationService) atomicMove(ctx context.Context, srcPath, dstPath str
}
// 确保目标目录的父目录存在
dstParent := filepath.Dir(dstPath)
if err := os.MkdirAll(dstParent, 0755); err != nil {
return fmt.Errorf("Failed to create target parent directory")
if err := os.MkdirAll(filepath.Dir(dstPath), 0755); err != nil {
return fmt.Errorf("failed to create target parent directory: %v", err)
}
// 检查目标路径情况
if stat, err := os.Stat(dstPath); err == nil {
if !stat.IsDir() {
return fmt.Errorf("Target path exists but is not a directory")
}
isEmpty, err := ms.isDirectoryEmpty(dstPath)
if err != nil {
return fmt.Errorf("Failed to check target directory")
}
if !isEmpty {
return fmt.Errorf("Target directory is not empty")
}
// 检查目标路径
if err := ms.checkTargetPath(dstPath); err != nil {
return err
}
// 尝试直接重命名(如果在同一分区,这会很快)
progress.Progress = 20
ms.updateProgress(*progress)
// 尝试直接重命名
ms.updateProgress(MigrationProgress{
Status: MigrationStatusMigrating,
Progress: 20,
})
if err := os.Rename(srcPath, dstPath); err == nil {
ms.logger.Info("Migration: Fast rename successful")
return nil
} else {
ms.logger.Info("Migration: Fast rename failed, using copy method", "error", err)
}
// 重命名失败,使用压缩迁移
progress.Progress = 30
ms.updateProgress(*progress)
ms.updateProgress(MigrationProgress{
Status: MigrationStatusMigrating,
Progress: 30,
})
return ms.atomicCompressMove(ctx, srcPath, dstPath, progress)
return ms.compressMove(ctx, srcPath, dstPath)
}
// atomicCompressMove 原子压缩迁移
func (ms *MigrationService) atomicCompressMove(ctx context.Context, srcPath, dstPath string, progress *MigrationProgress) error {
tempDir := os.TempDir()
tempZipFile := filepath.Join(tempDir, fmt.Sprintf("voidraft_migration_%d.zip", time.Now().UnixNano()))
// checkTargetPath 检查目标路径
func (ms *MigrationService) checkTargetPath(dstPath string) error {
stat, err := os.Stat(dstPath)
if os.IsNotExist(err) {
return nil
}
if err != nil {
return fmt.Errorf("failed to check target path: %v", err)
}
defer func() {
if err := os.Remove(tempZipFile); err != nil && !os.IsNotExist(err) {
ms.logger.Error("Migration: Failed to clean up temporary zip file", "error", err)
}
}()
if !stat.IsDir() {
return fmt.Errorf("target path exists but is not a directory")
}
isEmpty, err := ms.isDirectoryEmpty(dstPath)
if err != nil {
return fmt.Errorf("failed to check target directory: %v", err)
}
if !isEmpty {
return fmt.Errorf("target directory is not empty")
}
return nil
}
// compressMove 压缩迁移
func (ms *MigrationService) compressMove(ctx context.Context, srcPath, dstPath string) error {
tempZipFile := filepath.Join(os.TempDir(),
fmt.Sprintf("voidraft_migration_%d.zip", time.Now().UnixNano()))
defer os.Remove(tempZipFile)
// 压缩源目录
progress.Progress = 40
ms.updateProgress(*progress)
ms.updateProgress(MigrationProgress{
Status: MigrationStatusMigrating,
Progress: 40,
})
if err := ms.compressDirectory(ctx, srcPath, tempZipFile); err != nil {
return fmt.Errorf("Failed to compress source directory")
return fmt.Errorf("failed to compress source directory: %v", err)
}
// 解压到目标位置
progress.Progress = 70
ms.updateProgress(*progress)
ms.updateProgress(MigrationProgress{
Status: MigrationStatusMigrating,
Progress: 70,
})
if err := ms.extractToDirectory(ctx, tempZipFile, dstPath); err != nil {
return fmt.Errorf("Failed to extract to target location")
return fmt.Errorf("failed to extract to target location: %v", err)
}
// 检查是否取消
@@ -220,13 +250,12 @@ func (ms *MigrationService) atomicCompressMove(ctx context.Context, srcPath, dst
}
// 删除源目录
progress.Progress = 90
ms.updateProgress(*progress)
if err := os.RemoveAll(srcPath); err != nil {
ms.logger.Error("Migration: Failed to remove source directory", "error", err)
}
ms.updateProgress(MigrationProgress{
Status: MigrationStatusMigrating,
Progress: 90,
})
os.RemoveAll(srcPath)
return nil
}
@@ -234,7 +263,7 @@ func (ms *MigrationService) atomicCompressMove(ctx context.Context, srcPath, dst
func (ms *MigrationService) compressDirectory(ctx context.Context, srcDir, zipFile string) error {
zipWriter, err := os.Create(zipFile)
if err != nil {
return fmt.Errorf("Failed to create temporary file")
return err
}
defer zipWriter.Close()
@@ -254,21 +283,16 @@ func (ms *MigrationService) compressDirectory(ctx context.Context, srcDir, zipFi
}
relPath, err := filepath.Rel(srcDir, filePath)
if err != nil {
if err != nil || relPath == "." {
return err
}
if relPath == "." {
return nil
}
header, err := zip.FileInfoHeader(info)
if err != nil {
return err
}
header.Name = strings.ReplaceAll(relPath, string(filepath.Separator), "/")
if info.IsDir() {
header.Name += "/"
header.Method = zip.Store
@@ -282,32 +306,34 @@ func (ms *MigrationService) compressDirectory(ctx context.Context, srcDir, zipFi
}
if !info.IsDir() {
file, err := os.Open(filePath)
if err != nil {
return err
}
defer file.Close()
_, err = io.Copy(writer, file)
if err != nil {
return err
}
return ms.copyFileToZip(filePath, writer)
}
return nil
})
}
// copyFileToZip 复制文件到zip
func (ms *MigrationService) copyFileToZip(filePath string, writer io.Writer) error {
file, err := os.Open(filePath)
if err != nil {
return err
}
defer file.Close()
_, err = io.Copy(writer, file)
return err
}
// extractToDirectory 从zip文件解压到目录
func (ms *MigrationService) extractToDirectory(ctx context.Context, zipFile, dstDir string) error {
reader, err := zip.OpenReader(zipFile)
if err != nil {
return fmt.Errorf("Failed to open temporary file")
return err
}
defer reader.Close()
if err := os.MkdirAll(dstDir, 0755); err != nil {
return fmt.Errorf("Failed to create target directory")
return err
}
for _, file := range reader.File {
@@ -318,25 +344,7 @@ func (ms *MigrationService) extractToDirectory(ctx context.Context, zipFile, dst
default:
}
dstPath := filepath.Join(dstDir, file.Name)
// 安全检查防止zip slip攻击
if !strings.HasPrefix(dstPath, filepath.Clean(dstDir)+string(os.PathSeparator)) {
return fmt.Errorf("Invalid file path in archive")
}
if file.FileInfo().IsDir() {
if err := os.MkdirAll(dstPath, file.FileInfo().Mode()); err != nil {
return err
}
continue
}
if err := os.MkdirAll(filepath.Dir(dstPath), 0755); err != nil {
return err
}
if err := ms.extractFile(file, dstPath); err != nil {
if err := ms.extractSingleFile(file, dstDir); err != nil {
return err
}
}
@@ -344,8 +352,23 @@ func (ms *MigrationService) extractToDirectory(ctx context.Context, zipFile, dst
return nil
}
// extractFile 解压单个文件
func (ms *MigrationService) extractFile(file *zip.File, dstPath string) error {
// extractSingleFile 解压单个文件
func (ms *MigrationService) extractSingleFile(file *zip.File, dstDir string) error {
dstPath := filepath.Join(dstDir, file.Name)
// 安全检查防止zip slip攻击
if !strings.HasPrefix(dstPath, filepath.Clean(dstDir)+string(os.PathSeparator)) {
return fmt.Errorf("invalid file path in archive: %s", file.Name)
}
if file.FileInfo().IsDir() {
return os.MkdirAll(dstPath, file.FileInfo().Mode())
}
if err := os.MkdirAll(filepath.Dir(dstPath), 0755); err != nil {
return err
}
srcFile, err := file.Open()
if err != nil {
return err
@@ -371,20 +394,14 @@ func (ms *MigrationService) isDirectoryEmpty(dirPath string) (bool, error) {
defer f.Close()
_, err = f.Readdir(1)
if err == io.EOF {
return true, nil
}
if err != nil {
return false, err
}
return false, nil
return err == io.EOF, nil
}
// isSubDirectory 检查target是否是parent的子目录
func (ms *MigrationService) isSubDirectory(parent, target string) bool {
parent = filepath.Clean(parent) + string(filepath.Separator)
target = filepath.Clean(target) + string(filepath.Separator)
return len(target) > len(parent) && target[:len(parent)] == parent
return len(target) > len(parent) && strings.HasPrefix(target, parent)
}
// CancelMigration 取消迁移
@@ -392,21 +409,16 @@ func (ms *MigrationService) CancelMigration() error {
ms.mu.Lock()
defer ms.mu.Unlock()
if ms.cancelFunc != nil {
ms.cancelFunc()
ms.logger.Info("Migration: Cancellation requested")
if ms.cancel != nil {
ms.cancel()
return nil
}
return fmt.Errorf("No active migration to cancel")
return fmt.Errorf("no active migration to cancel")
}
// ServiceShutdown 服务关闭
func (ms *MigrationService) ServiceShutdown() error {
ms.logger.Info("Migration: Service is shutting down...")
if err := ms.CancelMigration(); err != nil {
ms.logger.Debug("Migration: No active migration to cancel during shutdown")
}
ms.logger.Info("Migration: Service shutdown completed")
ms.CancelMigration()
return nil
}