list.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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. formatter2 "github.com/docker/compose-cli/cmd/formatter"
  19. "github.com/spf13/cobra"
  20. "github.com/docker/compose-cli/api/client"
  21. "github.com/docker/compose-cli/api/volumes"
  22. )
  23. type listVolumeOpts struct {
  24. format string
  25. quiet bool
  26. }
  27. func listVolume() *cobra.Command {
  28. var opts listVolumeOpts
  29. cmd := &cobra.Command{
  30. Use: "ls",
  31. Short: "list available volumes in context.",
  32. Args: cobra.ExactArgs(0),
  33. RunE: func(cmd *cobra.Command, args []string) error {
  34. c, err := client.New(cmd.Context())
  35. if err != nil {
  36. return err
  37. }
  38. vols, err := c.VolumeService().List(cmd.Context())
  39. if err != nil {
  40. return err
  41. }
  42. if opts.quiet {
  43. for _, v := range vols {
  44. fmt.Println(v.ID)
  45. }
  46. return nil
  47. }
  48. view := viewFromVolumeList(vols)
  49. return formatter2.Print(view, opts.format, os.Stdout, func(w io.Writer) {
  50. for _, vol := range view {
  51. _, _ = fmt.Fprintf(w, "%s\t%s\n", vol.ID, vol.Description)
  52. }
  53. }, "ID", "DESCRIPTION")
  54. },
  55. }
  56. cmd.Flags().StringVar(&opts.format, "format", formatter2.PRETTY, "Format the output. Values: [pretty | json]. (Default: pretty)")
  57. cmd.Flags().BoolVarP(&opts.quiet, "quiet", "q", false, "Only display IDs")
  58. return cmd
  59. }
  60. type volumeView struct {
  61. ID string
  62. Description string
  63. }
  64. func viewFromVolumeList(volumeList []volumes.Volume) []volumeView {
  65. retList := make([]volumeView, len(volumeList))
  66. for i, v := range volumeList {
  67. retList[i] = volumeView{
  68. ID: v.ID,
  69. Description: v.Description,
  70. }
  71. }
  72. return retList
  73. }