|
| 1 | +package commands |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + |
| 6 | + "github.com/branchd-dev/branchd/internal/cli/config" |
| 7 | + "github.com/branchd-dev/branchd/internal/cli/serverselect" |
| 8 | + "github.com/branchd-dev/branchd/internal/cli/userconfig" |
| 9 | + "github.com/spf13/cobra" |
| 10 | +) |
| 11 | + |
| 12 | +// NewSelectServerCmd creates the select-server command |
| 13 | +func NewSelectServerCmd() *cobra.Command { |
| 14 | + cmd := &cobra.Command{ |
| 15 | + Use: "select-server [ip-or-alias]", |
| 16 | + Short: "Select the default server to use for commands", |
| 17 | + Long: `Select the default server to use for commands. |
| 18 | +
|
| 19 | +If no IP or alias is provided, an interactive prompt will be shown. |
| 20 | +Otherwise, you can directly specify a server by its IP address or alias. |
| 21 | +
|
| 22 | +Examples: |
| 23 | + branchd select-server # Interactive selection |
| 24 | + branchd select-server 192.168.1.1 # Select by IP |
| 25 | + branchd select-server production # Select by alias`, |
| 26 | + Args: cobra.MaximumNArgs(1), |
| 27 | + RunE: func(cmd *cobra.Command, args []string) error { |
| 28 | + var ipOrAlias string |
| 29 | + if len(args) > 0 { |
| 30 | + ipOrAlias = args[0] |
| 31 | + } |
| 32 | + return runSelectServer(ipOrAlias) |
| 33 | + }, |
| 34 | + } |
| 35 | + |
| 36 | + return cmd |
| 37 | +} |
| 38 | + |
| 39 | +func runSelectServer(ipOrAlias string) error { |
| 40 | + // Load project config |
| 41 | + cfg, err := config.LoadFromCurrentDir() |
| 42 | + if err != nil { |
| 43 | + return fmt.Errorf("failed to load config: %w\nRun 'branchd init' to create a configuration file", err) |
| 44 | + } |
| 45 | + |
| 46 | + var server *config.Server |
| 47 | + |
| 48 | + if ipOrAlias != "" { |
| 49 | + // User provided an IP or alias, find it |
| 50 | + server, err = serverselect.GetServerByIPOrAlias(cfg, ipOrAlias) |
| 51 | + if err != nil { |
| 52 | + return err |
| 53 | + } |
| 54 | + } else { |
| 55 | + // Show interactive selection |
| 56 | + server, err = serverselect.PromptServerSelection(cfg) |
| 57 | + if err != nil { |
| 58 | + return err |
| 59 | + } |
| 60 | + } |
| 61 | + |
| 62 | + // Save the selected server |
| 63 | + if err := userconfig.SetSelectedServer(server.IP); err != nil { |
| 64 | + return fmt.Errorf("failed to save selected server: %w", err) |
| 65 | + } |
| 66 | + |
| 67 | + fmt.Printf("Selected server: %s (%s)\n", server.Alias, server.IP) |
| 68 | + return nil |
| 69 | +} |
0 commit comments