list.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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 volume
  14. import (
  15. "fmt"
  16. "io"
  17. "os"
  18. "strings"
  19. "github.com/pkg/errors"
  20. "github.com/spf13/cobra"
  21. "github.com/docker/compose-cli/api/client"
  22. "github.com/docker/compose-cli/api/volumes"
  23. "github.com/docker/compose-cli/errdefs"
  24. "github.com/docker/compose-cli/formatter"
  25. )
  26. type listVolumeOpts struct {
  27. format string
  28. }
  29. func listVolume() *cobra.Command {
  30. var opts listVolumeOpts
  31. cmd := &cobra.Command{
  32. Use: "ls",
  33. Short: "list available volumes in context.",
  34. Args: cobra.ExactArgs(0),
  35. RunE: func(cmd *cobra.Command, args []string) error {
  36. c, err := client.New(cmd.Context())
  37. if err != nil {
  38. return err
  39. }
  40. vols, err := c.VolumeService().List(cmd.Context())
  41. if err != nil {
  42. return err
  43. }
  44. return printList(opts.format, os.Stdout, vols)
  45. },
  46. }
  47. cmd.Flags().StringVar(&opts.format, "format", formatter.PRETTY, "Format the output. Values: [pretty | json]. (Default: pretty)")
  48. return cmd
  49. }
  50. func printList(format string, out io.Writer, volumes []volumes.Volume) error {
  51. var err error
  52. switch strings.ToLower(format) {
  53. case formatter.PRETTY, "":
  54. _ = formatter.PrintPrettySection(out, func(w io.Writer) {
  55. for _, vol := range volumes {
  56. _, _ = fmt.Fprintf(w, "%s\t%s\n", vol.ID, vol.Description)
  57. }
  58. }, "ID", "DESCRIPTION")
  59. case formatter.JSON:
  60. outJSON, err := formatter.ToStandardJSON(volumes)
  61. if err != nil {
  62. return err
  63. }
  64. _, _ = fmt.Fprint(out, outJSON)
  65. default:
  66. err = errors.Wrapf(errdefs.ErrParsingFailed, "format value %q could not be parsed", format)
  67. }
  68. return err
  69. }