|
1 | 1 | package cmd
|
2 | 2 |
|
3 | 3 | import (
|
| 4 | + "encoding/json" |
| 5 | + "fmt" |
| 6 | + |
4 | 7 | log "github.com/sirupsen/logrus"
|
| 8 | + |
5 | 9 | "github.com/spf13/cobra"
|
6 | 10 | )
|
7 | 11 |
|
8 | 12 | var (
|
| 13 | + // BuildTag holds the `git tag` if this is a tagged build/release |
| 14 | + BuildTag = "canary" |
| 15 | + |
9 | 16 | // BuildSHA holds the git commit SHA at `make build` time.
|
10 | 17 | BuildSHA = "unset"
|
11 | 18 |
|
12 |
| - // BuildTag holds the `git tag` if this is a tagged build/release |
13 |
| - BuildTag = "unset" |
| 19 | + // GitTreeState is the state of the git tree, either clean or dirty |
| 20 | + GitTreeState = "unset" |
| 21 | + |
| 22 | + outputFormatOptions = []string{"human", "json"} |
| 23 | + outputFormat string |
| 24 | + version versionInfo |
14 | 25 | )
|
15 | 26 |
|
| 27 | +type versionInfo struct { |
| 28 | + GitTag string |
| 29 | + GitCommit string |
| 30 | + GitTreeState string |
| 31 | +} |
| 32 | + |
| 33 | +func init() { |
| 34 | + version = versionInfo{ |
| 35 | + GitTag: BuildTag, |
| 36 | + GitCommit: BuildSHA, |
| 37 | + GitTreeState: GitTreeState, |
| 38 | + } |
| 39 | +} |
| 40 | + |
| 41 | +func getHumanVersion() string { |
| 42 | + r := fmt.Sprintf("Version: %s\nGitCommit: %s\nGitTreeState: %s", |
| 43 | + version.GitTag, |
| 44 | + version.GitCommit, |
| 45 | + version.GitTreeState) |
| 46 | + |
| 47 | + return r |
| 48 | +} |
| 49 | + |
| 50 | +func getJSONVersion() string { |
| 51 | + jsonVersion, _ := json.MarshalIndent(version, "", " ") |
| 52 | + return string(jsonVersion) |
| 53 | +} |
| 54 | + |
| 55 | +func getVersion(outputType string) string { |
| 56 | + var output string |
| 57 | + |
| 58 | + if outputType == "human" { |
| 59 | + output = getHumanVersion() |
| 60 | + } else if outputType == "json" { |
| 61 | + output = getJSONVersion() |
| 62 | + } else { |
| 63 | + log.Fatalf("unsupported output format: %s\n", outputFormat) |
| 64 | + } |
| 65 | + |
| 66 | + return output |
| 67 | +} |
| 68 | + |
16 | 69 | func newVersionCmd() *cobra.Command {
|
17 | 70 | versionCmd := &cobra.Command{
|
18 | 71 | Use: "version",
|
19 | 72 | Short: "Print the version of ACS-Engine",
|
20 | 73 | Long: "Print the version of ACS-Engine",
|
21 | 74 |
|
22 | 75 | Run: func(cmd *cobra.Command, args []string) {
|
23 |
| - log.Infof("ACS-Engine Version: %s (%s)", BuildTag, BuildSHA) |
| 76 | + fmt.Println(getVersion(outputFormat)) |
24 | 77 | },
|
25 | 78 | }
|
| 79 | + |
| 80 | + versionCmdDescription := fmt.Sprintf("Output format to use: %s", outputFormatOptions) |
| 81 | + |
| 82 | + versionCmd.Flags().StringVarP(&outputFormat, "output", "o", "human", versionCmdDescription) |
| 83 | + |
26 | 84 | return versionCmd
|
27 | 85 | }
|
0 commit comments