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