github.com/khulnasoft/cli@v0.0.0-20240402070845-01bcad7beefa/cli/command/context/use.go (about) 1 package context 2 3 import ( 4 "fmt" 5 "os" 6 7 "github.com/docker/docker/client" 8 "github.com/khulnasoft/cli/cli/command" 9 "github.com/khulnasoft/cli/cli/context/store" 10 "github.com/spf13/cobra" 11 ) 12 13 func newUseCommand(dockerCli command.Cli) *cobra.Command { 14 cmd := &cobra.Command{ 15 Use: "use CONTEXT", 16 Short: "Set the current docker context", 17 Args: cobra.ExactArgs(1), 18 RunE: func(cmd *cobra.Command, args []string) error { 19 name := args[0] 20 return RunUse(dockerCli, name) 21 }, 22 } 23 return cmd 24 } 25 26 // RunUse set the current Docker context 27 func RunUse(dockerCli command.Cli, name string) error { 28 // configValue uses an empty string for "default" 29 var configValue string 30 if name != command.DefaultContextName { 31 if err := store.ValidateContextName(name); err != nil { 32 return err 33 } 34 if _, err := dockerCli.ContextStore().GetMetadata(name); err != nil { 35 return err 36 } 37 configValue = name 38 } 39 dockerConfig := dockerCli.ConfigFile() 40 // Avoid updating the config-file if nothing changed. This also prevents 41 // creating the file and config-directory if the default is used and 42 // no config-file existed yet. 43 if dockerConfig.CurrentContext != configValue { 44 dockerConfig.CurrentContext = configValue 45 if err := dockerConfig.Save(); err != nil { 46 return err 47 } 48 } 49 fmt.Fprintln(dockerCli.Out(), name) 50 fmt.Fprintf(dockerCli.Err(), "Current context is now %q\n", name) 51 if name != command.DefaultContextName && os.Getenv(client.EnvOverrideHost) != "" { 52 fmt.Fprintf(dockerCli.Err(), "Warning: %[1]s environment variable overrides the active context. "+ 53 "To use %[2]q, either set the global --context flag, or unset %[1]s environment variable.\n", client.EnvOverrideHost, name) 54 } 55 return nil 56 }