github.1git.de/docker/cli@v26.1.3+incompatible/cli/command/stack/list.go (about)

     1  package stack
     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/stack/formatter"
    11  	"github.com/docker/cli/cli/command/stack/options"
    12  	"github.com/docker/cli/cli/command/stack/swarm"
    13  	flagsHelper "github.com/docker/cli/cli/flags"
    14  	"github.com/fvbommel/sortorder"
    15  	"github.com/spf13/cobra"
    16  )
    17  
    18  func newListCommand(dockerCli command.Cli) *cobra.Command {
    19  	opts := options.List{}
    20  
    21  	cmd := &cobra.Command{
    22  		Use:     "ls [OPTIONS]",
    23  		Aliases: []string{"list"},
    24  		Short:   "List stacks",
    25  		Args:    cli.NoArgs,
    26  		RunE: func(cmd *cobra.Command, args []string) error {
    27  			return RunList(cmd.Context(), dockerCli, opts)
    28  		},
    29  		ValidArgsFunction: completion.NoComplete,
    30  	}
    31  
    32  	flags := cmd.Flags()
    33  	flags.StringVar(&opts.Format, "format", "", flagsHelper.FormatHelp)
    34  	return cmd
    35  }
    36  
    37  // RunList performs a stack list against the specified swarm cluster
    38  func RunList(ctx context.Context, dockerCli command.Cli, opts options.List) error {
    39  	ss, err := swarm.GetStacks(ctx, dockerCli)
    40  	if err != nil {
    41  		return err
    42  	}
    43  	stacks := make([]*formatter.Stack, 0, len(ss))
    44  	stacks = append(stacks, ss...)
    45  	return format(dockerCli, opts, stacks)
    46  }
    47  
    48  func format(dockerCli command.Cli, opts options.List, stacks []*formatter.Stack) error {
    49  	fmt := formatter.Format(opts.Format)
    50  	if fmt == "" || fmt == formatter.TableFormatKey {
    51  		fmt = formatter.SwarmStackTableFormat
    52  	}
    53  	stackCtx := formatter.Context{
    54  		Output: dockerCli.Out(),
    55  		Format: fmt,
    56  	}
    57  	sort.Slice(stacks, func(i, j int) bool {
    58  		return sortorder.NaturalLess(stacks[i].Name, stacks[j].Name) ||
    59  			!sortorder.NaturalLess(stacks[j].Name, stacks[i].Name)
    60  	})
    61  	return formatter.StackWrite(stackCtx, stacks)
    62  }