github.com/flavio/docker@v0.1.3-0.20170117145210-f63d1a6eec47/cli/command/volume/list.go (about)

     1  package volume
     2  
     3  import (
     4  	"sort"
     5  
     6  	"golang.org/x/net/context"
     7  
     8  	"github.com/docker/docker/api/types"
     9  	"github.com/docker/docker/cli"
    10  	"github.com/docker/docker/cli/command"
    11  	"github.com/docker/docker/cli/command/formatter"
    12  	"github.com/docker/docker/opts"
    13  	"github.com/spf13/cobra"
    14  )
    15  
    16  type byVolumeName []*types.Volume
    17  
    18  func (r byVolumeName) Len() int      { return len(r) }
    19  func (r byVolumeName) Swap(i, j int) { r[i], r[j] = r[j], r[i] }
    20  func (r byVolumeName) Less(i, j int) bool {
    21  	return r[i].Name < r[j].Name
    22  }
    23  
    24  type listOptions struct {
    25  	quiet  bool
    26  	format string
    27  	filter opts.FilterOpt
    28  }
    29  
    30  func newListCommand(dockerCli *command.DockerCli) *cobra.Command {
    31  	opts := listOptions{filter: opts.NewFilterOpt()}
    32  
    33  	cmd := &cobra.Command{
    34  		Use:     "ls [OPTIONS]",
    35  		Aliases: []string{"list"},
    36  		Short:   "List volumes",
    37  		Args:    cli.NoArgs,
    38  		RunE: func(cmd *cobra.Command, args []string) error {
    39  			return runList(dockerCli, opts)
    40  		},
    41  	}
    42  
    43  	flags := cmd.Flags()
    44  	flags.BoolVarP(&opts.quiet, "quiet", "q", false, "Only display volume names")
    45  	flags.StringVar(&opts.format, "format", "", "Pretty-print volumes using a Go template")
    46  	flags.VarP(&opts.filter, "filter", "f", "Provide filter values (e.g. 'dangling=true')")
    47  
    48  	return cmd
    49  }
    50  
    51  func runList(dockerCli *command.DockerCli, opts listOptions) error {
    52  	client := dockerCli.Client()
    53  	volumes, err := client.VolumeList(context.Background(), opts.filter.Value())
    54  	if err != nil {
    55  		return err
    56  	}
    57  
    58  	format := opts.format
    59  	if len(format) == 0 {
    60  		if len(dockerCli.ConfigFile().VolumesFormat) > 0 && !opts.quiet {
    61  			format = dockerCli.ConfigFile().VolumesFormat
    62  		} else {
    63  			format = formatter.TableFormatKey
    64  		}
    65  	}
    66  
    67  	sort.Sort(byVolumeName(volumes.Volumes))
    68  
    69  	volumeCtx := formatter.Context{
    70  		Output: dockerCli.Out(),
    71  		Format: formatter.NewVolumeFormat(format, opts.quiet),
    72  	}
    73  	return formatter.VolumeWrite(volumeCtx, volumes.Volumes)
    74  }