//go:build !windows // +build !windows package cmd import ( "fmt" "os" "os/user" "path/filepath" "runtime" "strings" "github.com/evil7/hostsync/utils" ) // setupWindowsEnvironment 在非 Windows 平台上不执行任何操作 func setupWindowsEnvironment(installDir string) error { return fmt.Errorf("Windows 特定功能不支持当前平台 (%s)", runtime.GOOS) } // setupUnixEnvironment 设置Unix/Linux环境 func setupUnixEnvironment(installDir string) error { utils.LogInfo("配置Unix/Linux环境变量...") currentUser, err := user.Current() if err != nil { return fmt.Errorf("获取当前用户信息失败: %v", err) } // 检查常见的shell配置文件 shellRcFiles := []string{ filepath.Join(currentUser.HomeDir, ".bashrc"), filepath.Join(currentUser.HomeDir, ".zshrc"), filepath.Join(currentUser.HomeDir, ".profile"), } exportLine := fmt.Sprintf("export PATH=\"%s:$PATH\"", installDir) updated := false for _, rcFile := range shellRcFiles { if !utils.FileExists(rcFile) { continue } // 读取文件内容 content, err := os.ReadFile(rcFile) if err != nil { utils.LogWarning("读取 %s 失败: %v", rcFile, err) continue } // 检查是否已经添加过 if strings.Contains(string(content), installDir) { utils.LogSuccess("%s 已包含程序路径", rcFile) updated = true continue } // 添加PATH导出 f, err := os.OpenFile(rcFile, os.O_APPEND|os.O_WRONLY, 0644) if err != nil { utils.LogWarning("打开 %s 失败: %v", rcFile, err) continue } f.WriteString("\n# HostSync PATH\n") f.WriteString(exportLine + "\n") f.Close() utils.LogSuccess("已添加PATH到 %s", rcFile) updated = true } if !updated { utils.LogWarning("未找到shell配置文件,请手动将以下路径添加到PATH:") utils.LogInfo(" %s", installDir) utils.LogInfo("💡 可以在 ~/.bashrc 或 ~/.zshrc 中添加:") utils.LogInfo(" %s", exportLine) } else { utils.LogInfo("💡 请重新加载shell配置或重启终端以使环境变量生效") } return nil }