增加 id 迁移的补丁
This commit is contained in:
1 parent
338926e772
commit
6695f6e4a6
1 file changed
+75
@@ -22,6 +22,18 @@ func NewManager() *Manager {
|
||||
}
|
||||
}
|
||||
|
||||
func oldGetIDFilePath() string {
|
||||
// 获取用户主目录
|
||||
homeDir, err := os.UserHomeDir()
|
||||
if err != nil {
|
||||
// 如果无法获取主目录,使用当前目录
|
||||
homeDir = "."
|
||||
}
|
||||
|
||||
// 统一使用 ~/.pika/agent.id
|
||||
return filepath.Join(homeDir, ".pika", "agent.id")
|
||||
}
|
||||
|
||||
// GetIDFilePath 获取 ID 文件路径
|
||||
func GetIDFilePath() string {
|
||||
// 获取用户主目录
|
||||
@@ -33,6 +45,12 @@ func GetIDFilePath() string {
|
||||
// Load 加载或生成探针 ID
|
||||
// 如果 ID 文件存在,则读取;否则生成新的 UUID 并保存
|
||||
func (m *Manager) Load() (string, error) {
|
||||
// 尝试从旧路径迁移
|
||||
if err := m.migrateFromOldPath(); err != nil {
|
||||
// 迁移失败不影响后续流程,仅记录错误
|
||||
fmt.Printf("警告: 迁移旧 ID 文件失败: %v\n", err)
|
||||
}
|
||||
|
||||
// 尝试读取现有 ID
|
||||
if id, err := m.read(); err == nil && id != "" {
|
||||
return id, nil
|
||||
@@ -95,3 +113,60 @@ func (m *Manager) Exists() bool {
|
||||
func (m *Manager) Delete() error {
|
||||
return os.Remove(m.idFilePath)
|
||||
}
|
||||
|
||||
// migrateFromOldPath 从旧路径迁移 ID 文件到新路径
|
||||
func (m *Manager) migrateFromOldPath() error {
|
||||
oldPath := oldGetIDFilePath()
|
||||
newPath := m.idFilePath
|
||||
|
||||
// 如果旧路径和新路径相同,无需迁移
|
||||
if oldPath == newPath {
|
||||
return nil
|
||||
}
|
||||
|
||||
// 检查旧文件是否存在
|
||||
oldInfo, err := os.Stat(oldPath)
|
||||
if err != nil {
|
||||
// 旧文件不存在,无需迁移
|
||||
if os.IsNotExist(err) {
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("检查旧 ID 文件失败: %w", err)
|
||||
}
|
||||
|
||||
// 检查新文件是否已存在
|
||||
if _, err := os.Stat(newPath); err == nil {
|
||||
// 新文件已存在,不覆盖,删除旧文件
|
||||
fmt.Printf("新 ID 文件已存在,删除旧文件: %s\n", oldPath)
|
||||
return os.Remove(oldPath)
|
||||
}
|
||||
|
||||
// 确保新路径的目录存在
|
||||
newDir := filepath.Dir(newPath)
|
||||
if err := os.MkdirAll(newDir, 0755); err != nil {
|
||||
return fmt.Errorf("创建新目录失败: %w", err)
|
||||
}
|
||||
|
||||
// 移动文件
|
||||
if err := os.Rename(oldPath, newPath); err != nil {
|
||||
// 如果 Rename 失败(可能跨文件系统),尝试复制后删除
|
||||
data, readErr := os.ReadFile(oldPath)
|
||||
if readErr != nil {
|
||||
return fmt.Errorf("读取旧 ID 文件失败: %w", readErr)
|
||||
}
|
||||
|
||||
if writeErr := os.WriteFile(newPath, data, oldInfo.Mode()); writeErr != nil {
|
||||
return fmt.Errorf("写入新 ID 文件失败: %w", writeErr)
|
||||
}
|
||||
|
||||
if removeErr := os.Remove(oldPath); removeErr != nil {
|
||||
fmt.Printf("警告: 删除旧 ID 文件失败: %v\n", removeErr)
|
||||
}
|
||||
|
||||
fmt.Printf("已迁移 ID 文件: %s -> %s\n", oldPath, newPath)
|
||||
return nil
|
||||
}
|
||||
|
||||
fmt.Printf("已迁移 ID 文件: %s -> %s\n", oldPath, newPath)
|
||||
return nil
|
||||
}
|
||||
Reference in new issue
Block a user