|
| 1 | +// version package provides build-time version information. |
| 2 | +// It is designed to be used via the -ldflags option of go build. |
| 3 | +// |
| 4 | +// e.g. |
| 5 | +// |
| 6 | +// go build -ldflags "-X github.com/kunitsucom/util.go/version.version=${BUILD_VERSION} -X github.com/kunitsucom/util.go/version.revision=${BUILD_REVISION} -X github.com/kunitsucom/util.go/version.branch=${BUILD_BRANCH} -X github.com/kunitsucom/util.go/version.timestamp=${BUILD_TIMESTAMP}" |
| 7 | +package version |
| 8 | + |
| 9 | +import ( |
| 10 | + "runtime" |
| 11 | + "runtime/debug" |
| 12 | +) |
| 13 | + |
| 14 | +//nolint:gochecknoglobals |
| 15 | +var ( |
| 16 | + version string |
| 17 | + revision string |
| 18 | + branch string |
| 19 | + timestamp string |
| 20 | +) |
| 21 | + |
| 22 | +type BuildVersion struct { |
| 23 | + Version string `json:"version"` |
| 24 | + Revision string `json:"revision"` |
| 25 | + Branch string `json:"branch"` |
| 26 | + Timestamp string `json:"timestamp"` |
| 27 | + GoVersion string `json:"goVersion"` |
| 28 | + GOARCH string `json:"goarch"` |
| 29 | + GOOS string `json:"goos"` |
| 30 | +} |
| 31 | + |
| 32 | +func ReadBuildVersion() BuildVersion { |
| 33 | + return BuildVersion{ |
| 34 | + Version: Version(), |
| 35 | + Revision: Revision(), |
| 36 | + Branch: Branch(), |
| 37 | + Timestamp: Timestamp(), |
| 38 | + GoVersion: runtime.Version(), |
| 39 | + GOARCH: runtime.GOARCH, |
| 40 | + GOOS: runtime.GOOS, |
| 41 | + } |
| 42 | +} |
| 43 | + |
| 44 | +func Version() string { |
| 45 | + if version != "" { |
| 46 | + return version |
| 47 | + } |
| 48 | + |
| 49 | + if info, ok := debug.ReadBuildInfo(); ok { |
| 50 | + return info.Main.Version |
| 51 | + } |
| 52 | + |
| 53 | + return "" |
| 54 | +} |
| 55 | + |
| 56 | +func Revision() string { |
| 57 | + if revision != "" { |
| 58 | + return revision |
| 59 | + } |
| 60 | + |
| 61 | + if info, ok := debug.ReadBuildInfo(); ok { |
| 62 | + for _, setting := range info.Settings { |
| 63 | + if setting.Key == "vcs.revision" { |
| 64 | + return setting.Value |
| 65 | + } |
| 66 | + } |
| 67 | + } |
| 68 | + |
| 69 | + return "" |
| 70 | +} |
| 71 | + |
| 72 | +func Branch() string { |
| 73 | + return branch |
| 74 | +} |
| 75 | + |
| 76 | +func Timestamp() string { |
| 77 | + if timestamp != "" { |
| 78 | + return timestamp |
| 79 | + } |
| 80 | + |
| 81 | + if info, ok := debug.ReadBuildInfo(); ok { |
| 82 | + for _, setting := range info.Settings { |
| 83 | + if setting.Key == "vcs.time" { |
| 84 | + return setting.Value |
| 85 | + } |
| 86 | + } |
| 87 | + } |
| 88 | + |
| 89 | + return "" |
| 90 | +} |
0 commit comments