rm.go 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. package cmd
  2. import (
  3. "context"
  4. "fmt"
  5. "github.com/pkg/errors"
  6. "github.com/spf13/cobra"
  7. "github.com/docker/api/client"
  8. "github.com/docker/api/multierror"
  9. )
  10. type rmOpts struct {
  11. force bool
  12. }
  13. // RmCommand deletes containers
  14. func RmCommand() *cobra.Command {
  15. var opts rmOpts
  16. cmd := &cobra.Command{
  17. Use: "rm",
  18. Aliases: []string{"delete"},
  19. Short: "Remove containers",
  20. Args: cobra.MinimumNArgs(1),
  21. RunE: func(cmd *cobra.Command, args []string) error {
  22. return runRm(cmd.Context(), args, opts)
  23. },
  24. }
  25. cmd.Flags().BoolVarP(&opts.force, "force", "f", false, "Force removal")
  26. return cmd
  27. }
  28. func runRm(ctx context.Context, args []string, opts rmOpts) error {
  29. c, err := client.New(ctx)
  30. if err != nil {
  31. return errors.Wrap(err, "cannot connect to backend")
  32. }
  33. var errs *multierror.Error
  34. for _, id := range args {
  35. err := c.ContainerService().Delete(ctx, id, opts.force)
  36. if err != nil {
  37. errs = multierror.Append(errs, err)
  38. continue
  39. }
  40. fmt.Println(id)
  41. }
  42. return errs.ErrorOrNil()
  43. }