Skip to content

Commit

Permalink
Refactor cluster switch to prompt user for selection if no domain pro…
Browse files Browse the repository at this point in the history
…vided
  • Loading branch information
andscoop committed Oct 8, 2018
1 parent f44108a commit e3777db
Show file tree
Hide file tree
Showing 2 changed files with 73 additions and 6 deletions.
70 changes: 66 additions & 4 deletions cluster/cluster.go
@@ -1,21 +1,26 @@
package cluster

import (
"strconv"
"strings"

"github.com/astronomerio/astro-cli/config"
"github.com/astronomerio/astro-cli/pkg/input"
"github.com/astronomerio/astro-cli/pkg/printutil"
"github.com/pkg/errors"
)

// List all available clusters a user has previously authenticated to
// Returns error
func List() error {
tab := printutil.Table{
var (
tab = printutil.Table{
Padding: []int{44},
Header: []string{"NAME"},
ColorRowCode: [2]string{"\033[33;m", "\033[0m"},
}
)

// List all available clusters a user has previously authenticated to
// Returns error
func List() error {
var domain string

c, err := GetClusters()
Expand Down Expand Up @@ -82,9 +87,66 @@ func SetCluster(domain string) error {
return c.SetContext()
}

func getClusterSelection() (string, error) {
var domain string
tab.GetUserInput = true

c, err := GetClusters()
if err != nil {
return "", err
}

ctx, err := GetCurrentCluster()
if err != nil {
return "", err
}

contexts := []string{}
for k, v := range c.Contexts {
if v.Domain != "" {
domain = v.Domain
} else {
domain = strings.Replace(k, "_", ".", -1)
}

contexts = append(contexts, domain)

colorRow := false
if domain == ctx.Domain {
colorRow = true
}

tab.AddRow([]string{domain}, colorRow)
}

tab.Print()

in := input.InputText("\n> ")
i, err := strconv.ParseInt(
in,
10,
64,
)

if err != nil {
return "", errors.Wrapf(err, "cannot parse %s to int", in)
}

return contexts[i-1], nil

}

// SwitchCluster is a thin wrapper around the switch cluster receiver
// Returns error
func Switch(domain string) error {
if len(domain) == 0 {
d, err := getClusterSelection()
if err != nil {
return err
}
domain = d
}

c := config.Context{Domain: domain}
err := c.SwitchContext()
if err != nil {
Expand Down
9 changes: 7 additions & 2 deletions cmd/cluster.go
Expand Up @@ -27,7 +27,7 @@ var (
Short: "Switch to a different cluster context",
Long: "Switch to a different cluster context",
RunE: clusterSwitch,
Args: cobra.ExactArgs(1),
Args: cobra.MaximumNArgs(1),
}
)

Expand All @@ -50,5 +50,10 @@ func clusterSwitch(cmd *cobra.Command, args []string) error {
// Silence Usage as we have now validated command input
cmd.SilenceUsage = true

return cluster.Switch(args[0])
d := ""
if len(args) == 1 {
d = args[0]
}

return cluster.Switch(d)
}

0 comments on commit e3777db

Please sign in to comment.