1
0

rm.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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/hashicorp/go-multierror"
  18. "github.com/pkg/errors"
  19. "github.com/spf13/cobra"
  20. "github.com/docker/compose-cli/api/client"
  21. "github.com/docker/compose-cli/api/containers"
  22. "github.com/docker/compose-cli/cli/formatter"
  23. "github.com/docker/compose-cli/errdefs"
  24. )
  25. type rmOpts struct {
  26. force bool
  27. }
  28. // RmCommand deletes containers
  29. func RmCommand() *cobra.Command {
  30. var opts rmOpts
  31. cmd := &cobra.Command{
  32. Use: "rm",
  33. Short: "Remove containers",
  34. Args: cobra.MinimumNArgs(1),
  35. RunE: func(cmd *cobra.Command, args []string) error {
  36. return runRm(cmd.Context(), args, opts)
  37. },
  38. }
  39. cmd.Flags().BoolVarP(&opts.force, "force", "f", false, "Force removal")
  40. return cmd
  41. }
  42. func runRm(ctx context.Context, args []string, opts rmOpts) error {
  43. c, err := client.New(ctx)
  44. if err != nil {
  45. return errors.Wrap(err, "cannot connect to backend")
  46. }
  47. var errs *multierror.Error
  48. for _, id := range args {
  49. err := c.ContainerService().Delete(ctx, id, containers.DeleteRequest{
  50. Force: opts.force,
  51. })
  52. if err != nil {
  53. if errdefs.IsForbiddenError(err) {
  54. errs = multierror.Append(errs, fmt.Errorf("you cannot remove a running container %s. Stop the container before attempting removal or force remove", id))
  55. } else if errdefs.IsNotFoundError(err) {
  56. errs = multierror.Append(errs, fmt.Errorf("container %s not found", id))
  57. } else {
  58. errs = multierror.Append(errs, err)
  59. }
  60. continue
  61. }
  62. fmt.Println(id)
  63. }
  64. formatter.SetMultiErrorFormat(errs)
  65. return errs.ErrorOrNil()
  66. }