list.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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 (i.e. 'dangling=true')")
  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. f := opts.format
  48. if len(f) == 0 {
  49. if len(dockerCli.ConfigFile().NetworksFormat) > 0 && !opts.quiet {
  50. f = dockerCli.ConfigFile().NetworksFormat
  51. } else {
  52. f = "table"
  53. }
  54. }
  55. sort.Sort(byNetworkName(networkResources))
  56. networksCtx := formatter.NetworkContext{
  57. Context: formatter.Context{
  58. Output: dockerCli.Out(),
  59. Format: f,
  60. Quiet: opts.quiet,
  61. Trunc: !opts.noTrunc,
  62. },
  63. Networks: networkResources,
  64. }
  65. networksCtx.Write()
  66. return nil
  67. }