/
version.go
68 lines (54 loc) · 1.33 KB
/
version.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package cmd
import (
"encoding/json"
"fmt"
"runtime"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"gopkg.in/yaml.v2"
)
var (
// Version defines the application version (defined at compile time)
Version = ""
// Commit defines the application commit hash (defined at compile time)
Commit = ""
)
const (
flagFormat = "format"
)
// VersionCmd returns the command that allows to show the version information
func VersionCmd() *cobra.Command {
versionCmd := &cobra.Command{
Use: "version",
Short: "Print the version information",
RunE: func(cmd *cobra.Command, args []string) error {
verInfo := struct {
Version string `json:"version" yaml:"version"`
Commit string `json:"commit" yaml:"commit"`
Go string `json:"go" yaml:"go"`
}{
Version: Version,
Commit: Commit,
Go: fmt.Sprintf("%s %s/%s", runtime.Version(), runtime.GOOS, runtime.GOARCH),
}
var (
bz []byte
err error
)
versionFormat := viper.GetString(flagFormat)
switch versionFormat {
case "json":
bz, err = json.Marshal(verInfo)
default:
bz, err = yaml.Marshal(&verInfo)
}
if err != nil {
return err
}
_, err = fmt.Println(string(bz))
return err
},
}
versionCmd.Flags().String(flagFormat, "text", "Print the version in the given format (text | json)")
return versionCmd
}