list.go 1.9 KB

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