...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package format
17
18 import (
19 "encoding/json"
20 "fmt"
21
22 "github.com/sigstore/timestamp-authority/pkg/log"
23 "github.com/spf13/cobra"
24 "github.com/spf13/viper"
25 )
26
27 type CobraCmd func(cmd *cobra.Command, args []string)
28
29 type formatCmd func(args []string) (interface{}, error)
30
31 func WrapCmd(f formatCmd) CobraCmd {
32 return func(cmd *cobra.Command, args []string) {
33 obj, err := f(args)
34 if err != nil {
35 log.CliLogger.Fatal(err)
36 }
37
38
39 format := viper.GetString("format")
40 switch format {
41 case "default":
42 if s, ok := obj.(fmt.Stringer); ok {
43 fmt.Print(s.String())
44 } else {
45 fmt.Println(toJSON(s))
46 }
47 case "json":
48 fmt.Println(toJSON(obj))
49 }
50 }
51 }
52
53 func toJSON(i interface{}) string {
54 b, err := json.Marshal(i)
55 if err != nil {
56 log.CliLogger.Fatal(err)
57 }
58 return string(b)
59 }
60
View as plain text