|
4 | 4 | // |
5 | 5 | // This package captures key metadata about the application build, including the |
6 | 6 | // Git tag, full and short commit hashes, build date, Go runtime version, target |
7 | | -// platform, and the list of Go modules used in the build. These values are |
8 | | -// intended to be set at build time via linker flags (-ldflags), allowing |
9 | | -// embedding of dynamic version information within the compiled binary. |
| 7 | +// platform, and the list of Go modules used in the build. These values can be |
| 8 | +// set at build time via linker flags (-ldflags), or automatically extracted from |
| 9 | +// debug.BuildInfo at runtime when available. |
| 10 | +// |
| 11 | +// Version Information Sources: |
| 12 | +// |
| 13 | +// 1. Build-time ldflags (recommended for releases): |
| 14 | +// - Provides precise control over version information |
| 15 | +// - Set via -ldflags during go build |
| 16 | +// |
| 17 | +// 2. Runtime debug.BuildInfo (automatic fallback): |
| 18 | +// - Automatically used when ldflags are not set |
| 19 | +// - Extracts vcs.revision (git commit), vcs.time (build date), vcs.modified |
| 20 | +// - Available when building with Go 1.18+ and VCS information embedded |
| 21 | +// - Can be manually triggered via LoadFromBuildInfo() |
10 | 22 | // |
11 | 23 | // Supported Version Formats: |
12 | 24 | // |
@@ -107,9 +119,36 @@ var ( |
107 | 119 | ) |
108 | 120 |
|
109 | 121 | func init() { |
110 | | - if info, available := debug.ReadBuildInfo(); available { |
111 | | - for _, mod := range info.Deps { |
112 | | - Modules = append(Modules, (&Module{}).fromBuildInfo(mod)) |
| 122 | + info, available := debug.ReadBuildInfo() |
| 123 | + if !available { |
| 124 | + return |
| 125 | + } |
| 126 | + |
| 127 | + for _, mod := range info.Deps { |
| 128 | + Modules = append(Modules, (&Module{}).fromBuildInfo(mod)) |
| 129 | + } |
| 130 | + |
| 131 | + if GitCommit != "unknown" || BuildDate != "unknown" { |
| 132 | + return |
| 133 | + } |
| 134 | + |
| 135 | + if info.Main.Version != "" && info.Main.Version != "(devel)" { |
| 136 | + GitTag = info.Main.Version |
| 137 | + } |
| 138 | + |
| 139 | + for _, setting := range info.Settings { |
| 140 | + switch setting.Key { |
| 141 | + case "vcs.revision": |
| 142 | + if setting.Value != "" { |
| 143 | + GitCommit = setting.Value |
| 144 | + GitShort = GitCommit |
| 145 | + |
| 146 | + if len(GitShort) >= 7 { |
| 147 | + GitShort = GitShort[:7] |
| 148 | + } |
| 149 | + } |
| 150 | + case "vcs.time": |
| 151 | + BuildDate = setting.Value |
113 | 152 | } |
114 | 153 | } |
115 | 154 | } |
|
0 commit comments