list.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. package volume
  2. import (
  3. "fmt"
  4. "sort"
  5. "text/tabwriter"
  6. "golang.org/x/net/context"
  7. "github.com/docker/docker/api/client"
  8. "github.com/docker/docker/cli"
  9. "github.com/docker/engine-api/types"
  10. "github.com/docker/engine-api/types/filters"
  11. "github.com/spf13/cobra"
  12. )
  13. type byVolumeName []*types.Volume
  14. func (r byVolumeName) Len() int { return len(r) }
  15. func (r byVolumeName) Swap(i, j int) { r[i], r[j] = r[j], r[i] }
  16. func (r byVolumeName) Less(i, j int) bool {
  17. return r[i].Name < r[j].Name
  18. }
  19. type listOptions struct {
  20. quiet bool
  21. filter []string
  22. }
  23. func newListCommand(dockerCli *client.DockerCli) *cobra.Command {
  24. var opts listOptions
  25. cmd := &cobra.Command{
  26. Use: "ls [OPTIONS]",
  27. Aliases: []string{"list"},
  28. Short: "List volumes",
  29. Long: listDescription,
  30. Args: cli.NoArgs,
  31. RunE: func(cmd *cobra.Command, args []string) error {
  32. return runList(dockerCli, opts)
  33. },
  34. }
  35. flags := cmd.Flags()
  36. flags.BoolVarP(&opts.quiet, "quiet", "q", false, "Only display volume names")
  37. flags.StringSliceVarP(&opts.filter, "filter", "f", []string{}, "Provide filter values (i.e. 'dangling=true')")
  38. return cmd
  39. }
  40. func runList(dockerCli *client.DockerCli, opts listOptions) error {
  41. client := dockerCli.Client()
  42. volFilterArgs := filters.NewArgs()
  43. for _, f := range opts.filter {
  44. var err error
  45. volFilterArgs, err = filters.ParseFlag(f, volFilterArgs)
  46. if err != nil {
  47. return err
  48. }
  49. }
  50. volumes, err := client.VolumeList(context.Background(), volFilterArgs)
  51. if err != nil {
  52. return err
  53. }
  54. w := tabwriter.NewWriter(dockerCli.Out(), 20, 1, 3, ' ', 0)
  55. if !opts.quiet {
  56. for _, warn := range volumes.Warnings {
  57. fmt.Fprintln(dockerCli.Err(), warn)
  58. }
  59. fmt.Fprintf(w, "DRIVER \tVOLUME NAME")
  60. fmt.Fprintf(w, "\n")
  61. }
  62. sort.Sort(byVolumeName(volumes.Volumes))
  63. for _, vol := range volumes.Volumes {
  64. if opts.quiet {
  65. fmt.Fprintln(w, vol.Name)
  66. continue
  67. }
  68. fmt.Fprintf(w, "%s\t%s\n", vol.Driver, vol.Name)
  69. }
  70. w.Flush()
  71. return nil
  72. }
  73. var listDescription = `
  74. Lists all the volumes Docker knows about. You can filter using the **-f** or
  75. **--filter** flag. The filtering format is a **key=value** pair. To specify
  76. more than one filter, pass multiple flags (for example,
  77. **--filter "foo=bar" --filter "bif=baz"**)
  78. There is a single supported filter **dangling=value** which takes a boolean of
  79. **true** or **false**.
  80. `