list.go 2.1 KB

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