list.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /*
  2. Copyright 2020 Docker, Inc.
  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. "text/tabwriter"
  20. "github.com/spf13/cobra"
  21. "github.com/docker/compose-cli/api/client"
  22. "github.com/docker/compose-cli/api/volumes"
  23. )
  24. func listVolume() *cobra.Command {
  25. cmd := &cobra.Command{
  26. Use: "ls",
  27. Short: "list available volumes in context.",
  28. Args: cobra.ExactArgs(0),
  29. RunE: func(cmd *cobra.Command, args []string) error {
  30. c, err := client.New(cmd.Context())
  31. if err != nil {
  32. return err
  33. }
  34. vols, err := c.VolumeService().List(cmd.Context())
  35. if err != nil {
  36. return err
  37. }
  38. printList(os.Stdout, vols)
  39. return nil
  40. },
  41. }
  42. return cmd
  43. }
  44. func printList(out io.Writer, volumes []volumes.Volume) {
  45. printSection(out, func(w io.Writer) {
  46. for _, vol := range volumes {
  47. _, _ = fmt.Fprintf(w, "%s\t%s\n", vol.ID, vol.Description)
  48. }
  49. }, "ID", "DESCRIPTION")
  50. }
  51. func printSection(out io.Writer, printer func(io.Writer), headers ...string) {
  52. w := tabwriter.NewWriter(out, 20, 1, 3, ' ', 0)
  53. _, _ = fmt.Fprintln(w, strings.Join(headers, "\t"))
  54. printer(w)
  55. _ = w.Flush()
  56. }