From 17a00c9057e2ba4bb9ea698d801ed582cf06efea Mon Sep 17 00:00:00 2001 From: Matej Vasek Date: Tue, 11 Aug 2020 15:25:33 +0200 Subject: [PATCH] feat: JSON output for the `list` sub-command --- cmd/list.go | 72 +++++++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 67 insertions(+), 5 deletions(-) diff --git a/cmd/list.go b/cmd/list.go index 692e8a14..fd7c2169 100644 --- a/cmd/list.go +++ b/cmd/list.go @@ -1,16 +1,44 @@ package cmd import ( + "encoding/json" "fmt" + "gopkg.in/yaml.v2" + "io" + "os" "github.com/boson-project/faas" "github.com/boson-project/faas/knative" - "github.com/ory/viper" "github.com/spf13/cobra" ) +var formats = map[string]fmtFn{ + "plain": fmtPlain, + "json": fmtJSON, + "yaml": fmtYAML, +} + +var validFormats []string + +func completeFormats(cmd *cobra.Command, args []string, toComplete string) (formats []string, directive cobra.ShellCompDirective) { + formats = validFormats + directive = cobra.ShellCompDirectiveDefault + return +} + func init() { root.AddCommand(listCmd) + + validFormats = make([]string, 0, len(formats)) + for name := range formats { + validFormats = append(validFormats, name) + } + + listCmd.Flags().StringP("output", "o", "plain", "optionally specify output format (plain,json,yaml)") + err := listCmd.RegisterFlagCompletionFunc("output", completeFormats) + if err != nil { + fmt.Fprintln(os.Stderr, err) + } } var listCmd = &cobra.Command{ @@ -21,8 +49,39 @@ var listCmd = &cobra.Command{ RunE: list, } +type fmtFn func(writer io.Writer, names []string) error + +func fmtPlain(writer io.Writer, names []string) error { + for _, name := range names { + _, err := fmt.Fprintf(writer, "%s\n", name) + if err != nil { + return err + } + } + return nil +} + +func fmtJSON(writer io.Writer, names []string) error { + encoder := json.NewEncoder(writer) + return encoder.Encode(names) +} + +func fmtYAML(writer io.Writer, names []string) error { + encoder := yaml.NewEncoder(writer) + return encoder.Encode(names) +} + func list(cmd *cobra.Command, args []string) (err error) { - verbose := viper.GetBool("verbose") + + verbose, err := cmd.Flags().GetBool("verbose") + if err != nil { + return + } + + format, err := cmd.Flags().GetString("output") + if err != nil { + return + } lister, err := knative.NewLister(faas.DefaultNamespace) if err != nil { @@ -42,8 +101,11 @@ func list(cmd *cobra.Command, args []string) (err error) { if err != nil { return } - for _, name := range names { - fmt.Printf("%s\n", name) + + fmtFn, ok := formats[format] + if !ok { + return fmt.Errorf("invalid format name: %s", format) } - return + + return fmtFn(os.Stdout, names) }