volumes.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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. "fmt"
  17. "slices"
  18. "github.com/docker/cli/cli/command"
  19. "github.com/docker/cli/cli/command/formatter"
  20. "github.com/docker/cli/cli/flags"
  21. "github.com/docker/compose/v2/pkg/api"
  22. "github.com/spf13/cobra"
  23. )
  24. type volumesOptions struct {
  25. *ProjectOptions
  26. Quiet bool
  27. Format string
  28. }
  29. func volumesCommand(p *ProjectOptions, dockerCli command.Cli, backend api.Service) *cobra.Command {
  30. options := volumesOptions{
  31. ProjectOptions: p,
  32. }
  33. cmd := &cobra.Command{
  34. Use: "volumes [OPTIONS] [SERVICE...]",
  35. Short: "List volumes",
  36. RunE: Adapt(func(ctx context.Context, args []string) error {
  37. return runVol(ctx, dockerCli, backend, args, options)
  38. }),
  39. ValidArgsFunction: completeServiceNames(dockerCli, p),
  40. }
  41. cmd.Flags().BoolVarP(&options.Quiet, "quiet", "q", false, "Only display volume names")
  42. cmd.Flags().StringVar(&options.Format, "format", "table", flags.FormatHelp)
  43. return cmd
  44. }
  45. func runVol(ctx context.Context, dockerCli command.Cli, backend api.Service, services []string, options volumesOptions) error {
  46. project, name, err := options.projectOrName(ctx, dockerCli, services...)
  47. if err != nil {
  48. return err
  49. }
  50. if project != nil {
  51. names := project.ServiceNames()
  52. for _, service := range services {
  53. if !slices.Contains(names, service) {
  54. return fmt.Errorf("no such service: %s", service)
  55. }
  56. }
  57. }
  58. volumes, err := backend.Volumes(ctx, name, api.VolumesOptions{
  59. Services: services,
  60. })
  61. if err != nil {
  62. return err
  63. }
  64. if options.Quiet {
  65. for _, v := range volumes {
  66. _, _ = fmt.Fprintln(dockerCli.Out(), v.Name)
  67. }
  68. return nil
  69. }
  70. volumeCtx := formatter.Context{
  71. Output: dockerCli.Out(),
  72. Format: formatter.NewVolumeFormat(options.Format, options.Quiet),
  73. }
  74. return formatter.VolumeWrite(volumeCtx, volumes)
  75. }