rm.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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 cmd
  14. import (
  15. "context"
  16. "fmt"
  17. "github.com/pkg/errors"
  18. "github.com/spf13/cobra"
  19. "github.com/docker/api/client"
  20. "github.com/docker/api/multierror"
  21. )
  22. type rmOpts struct {
  23. force bool
  24. }
  25. // RmCommand deletes containers
  26. func RmCommand() *cobra.Command {
  27. var opts rmOpts
  28. cmd := &cobra.Command{
  29. Use: "rm",
  30. Aliases: []string{"delete"},
  31. Short: "Remove containers",
  32. Args: cobra.MinimumNArgs(1),
  33. RunE: func(cmd *cobra.Command, args []string) error {
  34. return runRm(cmd.Context(), args, opts)
  35. },
  36. }
  37. cmd.Flags().BoolVarP(&opts.force, "force", "f", false, "Force removal")
  38. return cmd
  39. }
  40. func runRm(ctx context.Context, args []string, opts rmOpts) error {
  41. c, err := client.New(ctx)
  42. if err != nil {
  43. return errors.Wrap(err, "cannot connect to backend")
  44. }
  45. var errs *multierror.Error
  46. for _, id := range args {
  47. err := c.ContainerService().Delete(ctx, id, opts.force)
  48. if err != nil {
  49. errs = multierror.Append(errs, err)
  50. continue
  51. }
  52. fmt.Println(id)
  53. }
  54. return errs.ErrorOrNil()
  55. }