-
Notifications
You must be signed in to change notification settings - Fork 43
/
Copy pathversion.go
71 lines (62 loc) · 1.38 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
package buildinfo
import (
"fmt"
"runtime/debug"
"sync"
"golang.org/x/mod/semver"
)
const (
noVersion = "v0.0.0"
develPreRelease = "devel"
)
var (
buildInfo *debug.BuildInfo
buildInfoValid bool
readBuildInfo sync.Once
version string
readVersion sync.Once
// Injected with ldflags at build time
tag string
)
func revision() (string, bool) {
return find("vcs.revision")
}
func find(key string) (string, bool) {
readBuildInfo.Do(func() {
buildInfo, buildInfoValid = debug.ReadBuildInfo()
})
if !buildInfoValid {
panic("could not read build info")
}
for _, setting := range buildInfo.Settings {
if setting.Key != key {
continue
}
return setting.Value, true
}
return "", false
}
// Version returns the semantic version of the build.
// Use golang.org/x/mod/semver to compare versions.
func Version() string {
readVersion.Do(func() {
revision, valid := revision()
if valid {
revision = "+" + revision[:7]
}
if tag == "" {
// This occurs when the tag hasn't been injected,
// like when using "go run".
// <version>-<pre-release>+<revision>
version = fmt.Sprintf("%s-%s%s", noVersion, develPreRelease, revision)
return
}
version = "v" + tag
// The tag must be prefixed with "v" otherwise the
// semver library will return an empty string.
if semver.Build(version) == "" {
version += revision
}
})
return version
}