2018-11-09 09:10:41 -05:00
|
|
|
package context
|
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
|
|
|
"fmt"
|
|
|
|
"strings"
|
|
|
|
|
|
|
|
"github.com/docker/cli/cli"
|
|
|
|
"github.com/docker/cli/cli/command"
|
|
|
|
"github.com/spf13/cobra"
|
|
|
|
)
|
|
|
|
|
2019-01-21 03:37:20 -05:00
|
|
|
// RemoveOptions are the options used to remove contexts
|
|
|
|
type RemoveOptions struct {
|
|
|
|
Force bool
|
2018-11-09 09:10:41 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
func newRemoveCommand(dockerCli command.Cli) *cobra.Command {
|
2019-01-21 03:37:20 -05:00
|
|
|
var opts RemoveOptions
|
2018-11-09 09:10:41 -05:00
|
|
|
cmd := &cobra.Command{
|
|
|
|
Use: "rm CONTEXT [CONTEXT...]",
|
|
|
|
Aliases: []string{"remove"},
|
|
|
|
Short: "Remove one or more contexts",
|
|
|
|
Args: cli.RequiresMinArgs(1),
|
|
|
|
RunE: func(cmd *cobra.Command, args []string) error {
|
2019-01-21 03:37:20 -05:00
|
|
|
return RunRemove(dockerCli, opts, args)
|
2018-11-09 09:10:41 -05:00
|
|
|
},
|
|
|
|
}
|
2019-01-21 03:37:20 -05:00
|
|
|
cmd.Flags().BoolVarP(&opts.Force, "force", "f", false, "Force the removal of a context in use")
|
2018-11-09 09:10:41 -05:00
|
|
|
return cmd
|
|
|
|
}
|
|
|
|
|
2019-01-21 03:37:20 -05:00
|
|
|
// RunRemove removes one or more contexts
|
|
|
|
func RunRemove(dockerCli command.Cli, opts RemoveOptions, names []string) error {
|
2018-11-09 09:10:41 -05:00
|
|
|
var errs []string
|
|
|
|
currentCtx := dockerCli.CurrentContext()
|
|
|
|
for _, name := range names {
|
|
|
|
if name == "default" {
|
|
|
|
errs = append(errs, `default: context "default" cannot be removed`)
|
2019-01-21 03:37:20 -05:00
|
|
|
} else if err := doRemove(dockerCli, name, name == currentCtx, opts.Force); err != nil {
|
2018-11-09 09:10:41 -05:00
|
|
|
errs = append(errs, fmt.Sprintf("%s: %s", name, err))
|
|
|
|
} else {
|
|
|
|
fmt.Fprintln(dockerCli.Out(), name)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if len(errs) > 0 {
|
|
|
|
return errors.New(strings.Join(errs, "\n"))
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func doRemove(dockerCli command.Cli, name string, isCurrent, force bool) error {
|
2019-04-18 09:12:30 -04:00
|
|
|
if _, err := dockerCli.ContextStore().GetMetadata(name); err != nil {
|
2018-11-09 09:10:41 -05:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
if isCurrent {
|
|
|
|
if !force {
|
|
|
|
return errors.New("context is in use, set -f flag to force remove")
|
|
|
|
}
|
|
|
|
// fallback to DOCKER_HOST
|
|
|
|
cfg := dockerCli.ConfigFile()
|
|
|
|
cfg.CurrentContext = ""
|
|
|
|
if err := cfg.Save(); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
2019-04-18 09:12:30 -04:00
|
|
|
return dockerCli.ContextStore().Remove(name)
|
2018-11-09 09:10:41 -05:00
|
|
|
}
|