-
Notifications
You must be signed in to change notification settings - Fork 2.1k
Expand file tree
/
Copy pathremove.go
More file actions
87 lines (77 loc) · 2.46 KB
/
remove.go
File metadata and controls
87 lines (77 loc) · 2.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package context
import (
"errors"
"fmt"
"os"
"github.com/docker/cli/cli"
"github.com/docker/cli/cli/command"
"github.com/spf13/cobra"
)
// removeOptions are the options used to remove contexts.
type removeOptions struct {
force bool
}
func newRemoveCommand(dockerCLI command.Cli) *cobra.Command {
var opts removeOptions
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 {
return runRemove(dockerCLI, opts, args)
},
ValidArgsFunction: completeContextNames(dockerCLI, -1, false),
DisableFlagsInUseLine: true,
}
cmd.Flags().BoolVarP(&opts.force, "force", "f", false, "Force the removal of a context in use")
return cmd
}
// runRemove removes one or more contexts.
func runRemove(dockerCLI command.Cli, opts removeOptions, names []string) error {
var errs []error
currentCtx := dockerCLI.CurrentContext()
for _, name := range names {
if name == "default" {
errs = append(errs, errors.New(`context "default" cannot be removed`))
} else if err := doRemove(dockerCLI, name, name == currentCtx, opts.force); err != nil {
errs = append(errs, err)
} else {
_, _ = fmt.Fprintln(dockerCLI.Out(), name)
}
}
return errors.Join(errs...)
}
func doRemove(dockerCli command.Cli, name string, isCurrent, force bool) error {
if isCurrent {
if !force {
return fmt.Errorf("context %q is in use, set -f flag to force remove", name)
}
// fallback to DOCKER_HOST
cfg := dockerCli.ConfigFile()
cfg.CurrentContext = ""
if err := cfg.Save(); err != nil {
return err
}
}
if !force {
// TODO(thaJeztah): instead of checking before removing, can we make ContextStore().Remove() return a proper errdef and ignore "not found" errors?
if err := checkContextExists(dockerCli, name); err != nil {
return err
}
}
return dockerCli.ContextStore().Remove(name)
}
// checkContextExists returns an error if the context directory does not exist.
func checkContextExists(dockerCli command.Cli, name string) error {
contextDir := dockerCli.ContextStore().GetStorageInfo(name).MetadataPath
_, err := os.Stat(contextDir)
if os.IsNotExist(err) {
return notFoundErr{fmt.Errorf("context %q does not exist", name)}
}
// Ignore other errors; if relevant, they will produce an error when
// performing the actual delete.
return nil
}
type notFoundErr struct{ error }
func (notFoundErr) NotFound() {}