瀏覽代碼

Do not allow deleting curent context without -f flag

Guillaume Tardif 5 年之前
父節點
當前提交
ddc44d7abe
共有 2 個文件被更改,包括 14 次插入2 次删除
  1. 7 2
      cli/cmd/context/rm.go
  2. 7 0
      tests/e2e/e2e_test.go

+ 7 - 2
cli/cmd/context/rm.go

@@ -29,10 +29,11 @@ package context
 
 import (
 	"context"
+	"errors"
 	"fmt"
 
 	"github.com/spf13/cobra"
-
+	apicontext "github.com/docker/api/context"
 	"github.com/docker/api/context/store"
 	"github.com/docker/api/multierror"
 )
@@ -50,10 +51,14 @@ func removeCommand() *cobra.Command {
 }
 
 func runRemove(ctx context.Context, args []string) error {
+	currentContext := apicontext.CurrentContext(ctx)
 	s := store.ContextStore(ctx)
+
 	var errs *multierror.Error
 	for _, n := range args {
-		if err := s.Remove(n); err != nil {
+		if currentContext == n {
+			errs = multierror.Append(errs, errors.New("cannot delete current context"))
+		} else if err := s.Remove(n); err != nil {
 			errs = multierror.Append(errs, err)
 		} else {
 			fmt.Println(n)

+ 7 - 0
tests/e2e/e2e_test.go

@@ -79,6 +79,13 @@ func (s *E2eSuite) TestContextCreateParseErrorDoesNotDelegateToLegacy() {
 	})
 }
 
+func (s *E2eSuite) TestCannotRemoveCurrentContext() {
+	s.NewDockerCommand("context", "create", "test-context", "--from", "default").ExecOrDie()
+	s.NewDockerCommand("context", "use", "test-context").ExecOrDie()
+	_, err := s.NewDockerCommand("context", "rm", "test-context").Exec()
+	Expect(err.Error()).To(ContainSubstring("cannot delete current context"))
+}
+
 func (s *E2eSuite) TestClassicLoginWithparameters() {
 	output, err := s.NewDockerCommand("login", "-u", "nouser", "-p", "wrongpasword").Exec()
 	Expect(output).To(ContainSubstring("Get https://registry-1.docker.io/v2/: unauthorized: incorrect username or password"))