...

Source file src/github.com/peterbourgon/ff/v3/ffcli/examples/objectctl/pkg/listcmd/list.go

Documentation: github.com/peterbourgon/ff/v3/ffcli/examples/objectctl/pkg/listcmd

     1  package listcmd
     2  
     3  import (
     4  	"context"
     5  	"flag"
     6  	"fmt"
     7  	"io"
     8  	"text/tabwriter"
     9  	"time"
    10  
    11  	"github.com/peterbourgon/ff/v3/ffcli"
    12  	"github.com/peterbourgon/ff/v3/ffcli/examples/objectctl/pkg/rootcmd"
    13  )
    14  
    15  // Config for the list subcommand, including a reference
    16  // to the global config, for access to global flags.
    17  type Config struct {
    18  	rootConfig      *rootcmd.Config
    19  	out             io.Writer
    20  	withAccessTimes bool
    21  }
    22  
    23  // New creates a new ffcli.Command for the list subcommand.
    24  func New(rootConfig *rootcmd.Config, out io.Writer) *ffcli.Command {
    25  	cfg := Config{
    26  		rootConfig: rootConfig,
    27  		out:        out,
    28  	}
    29  
    30  	fs := flag.NewFlagSet("objectctl list", flag.ExitOnError)
    31  	fs.BoolVar(&cfg.withAccessTimes, "a", false, "include last access time of each object")
    32  	rootConfig.RegisterFlags(fs)
    33  
    34  	return &ffcli.Command{
    35  		Name:       "list",
    36  		ShortUsage: "objectctl list [flags] [<prefix>]",
    37  		ShortHelp:  "List available objects",
    38  		FlagSet:    fs,
    39  		Exec:       cfg.Exec,
    40  	}
    41  }
    42  
    43  // Exec function for this command.
    44  func (c *Config) Exec(ctx context.Context, _ []string) error {
    45  	objects, err := c.rootConfig.Client.List(ctx)
    46  	if err != nil {
    47  		return fmt.Errorf("error executing list: %w", err)
    48  	}
    49  
    50  	if len(objects) <= 0 {
    51  		fmt.Fprintf(c.out, "no objects\n")
    52  		return nil
    53  	}
    54  
    55  	if c.rootConfig.Verbose {
    56  		fmt.Fprintf(c.out, "object count: %d\n", len(objects))
    57  	}
    58  
    59  	tw := tabwriter.NewWriter(c.out, 0, 2, 2, ' ', 0)
    60  	if c.withAccessTimes {
    61  		fmt.Fprintf(tw, "KEY\tVALUE\tATIME\n")
    62  	} else {
    63  		fmt.Fprintf(tw, "KEY\tVALUE\n")
    64  	}
    65  	for _, object := range objects {
    66  		if c.withAccessTimes {
    67  			fmt.Fprintf(tw, "%s\t%s\t%s\n", object.Key, object.Value, object.Access.Format(time.RFC3339))
    68  		} else {
    69  			fmt.Fprintf(tw, "%s\t%s\n", object.Key, object.Value)
    70  		}
    71  	}
    72  	tw.Flush()
    73  
    74  	return nil
    75  }
    76  

View as plain text