list.go 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. package volume
  2. import (
  3. "sort"
  4. "golang.org/x/net/context"
  5. "github.com/docker/docker/api/types"
  6. "github.com/docker/docker/cli"
  7. "github.com/docker/docker/cli/command"
  8. "github.com/docker/docker/cli/command/formatter"
  9. "github.com/docker/docker/opts"
  10. "github.com/spf13/cobra"
  11. )
  12. type byVolumeName []*types.Volume
  13. func (r byVolumeName) Len() int { return len(r) }
  14. func (r byVolumeName) Swap(i, j int) { r[i], r[j] = r[j], r[i] }
  15. func (r byVolumeName) Less(i, j int) bool {
  16. return r[i].Name < r[j].Name
  17. }
  18. type listOptions struct {
  19. quiet bool
  20. format string
  21. filter opts.FilterOpt
  22. }
  23. func newListCommand(dockerCli *command.DockerCli) *cobra.Command {
  24. opts := listOptions{filter: opts.NewFilterOpt()}
  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.StringVar(&opts.format, "format", "", "Pretty-print volumes using a Go template")
  38. flags.VarP(&opts.filter, "filter", "f", "Provide filter values (e.g. 'dangling=true')")
  39. return cmd
  40. }
  41. func runList(dockerCli *command.DockerCli, opts listOptions) error {
  42. client := dockerCli.Client()
  43. volumes, err := client.VolumeList(context.Background(), opts.filter.Value())
  44. if err != nil {
  45. return err
  46. }
  47. format := opts.format
  48. if len(format) == 0 {
  49. if len(dockerCli.ConfigFile().VolumesFormat) > 0 && !opts.quiet {
  50. format = dockerCli.ConfigFile().VolumesFormat
  51. } else {
  52. format = formatter.TableFormatKey
  53. }
  54. }
  55. sort.Sort(byVolumeName(volumes.Volumes))
  56. volumeCtx := formatter.Context{
  57. Output: dockerCli.Out(),
  58. Format: formatter.NewVolumeFormat(format, opts.quiet),
  59. }
  60. return formatter.VolumeWrite(volumeCtx, volumes.Volumes)
  61. }
  62. var listDescription = `
  63. Lists all the volumes Docker manages. You can filter using the **-f** or
  64. **--filter** flag. The filtering format is a **key=value** pair. To specify
  65. more than one filter, pass multiple flags (for example,
  66. **--filter "foo=bar" --filter "bif=baz"**)
  67. The currently supported filters are:
  68. * **dangling** (boolean - **true** or **false**, **1** or **0**)
  69. * **driver** (a volume driver's name)
  70. * **label** (**label=<key>** or **label=<key>=<value>**)
  71. * **name** (a volume's name)
  72. `