remove.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. /*
  2. Copyright 2020 Docker Compose CLI authors
  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 compose
  14. import (
  15. "context"
  16. "fmt"
  17. "strings"
  18. "github.com/docker/compose/v2/pkg/api"
  19. moby "github.com/docker/docker/api/types"
  20. "golang.org/x/sync/errgroup"
  21. "github.com/docker/compose/v2/pkg/progress"
  22. "github.com/docker/compose/v2/pkg/prompt"
  23. )
  24. func (s *composeService) Remove(ctx context.Context, projectName string, options api.RemoveOptions) error {
  25. containers, _, err := s.actualState(ctx, projectName, options.Services)
  26. if err != nil {
  27. return err
  28. }
  29. stoppedContainers := containers.filter(func(c moby.Container) bool {
  30. return c.State != ContainerRunning
  31. })
  32. var names []string
  33. stoppedContainers.forEach(func(c moby.Container) {
  34. names = append(names, getCanonicalContainerName(c))
  35. })
  36. if len(names) == 0 {
  37. fmt.Println("No stopped containers")
  38. return nil
  39. }
  40. msg := fmt.Sprintf("Going to remove %s", strings.Join(names, ", "))
  41. if options.Force {
  42. fmt.Println(msg)
  43. } else {
  44. confirm, err := prompt.User{}.Confirm(msg, false)
  45. if err != nil {
  46. return err
  47. }
  48. if !confirm {
  49. return nil
  50. }
  51. }
  52. return progress.Run(ctx, func(ctx context.Context) error {
  53. return s.remove(ctx, stoppedContainers, options)
  54. })
  55. }
  56. func (s *composeService) remove(ctx context.Context, containers Containers, options api.RemoveOptions) error {
  57. w := progress.ContextWriter(ctx)
  58. eg, ctx := errgroup.WithContext(ctx)
  59. for _, container := range containers {
  60. container := container
  61. eg.Go(func() error {
  62. eventName := getContainerProgressName(container)
  63. w.Event(progress.RemovingEvent(eventName))
  64. err := s.apiClient().ContainerRemove(ctx, container.ID, moby.ContainerRemoveOptions{
  65. RemoveVolumes: options.Volumes,
  66. Force: options.Force,
  67. })
  68. if err == nil {
  69. w.Event(progress.RemovedEvent(eventName))
  70. }
  71. return err
  72. })
  73. }
  74. return eg.Wait()
  75. }