github.com/ali-iotechsys/cli@v20.10.0+incompatible/cli/command/network/list.go (about) 1 package network 2 3 import ( 4 "context" 5 "sort" 6 7 "github.com/docker/cli/cli" 8 "github.com/docker/cli/cli/command" 9 "github.com/docker/cli/cli/command/formatter" 10 "github.com/docker/cli/opts" 11 "github.com/docker/docker/api/types" 12 "github.com/fvbommel/sortorder" 13 "github.com/spf13/cobra" 14 ) 15 16 type listOptions struct { 17 quiet bool 18 noTrunc bool 19 format string 20 filter opts.FilterOpt 21 } 22 23 func newListCommand(dockerCli command.Cli) *cobra.Command { 24 options := listOptions{filter: opts.NewFilterOpt()} 25 26 cmd := &cobra.Command{ 27 Use: "ls [OPTIONS]", 28 Aliases: []string{"list"}, 29 Short: "List networks", 30 Args: cli.NoArgs, 31 RunE: func(cmd *cobra.Command, args []string) error { 32 return runList(dockerCli, options) 33 }, 34 } 35 36 flags := cmd.Flags() 37 flags.BoolVarP(&options.quiet, "quiet", "q", false, "Only display network IDs") 38 flags.BoolVar(&options.noTrunc, "no-trunc", false, "Do not truncate the output") 39 flags.StringVar(&options.format, "format", "", "Pretty-print networks using a Go template") 40 flags.VarP(&options.filter, "filter", "f", "Provide filter values (e.g. 'driver=bridge')") 41 42 return cmd 43 } 44 45 func runList(dockerCli command.Cli, options listOptions) error { 46 client := dockerCli.Client() 47 listOptions := types.NetworkListOptions{Filters: options.filter.Value()} 48 networkResources, err := client.NetworkList(context.Background(), listOptions) 49 if err != nil { 50 return err 51 } 52 53 format := options.format 54 if len(format) == 0 { 55 if len(dockerCli.ConfigFile().NetworksFormat) > 0 && !options.quiet { 56 format = dockerCli.ConfigFile().NetworksFormat 57 } else { 58 format = formatter.TableFormatKey 59 } 60 } 61 62 sort.Slice(networkResources, func(i, j int) bool { 63 return sortorder.NaturalLess(networkResources[i].Name, networkResources[j].Name) 64 }) 65 66 networksCtx := formatter.Context{ 67 Output: dockerCli.Out(), 68 Format: NewFormat(format, options.quiet), 69 Trunc: !options.noTrunc, 70 } 71 return FormatWrite(networksCtx, networkResources) 72 }