2018-11-09 09:10:41 -05:00
|
|
|
package context
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
2019-04-09 11:12:12 -04:00
|
|
|
"os"
|
2018-11-09 09:10:41 -05:00
|
|
|
|
|
|
|
"github.com/docker/cli/cli/command"
|
2020-09-24 10:24:24 -04:00
|
|
|
"github.com/docker/cli/cli/context/store"
|
2022-03-24 19:15:14 -04:00
|
|
|
"github.com/docker/docker/client"
|
2018-11-09 09:10:41 -05:00
|
|
|
"github.com/spf13/cobra"
|
|
|
|
)
|
|
|
|
|
|
|
|
func newUseCommand(dockerCli command.Cli) *cobra.Command {
|
|
|
|
cmd := &cobra.Command{
|
|
|
|
Use: "use CONTEXT",
|
|
|
|
Short: "Set the current docker context",
|
|
|
|
Args: cobra.ExactArgs(1),
|
|
|
|
RunE: func(cmd *cobra.Command, args []string) error {
|
|
|
|
name := args[0]
|
2019-01-21 03:37:20 -05:00
|
|
|
return RunUse(dockerCli, name)
|
2018-11-09 09:10:41 -05:00
|
|
|
},
|
|
|
|
}
|
|
|
|
return cmd
|
|
|
|
}
|
2019-01-21 03:37:20 -05:00
|
|
|
|
|
|
|
// RunUse set the current Docker context
|
|
|
|
func RunUse(dockerCli command.Cli, name string) error {
|
2020-09-24 10:24:24 -04:00
|
|
|
if err := store.ValidateContextName(name); err != nil && name != "default" {
|
2019-01-21 03:37:20 -05:00
|
|
|
return err
|
|
|
|
}
|
2019-04-18 09:12:30 -04:00
|
|
|
if _, err := dockerCli.ContextStore().GetMetadata(name); err != nil && name != "default" {
|
2019-01-21 03:37:20 -05:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
configValue := name
|
|
|
|
if configValue == "default" {
|
|
|
|
configValue = ""
|
|
|
|
}
|
|
|
|
dockerConfig := dockerCli.ConfigFile()
|
|
|
|
dockerConfig.CurrentContext = configValue
|
|
|
|
if err := dockerConfig.Save(); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
fmt.Fprintln(dockerCli.Out(), name)
|
|
|
|
fmt.Fprintf(dockerCli.Err(), "Current context is now %q\n", name)
|
2022-03-24 19:15:14 -04:00
|
|
|
if os.Getenv(client.EnvOverrideHost) != "" {
|
|
|
|
fmt.Fprintf(dockerCli.Err(), "Warning: %[1]s environment variable overrides the active context. "+
|
|
|
|
"To use %[2]q, either set the global --context flag, or unset %[1]s environment variable.\n", client.EnvOverrideHost, name)
|
2019-04-09 11:12:12 -04:00
|
|
|
}
|
2019-01-21 03:37:20 -05:00
|
|
|
return nil
|
|
|
|
}
|