remove.go 2.5 KB

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