GetBuildInfo returns the current build information It first checks ldflags-injected values, then falls back to debug.ReadBuildInfo() for version information when installed via `go install`
()
| 34 | // It first checks ldflags-injected values, then falls back to debug.ReadBuildInfo() |
| 35 | // for version information when installed via `go install` |
| 36 | func GetBuildInfo() *BuildInfo { |
| 37 | info := &BuildInfo{ |
| 38 | Version: version, |
| 39 | BuildDate: buildDate, |
| 40 | Commit: commit, |
| 41 | GoVersion: runtime.Version(), |
| 42 | OS: runtime.GOOS, |
| 43 | Arch: runtime.GOARCH, |
| 44 | } |
| 45 | |
| 46 | // Backfill missing metadata from build info (supports go install without ldflags). |
| 47 | if buildInfo, ok := debug.ReadBuildInfo(); ok { |
| 48 | // Populate version from module tag when not provided via ldflags. |
| 49 | if info.Version == devBuildVersion && buildInfo.Main.Version != "" && buildInfo.Main.Version != "(devel)" { |
| 50 | info.Version = strings.TrimPrefix(buildInfo.Main.Version, "v") |
| 51 | } |
| 52 | |
| 53 | // Extract VCS info if available. |
| 54 | for _, setting := range buildInfo.Settings { |
| 55 | switch setting.Key { |
| 56 | case "vcs.revision": |
| 57 | if info.Commit == unknownBuildValue && len(setting.Value) >= 7 { |
| 58 | info.Commit = setting.Value[:7] |
| 59 | } |
| 60 | case "vcs.time": |
| 61 | if info.BuildDate == unknownBuildValue { |
| 62 | info.BuildDate = setting.Value |
| 63 | } |
| 64 | } |
| 65 | } |
| 66 | } |
| 67 | |
| 68 | // Final fallback: use constants embedded at release time (release.go). |
| 69 | // These are set by the release script and are the only source of truth |
| 70 | // when building via `go install` from the module proxy, where no VCS |
| 71 | // metadata is available. |
| 72 | if info.Version == devBuildVersion && releaseVersion != "" { |
| 73 | info.Version = releaseVersion |
| 74 | } |
| 75 | if info.Commit == unknownBuildValue && releaseCommit != "" { |
| 76 | info.Commit = releaseCommit |
| 77 | } |
| 78 | if info.BuildDate == unknownBuildValue && releaseDate != "" { |
| 79 | info.BuildDate = releaseDate |
| 80 | } |
| 81 | |
| 82 | return info |
| 83 | } |
| 84 | |
| 85 | // GetVersionString returns a formatted version string |
| 86 | func GetVersionString() string { |