down.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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/compose-spec/compose-go/types"
  17. "github.com/docker/compose-cli/api/compose"
  18. "github.com/spf13/cobra"
  19. "github.com/docker/compose-cli/api/client"
  20. "github.com/docker/compose-cli/api/progress"
  21. )
  22. type downOptions struct {
  23. *projectOptions
  24. removeOrphans bool
  25. }
  26. func downCommand(p *projectOptions) *cobra.Command {
  27. opts := downOptions{
  28. projectOptions: p,
  29. }
  30. downCmd := &cobra.Command{
  31. Use: "down",
  32. Short: "Stop and remove containers, networks",
  33. RunE: func(cmd *cobra.Command, args []string) error {
  34. return runDown(cmd.Context(), opts)
  35. },
  36. }
  37. flags := downCmd.Flags()
  38. flags.BoolVar(&opts.removeOrphans, "remove-orphans", false, "Remove containers for services not defined in the Compose file.")
  39. return downCmd
  40. }
  41. func runDown(ctx context.Context, opts downOptions) error {
  42. c, err := client.NewWithDefaultLocalBackend(ctx)
  43. if err != nil {
  44. return err
  45. }
  46. _, err = progress.Run(ctx, func(ctx context.Context) (string, error) {
  47. name := opts.ProjectName
  48. var project *types.Project
  49. if opts.ProjectName == "" {
  50. p, err := opts.toProject(nil)
  51. if err != nil {
  52. return "", err
  53. }
  54. project = p
  55. name = p.Name
  56. }
  57. return name, c.ComposeService().Down(ctx, name, compose.DownOptions{
  58. RemoveOrphans: opts.removeOrphans,
  59. Project: project,
  60. })
  61. })
  62. return err
  63. }