feat: JSON output for the `list` sub-command

This commit is contained in:
Matej Vasek 2020-08-11 15:25:33 +02:00 committed by GitHub
parent 11692f6bd3
commit 17a00c9057
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 67 additions and 5 deletions

View File

@ -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)
}