remove.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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. "github.com/docker/compose/v2/pkg/api"
  17. "github.com/spf13/cobra"
  18. )
  19. type removeOptions struct {
  20. *projectOptions
  21. force bool
  22. stop bool
  23. volumes bool
  24. }
  25. func removeCommand(p *projectOptions, backend api.Service) *cobra.Command {
  26. opts := removeOptions{
  27. projectOptions: p,
  28. }
  29. cmd := &cobra.Command{
  30. Use: "rm [SERVICE...]",
  31. Short: "Removes stopped service containers",
  32. Long: `Removes stopped service containers
  33. By default, anonymous volumes attached to containers will not be removed. You
  34. can override this with -v. To list all volumes, use "docker volume ls".
  35. Any data which is not in a volume will be lost.`,
  36. RunE: Adapt(func(ctx context.Context, args []string) error {
  37. return runRemove(ctx, backend, opts, args)
  38. }),
  39. ValidArgsFunction: serviceCompletion(p),
  40. }
  41. f := cmd.Flags()
  42. f.BoolVarP(&opts.force, "force", "f", false, "Don't ask to confirm removal")
  43. f.BoolVarP(&opts.stop, "stop", "s", false, "Stop the containers, if required, before removing")
  44. f.BoolVarP(&opts.volumes, "volumes", "v", false, "Remove any anonymous volumes attached to containers")
  45. f.BoolP("all", "a", false, "Deprecated - no effect")
  46. f.MarkHidden("all") //nolint:errcheck
  47. return cmd
  48. }
  49. func runRemove(ctx context.Context, backend api.Service, opts removeOptions, services []string) error {
  50. project, err := opts.toProjectName()
  51. if err != nil {
  52. return err
  53. }
  54. if opts.stop {
  55. err := backend.Stop(ctx, project, api.StopOptions{
  56. Services: services,
  57. })
  58. if err != nil {
  59. return err
  60. }
  61. }
  62. return backend.Remove(ctx, project, api.RemoveOptions{
  63. Services: services,
  64. Force: opts.force,
  65. Volumes: opts.volumes,
  66. })
  67. }