github.com/justincormack/cli@v0.0.0-20201215022714-831ebeae9675/cli/command/context/remove.go (about) 1 package context 2 3 import ( 4 "errors" 5 "fmt" 6 "strings" 7 8 "github.com/docker/cli/cli" 9 "github.com/docker/cli/cli/command" 10 "github.com/spf13/cobra" 11 ) 12 13 // RemoveOptions are the options used to remove contexts 14 type RemoveOptions struct { 15 Force bool 16 } 17 18 func newRemoveCommand(dockerCli command.Cli) *cobra.Command { 19 var opts RemoveOptions 20 cmd := &cobra.Command{ 21 Use: "rm CONTEXT [CONTEXT...]", 22 Aliases: []string{"remove"}, 23 Short: "Remove one or more contexts", 24 Args: cli.RequiresMinArgs(1), 25 RunE: func(cmd *cobra.Command, args []string) error { 26 return RunRemove(dockerCli, opts, args) 27 }, 28 } 29 cmd.Flags().BoolVarP(&opts.Force, "force", "f", false, "Force the removal of a context in use") 30 return cmd 31 } 32 33 // RunRemove removes one or more contexts 34 func RunRemove(dockerCli command.Cli, opts RemoveOptions, names []string) error { 35 var errs []string 36 currentCtx := dockerCli.CurrentContext() 37 for _, name := range names { 38 if name == "default" { 39 errs = append(errs, `default: context "default" cannot be removed`) 40 } else if err := doRemove(dockerCli, name, name == currentCtx, opts.Force); err != nil { 41 errs = append(errs, fmt.Sprintf("%s: %s", name, err)) 42 } else { 43 fmt.Fprintln(dockerCli.Out(), name) 44 } 45 } 46 if len(errs) > 0 { 47 return errors.New(strings.Join(errs, "\n")) 48 } 49 return nil 50 } 51 52 func doRemove(dockerCli command.Cli, name string, isCurrent, force bool) error { 53 if _, err := dockerCli.ContextStore().GetMetadata(name); err != nil { 54 return err 55 } 56 if isCurrent { 57 if !force { 58 return errors.New("context is in use, set -f flag to force remove") 59 } 60 // fallback to DOCKER_HOST 61 cfg := dockerCli.ConfigFile() 62 cfg.CurrentContext = "" 63 if err := cfg.Save(); err != nil { 64 return err 65 } 66 } 67 return dockerCli.ContextStore().Remove(name) 68 }