Files
rainyun-cli/cmd/cli/commands/providercmd/provider.go
T

95 lines
2.5 KiB
Go

package providercmd
import (
"fmt"
"git.yoresee.cc/nightstar/ry/internal/config"
"git.yoresee.cc/nightstar/ry/internal/provider"
"github.com/spf13/cobra"
)
func Cmd(cfg *config.Config, cfgPath string) *cobra.Command {
providerCmd := &cobra.Command{
Use: "provider",
Short: "Manage cloud providers",
}
providerListCmd := &cobra.Command{
Use: "list",
Short: "List configured providers",
Annotations: map[string]string{"skipProvider": "true"},
RunE: func(cmd *cobra.Command, args []string) error {
current := ""
if cfg != nil {
current = cfg.CurrentProvider
}
for _, name := range provider.List() {
marker := " "
if name == current {
marker = "*"
}
fmt.Printf("%s %s\n", marker, name)
}
return nil
},
}
providerUseCmd := &cobra.Command{
Use: "use <name>",
Short: "Switch the current cloud provider",
Annotations: map[string]string{"skipProvider": "true"},
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
name := args[0]
if _, ok := cfg.Providers[name]; !ok {
return fmt.Errorf("provider %q not configured — run 'ry provider add %s' first", name, name)
}
cfg.CurrentProvider = name
if err := config.Save(cfgPath, cfg); err != nil {
return fmt.Errorf("save config: %w", err)
}
fmt.Printf("Switched to provider %q\n", name)
return nil
},
}
providerAddCmd := &cobra.Command{
Use: "add <name>",
Short: "Add a new cloud provider",
Annotations: map[string]string{"skipProvider": "true"},
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
name := args[0]
fmt.Printf("Adding provider %q...\n", name)
fmt.Print("Enter API Key: ")
var apiKey string
fmt.Scanln(&apiKey)
if apiKey == "" {
return fmt.Errorf("API Key is required")
}
if cfg.Providers == nil {
cfg.Providers = make(map[string]config.ProviderConfig)
}
cfg.Providers[name] = config.ProviderConfig{APIKey: apiKey}
if cfg.CurrentProvider == "" {
cfg.CurrentProvider = name
}
if err := config.Save(cfgPath, cfg); err != nil {
return fmt.Errorf("save config: %w", err)
}
fmt.Printf("Provider %q added successfully\n", name)
if cfg.CurrentProvider == name {
fmt.Printf("Set as current provider\n")
}
return nil
},
}
providerCmd.AddCommand(providerListCmd)
providerCmd.AddCommand(providerUseCmd)
providerCmd.AddCommand(providerAddCmd)
return providerCmd
}