prune.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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 cmd
  14. import (
  15. "context"
  16. "fmt"
  17. "github.com/pkg/errors"
  18. "github.com/spf13/cobra"
  19. "github.com/docker/compose-cli/api/client"
  20. "github.com/docker/compose-cli/api/resources"
  21. )
  22. type pruneOpts struct {
  23. force bool
  24. dryRun bool
  25. }
  26. // PruneCommand deletes backend resources
  27. func PruneCommand() *cobra.Command {
  28. var opts pruneOpts
  29. cmd := &cobra.Command{
  30. Use: "prune",
  31. Short: "prune existing resources in current context",
  32. Args: cobra.MaximumNArgs(0),
  33. RunE: func(cmd *cobra.Command, args []string) error {
  34. return runPrune(cmd.Context(), opts)
  35. },
  36. }
  37. cmd.Flags().BoolVar(&opts.force, "force", false, "Also prune running containers and Compose applications")
  38. cmd.Flags().BoolVar(&opts.dryRun, "dry-run", false, "List resources to be deleted, but do not delete them")
  39. return cmd
  40. }
  41. func runPrune(ctx context.Context, opts pruneOpts) error {
  42. c, err := client.New(ctx)
  43. if err != nil {
  44. return errors.Wrap(err, "cannot connect to backend")
  45. }
  46. result, err := c.ResourceService().Prune(ctx, resources.PruneRequest{Force: opts.force, DryRun: opts.dryRun})
  47. if opts.dryRun {
  48. fmt.Println("Resources that would be deleted:")
  49. } else {
  50. fmt.Println("Deleted resources:")
  51. }
  52. for _, id := range result.DeletedIDs {
  53. fmt.Println(id)
  54. }
  55. if result.Summary != "" {
  56. fmt.Println(result.Summary)
  57. }
  58. return err
  59. }