rm.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /*
  2. Copyright 2020 Docker, Inc.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package context
  14. import (
  15. "context"
  16. "errors"
  17. "fmt"
  18. "github.com/spf13/cobra"
  19. apicontext "github.com/docker/api/context"
  20. "github.com/docker/api/context/store"
  21. "github.com/docker/api/multierror"
  22. )
  23. type removeOpts struct {
  24. force bool
  25. }
  26. func removeCommand() *cobra.Command {
  27. var opts removeOpts
  28. cmd := &cobra.Command{
  29. Use: "rm CONTEXT [CONTEXT...]",
  30. Short: "Remove one or more contexts",
  31. Aliases: []string{"remove"},
  32. Args: cobra.MinimumNArgs(1),
  33. RunE: func(cmd *cobra.Command, args []string) error {
  34. return runRemove(cmd.Context(), args, opts.force)
  35. },
  36. }
  37. cmd.Flags().BoolVarP(&opts.force, "force", "f", false, "force removing current context")
  38. return cmd
  39. }
  40. func runRemove(ctx context.Context, args []string, force bool) error {
  41. currentContext := apicontext.CurrentContext(ctx)
  42. s := store.ContextStore(ctx)
  43. var errs *multierror.Error
  44. for _, contextName := range args {
  45. if currentContext == contextName {
  46. if force {
  47. err := runUse(ctx, "default")
  48. if err != nil {
  49. errs = multierror.Append(errs, errors.New("cannot delete current context"))
  50. } else {
  51. errs = removeContext(s, contextName, errs)
  52. }
  53. } else {
  54. errs = multierror.Append(errs, errors.New("cannot delete current context"))
  55. }
  56. } else {
  57. errs = removeContext(s, contextName, errs)
  58. }
  59. }
  60. return errs.ErrorOrNil()
  61. }
  62. func removeContext(s store.Store, n string, errs *multierror.Error) *multierror.Error {
  63. if err := s.Remove(n); err != nil {
  64. errs = multierror.Append(errs, err)
  65. } else {
  66. fmt.Println(n)
  67. }
  68. return errs
  69. }