remove.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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-cli/api/client"
  17. "github.com/docker/compose-cli/api/compose"
  18. "github.com/docker/compose-cli/api/progress"
  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) *cobra.Command {
  28. opts := removeOptions{
  29. projectOptions: p,
  30. }
  31. cmd := &cobra.Command{
  32. Use: "rm [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: func(cmd *cobra.Command, args []string) error {
  39. return runRemove(cmd.Context(), opts, args)
  40. },
  41. }
  42. f := cmd.Flags()
  43. f.BoolVarP(&opts.force, "force", "f", false, "Don't ask to confirm removal")
  44. f.BoolVarP(&opts.stop, "stop", "s", false, "Stop the containers, if required, before removing")
  45. f.BoolVarP(&opts.volumes, "volumes", "v", false, "Remove any anonymous volumes attached to containers")
  46. return cmd
  47. }
  48. func runRemove(ctx context.Context, opts removeOptions, services []string) error {
  49. c, err := client.NewWithDefaultLocalBackend(ctx)
  50. if err != nil {
  51. return err
  52. }
  53. project, err := opts.toProject(services)
  54. if err != nil {
  55. return err
  56. }
  57. _, err = progress.Run(ctx, func(ctx context.Context) (string, error) {
  58. if opts.stop {
  59. err := c.ComposeService().Stop(ctx, project)
  60. if err != nil {
  61. return "", err
  62. }
  63. }
  64. return "", c.ComposeService().Remove(ctx, project, compose.RemoveOptions{
  65. Volumes: opts.volumes,
  66. Force: opts.force,
  67. })
  68. })
  69. return err
  70. }