package utils import ( "bufio" "fmt" "os" "os/exec" "runtime" "strings" ) // WriteFile writes content to a file, exiting on error. func WriteFile(path, content string) { if err := os.WriteFile(path, []byte(content), 0644); err != nil { fmt.Printf("[ERROR] Failed to write file %s: %v\n", path, err) os.Exit(1) } } // CommandExists checks if a command exists in the system's PATH. func CommandExists(cmd string) bool { _, err := exec.LookPath(cmd) return err == nil } // RunCommand runs a command with its output visible to the user. func RunCommand(name string, args ...string) error { cmd := exec.Command(name, args...) cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr return cmd.Run() } // RunCommandQuiet runs a command without printing its stdout. func RunCommandQuiet(name string, args ...string) error { cmd := exec.Command(name, args...) cmd.Stderr = os.Stderr return cmd.Run() } // RunCommandInDir runs a command in a specific directory. func RunCommandInDir(dir string, name string, args ...string) error { cmd := exec.Command(name, args...) cmd.Dir = dir cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr return cmd.Run() } // HandleKubectlCacheError detects a specific kubectl cache error and offers an interactive fix. func HandleKubectlCacheError(err error) { // Guard clause: Only proceed if the error is the one we're looking for. if err == nil || !strings.Contains(err.Error(), "no matches for kind") { return } fmt.Println("\n[DIAGNOSIS] A common kubectl cache issue was detected.") fmt.Println("This happens when kubectl's local cache is out of sync with the cluster, often after installing new CRDs.") fmt.Print("Would you like to attempt to clear the cache now? (y/N): ") reader := bufio.NewReader(os.Stdin) response, _ := reader.ReadString('\n') if strings.TrimSpace(strings.ToLower(response)) != "y" { fmt.Println("[INFO] Operation cancelled by user.") return } var cmd *exec.Cmd var shell string // Determine the correct command based on the operating system. if runtime.GOOS == "windows" { shell = "PowerShell" // Using -NoProfile and -NonInteractive for cleaner execution cmd = exec.Command("powershell", "-NoProfile", "-NonInteractive", "-Command", "Remove-Item -Path $env:USERPROFILE\\.kube\\cache -Recurse -Force") } else { shell = "shell" // The user's home directory can be fetched reliably. homeDir, err := os.UserHomeDir() if err != nil { fmt.Printf("[ERROR] Could not determine home directory to clear cache: %v\n", err) return } cachePath := fmt.Sprintf("%s/.kube/cache", homeDir) cmd = exec.Command("rm", "-rf", cachePath) } fmt.Printf("[INFO] Attempting to clear kubectl cache using %s...\n", shell) cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr if err := cmd.Run(); err != nil { fmt.Printf("[ERROR] Failed to clear kubectl cache: %v\n", err) } else { fmt.Println("[SUCCESS] Kubectl cache cleared successfully.") fmt.Println("[INFO] Please try running the previous command again.") } }