@@ -29,35 +29,64 @@ package context
29
29
30
30
import (
31
31
"context"
32
+ "errors"
32
33
"fmt"
33
34
34
- "github.com/spf13/cobra"
35
-
35
+ apicontext "github.com/docker/api/context"
36
36
"github.com/docker/api/context/store"
37
37
"github.com/docker/api/multierror"
38
+ "github.com/spf13/cobra"
38
39
)
39
40
41
+ type removeOpts struct {
42
+ force bool
43
+ }
44
+
40
45
func removeCommand () * cobra.Command {
41
- return & cobra.Command {
46
+ var opts removeOpts
47
+ cmd := & cobra.Command {
42
48
Use : "rm CONTEXT [CONTEXT...]" ,
43
49
Short : "Remove one or more contexts" ,
44
50
Aliases : []string {"remove" },
45
51
Args : cobra .MinimumNArgs (1 ),
46
52
RunE : func (cmd * cobra.Command , args []string ) error {
47
- return runRemove (cmd .Context (), args )
53
+ return runRemove (cmd .Context (), args , opts . force )
48
54
},
49
55
}
56
+ cmd .Flags ().BoolVarP (& opts .force , "force" , "f" , false , "force removing current context" )
57
+
58
+ return cmd
50
59
}
51
60
52
- func runRemove (ctx context.Context , args []string ) error {
61
+ func runRemove (ctx context.Context , args []string , force bool ) error {
62
+ currentContext := apicontext .CurrentContext (ctx )
53
63
s := store .ContextStore (ctx )
64
+
54
65
var errs * multierror.Error
55
- for _ , n := range args {
56
- if err := s .Remove (n ); err != nil {
57
- errs = multierror .Append (errs , err )
66
+ for _ , contextName := range args {
67
+ if currentContext == contextName {
68
+ if force {
69
+ err := runUse (ctx , "default" )
70
+ if err != nil {
71
+ errs = multierror .Append (errs , errors .New ("cannot delete current context" ))
72
+ } else {
73
+ errs = removeContext (s , contextName , errs )
74
+ }
75
+ } else {
76
+ errs = multierror .Append (errs , errors .New ("cannot delete current context" ))
77
+ }
58
78
} else {
59
- fmt . Println ( n )
79
+ errs = removeContext ( s , contextName , errs )
60
80
}
61
81
}
62
82
return errs .ErrorOrNil ()
63
83
}
84
+
85
+ func removeContext (s store.Store , n string , errs * multierror.Error ) * multierror.Error {
86
+ if err := s .Remove (n ); err != nil {
87
+ errs = multierror .Append (errs , err )
88
+ } else {
89
+ fmt .Println (n )
90
+ }
91
+ return errs
92
+ }
0 commit comments