list.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. Args: cli.NoArgs,
  30. RunE: func(cmd *cobra.Command, args []string) error {
  31. return runList(dockerCli, opts)
  32. },
  33. }
  34. flags := cmd.Flags()
  35. flags.BoolVarP(&opts.quiet, "quiet", "q", false, "Only display volume names")
  36. flags.StringVar(&opts.format, "format", "", "Pretty-print volumes using a Go template")
  37. flags.VarP(&opts.filter, "filter", "f", "Provide filter values (e.g. 'dangling=true')")
  38. return cmd
  39. }
  40. func runList(dockerCli *command.DockerCli, opts listOptions) error {
  41. client := dockerCli.Client()
  42. volumes, err := client.VolumeList(context.Background(), opts.filter.Value())
  43. if err != nil {
  44. return err
  45. }
  46. format := opts.format
  47. if len(format) == 0 {
  48. if len(dockerCli.ConfigFile().VolumesFormat) > 0 && !opts.quiet {
  49. format = dockerCli.ConfigFile().VolumesFormat
  50. } else {
  51. format = formatter.TableFormatKey
  52. }
  53. }
  54. sort.Sort(byVolumeName(volumes.Volumes))
  55. volumeCtx := formatter.Context{
  56. Output: dockerCli.Out(),
  57. Format: formatter.NewVolumeFormat(format, opts.quiet),
  58. }
  59. return formatter.VolumeWrite(volumeCtx, volumes.Volumes)
  60. }