...
1
2
3
4
5
6
7
8
9
10
11
12
13
14 package version
15
16 import (
17 "bytes"
18 "fmt"
19 "runtime"
20 "runtime/debug"
21 "strings"
22 "text/template"
23 )
24
25
26 var (
27 Version string
28 Revision string
29 Branch string
30 BuildUser string
31 BuildDate string
32 GoVersion = runtime.Version()
33 GoOS = runtime.GOOS
34 GoArch = runtime.GOARCH
35
36 computedRevision string
37 computedTags string
38 )
39
40
41 var versionInfoTmpl = `
42 {{.program}}, version {{.version}} (branch: {{.branch}}, revision: {{.revision}})
43 build user: {{.buildUser}}
44 build date: {{.buildDate}}
45 go version: {{.goVersion}}
46 platform: {{.platform}}
47 tags: {{.tags}}
48 `
49
50
51 func Print(program string) string {
52 m := map[string]string{
53 "program": program,
54 "version": Version,
55 "revision": GetRevision(),
56 "branch": Branch,
57 "buildUser": BuildUser,
58 "buildDate": BuildDate,
59 "goVersion": GoVersion,
60 "platform": GoOS + "/" + GoArch,
61 "tags": GetTags(),
62 }
63 t := template.Must(template.New("version").Parse(versionInfoTmpl))
64
65 var buf bytes.Buffer
66 if err := t.ExecuteTemplate(&buf, "version", m); err != nil {
67 panic(err)
68 }
69 return strings.TrimSpace(buf.String())
70 }
71
72
73 func Info() string {
74 return fmt.Sprintf("(version=%s, branch=%s, revision=%s)", Version, Branch, GetRevision())
75 }
76
77
78 func BuildContext() string {
79 return fmt.Sprintf("(go=%s, platform=%s, user=%s, date=%s, tags=%s)", GoVersion, GoOS+"/"+GoArch, BuildUser, BuildDate, GetTags())
80 }
81
82 func GetRevision() string {
83 if Revision != "" {
84 return Revision
85 }
86 return computedRevision
87 }
88
89 func GetTags() string {
90 return computedTags
91 }
92
93 func init() {
94 computedRevision, computedTags = computeRevision()
95 }
96
97 func computeRevision() (string, string) {
98 var (
99 rev = "unknown"
100 tags = "unknown"
101 modified bool
102 )
103
104 buildInfo, ok := debug.ReadBuildInfo()
105 if !ok {
106 return rev, tags
107 }
108 for _, v := range buildInfo.Settings {
109 if v.Key == "vcs.revision" {
110 rev = v.Value
111 }
112 if v.Key == "vcs.modified" {
113 if v.Value == "true" {
114 modified = true
115 }
116 }
117 if v.Key == "-tags" {
118 tags = v.Value
119 }
120 }
121 if modified {
122 return rev + "-modified", tags
123 }
124 return rev, tags
125 }
126
View as plain text