github.com/kaisenlinux/docker.io@v0.0.0-20230510090727-ea55db55fac7/swarmkit/cmd/swarmctl/config/list.go (about)

     1  package config
     2  
     3  import (
     4  	"errors"
     5  	"fmt"
     6  	"os"
     7  	"sort"
     8  	"text/tabwriter"
     9  
    10  	"github.com/docker/swarmkit/api"
    11  	"github.com/docker/swarmkit/cmd/swarmctl/common"
    12  	"github.com/dustin/go-humanize"
    13  	gogotypes "github.com/gogo/protobuf/types"
    14  	"github.com/spf13/cobra"
    15  )
    16  
    17  type configSorter []*api.Config
    18  
    19  func (k configSorter) Len() int      { return len(k) }
    20  func (k configSorter) Swap(i, j int) { k[i], k[j] = k[j], k[i] }
    21  func (k configSorter) Less(i, j int) bool {
    22  	iTime, err := gogotypes.TimestampFromProto(k[i].Meta.CreatedAt)
    23  	if err != nil {
    24  		panic(err)
    25  	}
    26  	jTime, err := gogotypes.TimestampFromProto(k[j].Meta.CreatedAt)
    27  	if err != nil {
    28  		panic(err)
    29  	}
    30  	return jTime.Before(iTime)
    31  }
    32  
    33  var (
    34  	listCmd = &cobra.Command{
    35  		Use:   "ls",
    36  		Short: "List configs",
    37  		RunE: func(cmd *cobra.Command, args []string) error {
    38  			if len(args) != 0 {
    39  				return errors.New("ls command takes no arguments")
    40  			}
    41  
    42  			flags := cmd.Flags()
    43  			quiet, err := flags.GetBool("quiet")
    44  			if err != nil {
    45  				return err
    46  			}
    47  
    48  			client, err := common.Dial(cmd)
    49  			if err != nil {
    50  				return err
    51  			}
    52  
    53  			resp, err := client.ListConfigs(common.Context(cmd), &api.ListConfigsRequest{})
    54  			if err != nil {
    55  				return err
    56  			}
    57  
    58  			var output func(*api.Config)
    59  
    60  			if !quiet {
    61  				w := tabwriter.NewWriter(os.Stdout, 0, 4, 4, ' ', 0)
    62  				defer func() {
    63  					// Ignore flushing errors - there's nothing we can do.
    64  					_ = w.Flush()
    65  				}()
    66  				common.PrintHeader(w, "ID", "Name", "Created")
    67  				output = func(s *api.Config) {
    68  					created, err := gogotypes.TimestampFromProto(s.Meta.CreatedAt)
    69  					if err != nil {
    70  						panic(err)
    71  					}
    72  					fmt.Fprintf(w, "%s\t%s\t%s\n",
    73  						s.ID,
    74  						s.Spec.Annotations.Name,
    75  						humanize.Time(created),
    76  					)
    77  				}
    78  			} else {
    79  				output = func(s *api.Config) { fmt.Println(s.ID) }
    80  			}
    81  
    82  			sorted := configSorter(resp.Configs)
    83  			sort.Sort(sorted)
    84  			for _, s := range sorted {
    85  				output(s)
    86  			}
    87  			return nil
    88  		},
    89  	}
    90  )
    91  
    92  func init() {
    93  	listCmd.Flags().BoolP("quiet", "q", false, "Only display config IDs")
    94  }