This repository has been archived by the owner on Nov 5, 2020. It is now read-only.
forked from gomodules/x
-
Notifications
You must be signed in to change notification settings - Fork 2
/
version.go
87 lines (80 loc) · 2.4 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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package version
import (
"fmt"
"github.com/spf13/cobra"
semver "gomodules.xyz/version"
)
type version struct {
Version string `json:"version,omitempty"`
VersionStrategy string `json:"versionStrategy,omitempty"`
CommitHash string `json:"commitHash,omitempty"`
GitBranch string `json:"gitBranch,omitempty"`
GitTag string `json:"gitTag,omitempty"`
CommitTimestamp string `json:"commitTimestamp,omitempty"`
GoVersion string `json:"goVersion,omitempty"`
Compiler string `json:"compiler,omitempty"`
Platform string `json:"platform,omitempty"`
// Deprecated
Os string `json:"os,omitempty"`
// Deprecated
Arch string `json:"arch,omitempty"`
// Deprecated
BuildTimestamp string `json:"buildTimestamp,omitempty"`
// Deprecated
BuildHost string `json:"buildHost,omitempty"`
// Deprecated
BuildHostOs string `json:"buildHostOs,omitempty"`
// Deprecated
BuildHostArch string `json:"buildHostArch,omitempty"`
}
func (v *version) Print() {
fmt.Printf("Version = %v\n", v.Version)
fmt.Printf("VersionStrategy = %v\n", v.VersionStrategy)
fmt.Printf("GitTag = %v\n", v.GitTag)
fmt.Printf("GitBranch = %v\n", v.GitBranch)
fmt.Printf("CommitHash = %v\n", v.CommitHash)
fmt.Printf("CommitTimestamp = %v\n", v.CommitTimestamp)
if v.GoVersion != "" {
fmt.Printf("GoVersion = %v\n", v.GoVersion)
}
if v.Compiler != "" {
fmt.Printf("Compiler = %v\n", v.Compiler)
}
if v.Platform != "" {
fmt.Printf("Platform = %v\n", v.Platform)
}
}
var Version version
func NewCmdVersion() *cobra.Command {
var short bool
var check string
cmd := &cobra.Command{
Use: "version",
Short: "Prints binary version number.",
DisableAutoGenTag: true,
RunE: func(cmd *cobra.Command, args []string) error {
if short {
fmt.Print(Version.Version)
} else {
Version.Print()
}
if check != "" {
c, err := semver.NewConstraint(check)
if err != nil {
return fmt.Errorf("failed to parse --check: %v", err)
}
v, err := semver.NewSemver(Version.Version)
if err != nil {
return fmt.Errorf("failed to parse version: %v", err)
}
if !c.Check(v) {
return fmt.Errorf("version %q fails to meet constraint %q", v.String(), c.String())
}
}
return nil
},
}
cmd.Flags().BoolVar(&short, "short", false, "Print just the version number.")
cmd.Flags().StringVar(&check, "check", "", "Check version constraint")
return cmd
}