github.com/kunnos/engine@v1.13.1/cli/command/network/list.go (about)

     1  package network
     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 byNetworkName []types.NetworkResource
    17  
    18  func (r byNetworkName) Len() int           { return len(r) }
    19  func (r byNetworkName) Swap(i, j int)      { r[i], r[j] = r[j], r[i] }
    20  func (r byNetworkName) Less(i, j int) bool { return r[i].Name < r[j].Name }
    21  
    22  type listOptions struct {
    23  	quiet   bool
    24  	noTrunc bool
    25  	format  string
    26  	filter  opts.FilterOpt
    27  }
    28  
    29  func newListCommand(dockerCli *command.DockerCli) *cobra.Command {
    30  	opts := listOptions{filter: opts.NewFilterOpt()}
    31  
    32  	cmd := &cobra.Command{
    33  		Use:     "ls [OPTIONS]",
    34  		Aliases: []string{"list"},
    35  		Short:   "List networks",
    36  		Args:    cli.NoArgs,
    37  		RunE: func(cmd *cobra.Command, args []string) error {
    38  			return runList(dockerCli, opts)
    39  		},
    40  	}
    41  
    42  	flags := cmd.Flags()
    43  	flags.BoolVarP(&opts.quiet, "quiet", "q", false, "Only display network IDs")
    44  	flags.BoolVar(&opts.noTrunc, "no-trunc", false, "Do not truncate the output")
    45  	flags.StringVar(&opts.format, "format", "", "Pretty-print networks using a Go template")
    46  	flags.VarP(&opts.filter, "filter", "f", "Provide filter values (e.g. 'driver=bridge')")
    47  
    48  	return cmd
    49  }
    50  
    51  func runList(dockerCli *command.DockerCli, opts listOptions) error {
    52  	client := dockerCli.Client()
    53  	options := types.NetworkListOptions{Filters: opts.filter.Value()}
    54  	networkResources, err := client.NetworkList(context.Background(), options)
    55  	if err != nil {
    56  		return err
    57  	}
    58  
    59  	format := opts.format
    60  	if len(format) == 0 {
    61  		if len(dockerCli.ConfigFile().NetworksFormat) > 0 && !opts.quiet {
    62  			format = dockerCli.ConfigFile().NetworksFormat
    63  		} else {
    64  			format = formatter.TableFormatKey
    65  		}
    66  	}
    67  
    68  	sort.Sort(byNetworkName(networkResources))
    69  
    70  	networksCtx := formatter.Context{
    71  		Output: dockerCli.Out(),
    72  		Format: formatter.NewNetworkFormat(format, opts.quiet),
    73  		Trunc:  !opts.noTrunc,
    74  	}
    75  	return formatter.NetworkWrite(networksCtx, networkResources)
    76  }