Add context use command

Signed-off-by: Christopher Crone <christopher.crone@docker.com>
This commit is contained in:
Christopher Crone 2020-05-14 10:00:02 +02:00
parent c92a9b12d9
commit 8720a62c37

View File

@ -34,8 +34,10 @@ import (
"text/tabwriter" "text/tabwriter"
"github.com/hashicorp/go-multierror" "github.com/hashicorp/go-multierror"
"github.com/pkg/errors"
"github.com/spf13/cobra" "github.com/spf13/cobra"
cliconfig "github.com/docker/api/cli/config"
"github.com/docker/api/context/store" "github.com/docker/api/context/store"
) )
@ -50,6 +52,7 @@ func ContextCommand() *cobra.Command {
createCommand(), createCommand(),
listCommand(), listCommand(),
removeCommand(), removeCommand(),
useCommand(),
) )
return cmd return cmd
@ -106,6 +109,21 @@ func removeCommand() *cobra.Command {
} }
} }
func useCommand() *cobra.Command {
return &cobra.Command{
Use: "use CONTEXT",
Short: "Set the default context",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
config := cmd.Flag(cliconfig.ConfigFlagName)
if config == nil || config.Value.String() == "" {
panic(errors.New("no value for config directory"))
}
return runUse(cmd.Context(), config.Value.String(), args[0])
},
}
}
func runCreate(ctx context.Context, opts createOpts, name string, contextType string) error { func runCreate(ctx context.Context, opts createOpts, name string, contextType string) error {
switch contextType { switch contextType {
case "aci": case "aci":
@ -162,3 +180,18 @@ func runRemove(ctx context.Context, args []string) error {
} }
return errs.ErrorOrNil() return errs.ErrorOrNil()
} }
func runUse(ctx context.Context, configDir string, name string) error {
s := store.ContextStore(ctx)
// Match behavior of existing CLI
if name != store.DefaultContextName {
if _, err := s.Get(name, nil); err != nil {
return err
}
}
if err := cliconfig.WriteCurrentContext(configDir, name); err != nil {
return err
}
fmt.Println(name)
return nil
}