mirror of
https://tangled.org/evan.jarrett.net/at-container-registry
synced 2026-04-20 16:40:29 +00:00
97 lines
2.0 KiB
Go
97 lines
2.0 KiB
Go
package main
|
|
|
|
import (
|
|
"fmt"
|
|
"os"
|
|
"sort"
|
|
|
|
"github.com/charmbracelet/huh"
|
|
"github.com/spf13/cobra"
|
|
)
|
|
|
|
func newSwitchCmd() *cobra.Command {
|
|
return &cobra.Command{
|
|
Use: "switch [registry]",
|
|
Short: "Switch the active account for a registry",
|
|
Long: "Switch the active account used for Docker operations.\nDefault registry: atcr.io",
|
|
Args: cobra.MaximumNArgs(1),
|
|
RunE: runSwitch,
|
|
}
|
|
}
|
|
|
|
func runSwitch(cmd *cobra.Command, args []string) error {
|
|
serverURL := "atcr.io"
|
|
if len(args) > 0 {
|
|
serverURL = args[0]
|
|
}
|
|
|
|
appViewURL := buildAppViewURL(serverURL)
|
|
|
|
cfg, err := loadConfig()
|
|
if err != nil {
|
|
return fmt.Errorf("loading config: %w", err)
|
|
}
|
|
|
|
reg := cfg.findRegistry(appViewURL)
|
|
if reg == nil || len(reg.Accounts) == 0 {
|
|
fmt.Fprintf(os.Stderr, "No accounts configured for %s.\n", serverURL)
|
|
fmt.Fprintf(os.Stderr, "Run: docker-credential-atcr login\n")
|
|
return nil
|
|
}
|
|
|
|
if len(reg.Accounts) == 1 {
|
|
for h := range reg.Accounts {
|
|
fmt.Fprintf(os.Stderr, "Only one account (%s) — nothing to switch.\n", h)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// For exactly 2 accounts, just toggle
|
|
if len(reg.Accounts) == 2 {
|
|
for h := range reg.Accounts {
|
|
if h != reg.Active {
|
|
reg.Active = h
|
|
if err := cfg.save(); err != nil {
|
|
return fmt.Errorf("saving config: %w", err)
|
|
}
|
|
fmt.Printf("Switched to %s on %s\n", h, serverURL)
|
|
return nil
|
|
}
|
|
}
|
|
}
|
|
|
|
// 3+ accounts: interactive select
|
|
var handles []string
|
|
for h := range reg.Accounts {
|
|
handles = append(handles, h)
|
|
}
|
|
sort.Strings(handles)
|
|
|
|
var options []huh.Option[string]
|
|
for _, h := range handles {
|
|
label := h
|
|
if h == reg.Active {
|
|
label += " (current)"
|
|
}
|
|
options = append(options, huh.NewOption(label, h))
|
|
}
|
|
|
|
var selected string
|
|
err = huh.NewSelect[string]().
|
|
Title("Select account for " + serverURL).
|
|
Options(options...).
|
|
Value(&selected).
|
|
Run()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
reg.Active = selected
|
|
if err := cfg.save(); err != nil {
|
|
return fmt.Errorf("saving config: %w", err)
|
|
}
|
|
|
|
fmt.Printf("Switched to %s on %s\n", selected, serverURL)
|
|
return nil
|
|
}
|