-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuildinfo.go
More file actions
266 lines (231 loc) · 8.15 KB
/
Copy pathbuildinfo.go
File metadata and controls
266 lines (231 loc) · 8.15 KB
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
package buildinfo
import (
"encoding/json"
"runtime"
"runtime/debug"
"sync"
)
// Info contains build metadata for a Go binary.
//
// String fields default to DevVersion (Version) or Unknown (Commit, BuildTime,
// Branch) when neither -ldflags nor runtime/debug data populate them, so callers
// can render them safely without nil checks. Because those defaults are
// indistinguishable from real values by inspection alone, Source records which
// input actually won and HasCommit / HasVersion report whether a field holds
// real data.
type Info struct {
// Version is the semver string for this build, or DevVersion when nothing
// supplied one. Check Source to find out which.
Version string `json:"version"`
// Source records which input produced Version. See Source.
Source Source `json:"source"`
// Commit is the VCS commit hash, or Unknown.
Commit string `json:"commit"`
// BuildTime is the build timestamp in RFC3339 format, or Unknown.
BuildTime string `json:"build_time"`
// Branch is the VCS branch name, or Unknown. Go records no branch, so this
// is populated only via -ldflags.
Branch string `json:"branch"`
// GoVersion is the toolchain version that produced the binary.
GoVersion string `json:"go_version"`
// GOOS is the target operating system.
GOOS string `json:"goos"`
// GOARCH is the target architecture.
GOARCH string `json:"goarch"`
// Modified reports an uncommitted working tree at build time. Meaningful
// only alongside a real commit — see HasCommit.
Modified bool `json:"modified"`
// Modules lists dependency modules, with any replace directives resolved
// to their targets.
Modules []Module `json:"modules,omitempty"`
}
// HasCommit reports whether Commit holds a real hash rather than the Unknown
// sentinel.
//
// Needed because Modified is only meaningful alongside a commit: rendering
// "unknown (dirty)" asserts a dirty checkout for a build that carries no VCS
// record at all. Prefer this over comparing against Unknown yourself — the
// sentinel is this package's business, not its callers'.
func (i Info) HasCommit() bool {
return i.Commit != "" && i.Commit != Unknown
}
// HasVersion reports whether Version came from a real input (an -ldflags stamp
// or a resolved module version) rather than falling back to DevVersion.
//
// Equivalent to Source != SourceUnknown, and offered because that is the check
// most callers actually want when deciding whether to display a version at all.
func (i Info) HasVersion() bool {
return i.Source != SourceUnknown
}
// Module describes a single dependency module entry from runtime/debug.
type Module struct {
Path string `json:"path"`
Version string `json:"version"`
Sum string `json:"sum,omitempty"`
}
// develVersion is the placeholder runtime/debug reports for Main.Version when a
// binary is built from a local source tree rather than resolved through the
// module proxy (`go build` / `go test` / `go run`). It is not a real version, so
// it must never be surfaced to callers.
const develVersion = "(devel)"
// Sentinel values used when an input supplied nothing. Exported so callers can
// compare against them instead of hardcoding the literals — a duplicated
// sentinel in a consumer breaks silently if this package ever changes one.
const (
// DevVersion is Info.Version when no -ldflags stamp and no module version
// were available, i.e. a plain local build.
DevVersion = "dev"
// Unknown is the fallback for Commit, BuildTime, and Branch.
Unknown = "unknown"
)
// Source identifies which input produced Info.Version.
//
// Exists because the version string alone cannot answer the most common
// question a user asks about a build: "why does it say dev?" A binary reports
// DevVersion both when it was built locally and when a release pipeline forgot
// to pass its ldflags, and those need different responses. Surfacing the source
// makes the difference self-diagnosing rather than a support conversation.
type Source string
const (
// SourceLdflags means Version was stamped at build time via
// -X github.com/ubgo/buildinfo.Version=... — the release path.
SourceLdflags Source = "ldflags"
// SourceModule means Version came from the module version the Go toolchain
// recorded in BuildInfo.Main.Version, i.e. the binary was installed with
// `go install <pkg>@<version>`.
SourceModule Source = "module"
// SourceUnknown means neither input applied and Version is DevVersion: a
// plain `go build`, `go run`, or `go test` binary with no release
// provenance.
SourceUnknown Source = "unknown"
)
// Valid reports whether s is a known source. Guards against a zero-value or
// hand-constructed Info being treated as if it carried real provenance.
func (s Source) Valid() bool {
switch s {
case SourceLdflags, SourceModule, SourceUnknown:
return true
}
return false
}
// String implements fmt.Stringer.
func (s Source) String() string { return string(s) }
var (
cached Info
once sync.Once
// readBuildInfo is the seam for tests to inject a synthetic *debug.BuildInfo.
readBuildInfo = debug.ReadBuildInfo
)
// Get returns the populated Info struct, cached after the first call.
//
// Population precedence (highest first):
//
// 1. -ldflags overrides set at build time.
// 2. runtime/debug.ReadBuildInfo data — the module version recorded in
// Main.Version, plus VCS data (vcs.revision, vcs.time, vcs.modified).
// 3. Sentinel defaults (DevVersion for Version, Unknown for Commit /
// BuildTime / Branch).
//
// Info.Source reports which of those produced Version, so a caller never has to
// infer provenance from the string itself.
func Get() Info {
once.Do(load)
return cached
}
// Map returns Info as a flat string-only map for legacy or string-typed
// consumers (e.g. simple key-value renderers).
//
// Modified and Modules are omitted: the former is not a string and the latter is
// unbounded, which would swamp a log line or a metric label set.
func Map() map[string]string {
i := Get()
return map[string]string{
"version": i.Version,
"source": string(i.Source),
"commit": i.Commit,
"build_time": i.BuildTime,
"branch": i.Branch,
"go_version": i.GoVersion,
"goos": i.GOOS,
"goarch": i.GOARCH,
}
}
// JSON returns the Info marshalled as JSON bytes.
func (i Info) JSON() ([]byte, error) {
return json.Marshal(i)
}
func load() {
info := Info{
GoVersion: runtime.Version(),
GOOS: runtime.GOOS,
GOARCH: runtime.GOARCH,
}
if bi, ok := readBuildInfo(); ok {
// Main.Version carries the module version the binary was resolved at,
// e.g. "v1.2.3" after `go install example.com/cmd/app@v1.2.3`. The Go
// toolchain records it with no build flags, which makes it the only
// automatic version source for users who install via `go install`
// rather than downloading a CI-stamped release artifact.
//
// Locally built binaries report the develVersion placeholder instead;
// treat that as absent so the sentinel default applies.
if bi.Main.Version != "" && bi.Main.Version != develVersion {
info.Version = bi.Main.Version
info.Source = SourceModule
}
for _, s := range bi.Settings {
switch s.Key {
case "vcs.revision":
info.Commit = s.Value
case "vcs.time":
info.BuildTime = s.Value
case "vcs.modified":
info.Modified = s.Value == "true"
}
}
info.Modules = collectModules(bi)
}
// Source is assigned in the same statement as Version everywhere it is set,
// so the two cannot drift out of agreement as this function grows.
if Version != "" {
info.Version = Version
info.Source = SourceLdflags
}
if Commit != "" {
info.Commit = Commit
}
if BuildTime != "" {
info.BuildTime = BuildTime
}
if Branch != "" {
info.Branch = Branch
}
if info.Version == "" {
info.Version = DevVersion
info.Source = SourceUnknown
}
if info.Commit == "" {
info.Commit = Unknown
}
if info.BuildTime == "" {
info.BuildTime = Unknown
}
if info.Branch == "" {
info.Branch = Unknown
}
cached = info
}
func collectModules(bi *debug.BuildInfo) []Module {
mods := make([]Module, 0, len(bi.Deps))
for _, d := range bi.Deps {
for d.Replace != nil {
d = d.Replace
}
mods = append(mods, Module{
Path: d.Path,
Version: d.Version,
Sum: d.Sum,
})
}
return mods
}