github.com/justincormack/cli@v0.0.0-20201215022714-831ebeae9675/cli/command/node/list.go (about)

     1  package node
     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  	format string
    19  	filter opts.FilterOpt
    20  }
    21  
    22  func newListCommand(dockerCli command.Cli) *cobra.Command {
    23  	options := listOptions{filter: opts.NewFilterOpt()}
    24  
    25  	cmd := &cobra.Command{
    26  		Use:     "ls [OPTIONS]",
    27  		Aliases: []string{"list"},
    28  		Short:   "List nodes in the swarm",
    29  		Args:    cli.NoArgs,
    30  		RunE: func(cmd *cobra.Command, args []string) error {
    31  			return runList(dockerCli, options)
    32  		},
    33  	}
    34  	flags := cmd.Flags()
    35  	flags.BoolVarP(&options.quiet, "quiet", "q", false, "Only display IDs")
    36  	flags.StringVar(&options.format, "format", "", "Pretty-print nodes using a Go template")
    37  	flags.VarP(&options.filter, "filter", "f", "Filter output based on conditions provided")
    38  
    39  	return cmd
    40  }
    41  
    42  func runList(dockerCli command.Cli, options listOptions) error {
    43  	client := dockerCli.Client()
    44  	ctx := context.Background()
    45  
    46  	nodes, err := client.NodeList(
    47  		ctx,
    48  		types.NodeListOptions{Filters: options.filter.Value()})
    49  	if err != nil {
    50  		return err
    51  	}
    52  
    53  	info := types.Info{}
    54  	if len(nodes) > 0 && !options.quiet {
    55  		// only non-empty nodes and not quiet, should we call /info api
    56  		info, err = client.Info(ctx)
    57  		if err != nil {
    58  			return err
    59  		}
    60  	}
    61  
    62  	format := options.format
    63  	if len(format) == 0 {
    64  		format = formatter.TableFormatKey
    65  		if len(dockerCli.ConfigFile().NodesFormat) > 0 && !options.quiet {
    66  			format = dockerCli.ConfigFile().NodesFormat
    67  		}
    68  	}
    69  
    70  	nodesCtx := formatter.Context{
    71  		Output: dockerCli.Out(),
    72  		Format: NewFormat(format, options.quiet),
    73  	}
    74  	sort.Slice(nodes, func(i, j int) bool {
    75  		return sortorder.NaturalLess(nodes[i].Description.Hostname, nodes[j].Description.Hostname)
    76  	})
    77  	return FormatWrite(nodesCtx, nodes, info)
    78  }