github.com/khulnasoft/cli@v0.0.0-20240402070845-01bcad7beefa/cli/command/node/list.go (about)

     1  package node
     2  
     3  import (
     4  	"context"
     5  	"sort"
     6  
     7  	"github.com/docker/docker/api/types"
     8  	"github.com/docker/docker/api/types/system"
     9  	"github.com/fvbommel/sortorder"
    10  	"github.com/khulnasoft/cli/cli"
    11  	"github.com/khulnasoft/cli/cli/command"
    12  	"github.com/khulnasoft/cli/cli/command/completion"
    13  	"github.com/khulnasoft/cli/cli/command/formatter"
    14  	flagsHelper "github.com/khulnasoft/cli/cli/flags"
    15  	"github.com/khulnasoft/cli/opts"
    16  	"github.com/spf13/cobra"
    17  )
    18  
    19  type listOptions struct {
    20  	quiet  bool
    21  	format string
    22  	filter opts.FilterOpt
    23  }
    24  
    25  func newListCommand(dockerCli command.Cli) *cobra.Command {
    26  	options := listOptions{filter: opts.NewFilterOpt()}
    27  
    28  	cmd := &cobra.Command{
    29  		Use:     "ls [OPTIONS]",
    30  		Aliases: []string{"list"},
    31  		Short:   "List nodes in the swarm",
    32  		Args:    cli.NoArgs,
    33  		RunE: func(cmd *cobra.Command, args []string) error {
    34  			return runList(cmd.Context(), dockerCli, options)
    35  		},
    36  		ValidArgsFunction: completion.NoComplete,
    37  	}
    38  	flags := cmd.Flags()
    39  	flags.BoolVarP(&options.quiet, "quiet", "q", false, "Only display IDs")
    40  	flags.StringVar(&options.format, "format", "", flagsHelper.FormatHelp)
    41  	flags.VarP(&options.filter, "filter", "f", "Filter output based on conditions provided")
    42  
    43  	return cmd
    44  }
    45  
    46  func runList(ctx context.Context, dockerCli command.Cli, options listOptions) error {
    47  	client := dockerCli.Client()
    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 := system.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  }