|
| 1 | +// Package version formats a CLI version banner. |
| 2 | +// |
| 3 | +// Each binary's main package declares its own ldflag-populated |
| 4 | +// `version`, `commit`, `date` variables and passes them to Print. When the |
| 5 | +// binary is built without ldflags (e.g. `go install`), missing fields are |
| 6 | +// filled from runtime/debug.ReadBuildInfo where possible. |
| 7 | +package version |
| 8 | + |
| 9 | +import ( |
| 10 | + "fmt" |
| 11 | + "io" |
| 12 | + "runtime/debug" |
| 13 | +) |
| 14 | + |
| 15 | +const ( |
| 16 | + devVersion = "dev" |
| 17 | + noCommit = "none" |
| 18 | + unknownDate = "unknown" |
| 19 | + shortCommitLen = 7 |
| 20 | +) |
| 21 | + |
| 22 | +// Print writes a single-line version banner of the form |
| 23 | +// |
| 24 | +// <name> <version> (<commit>, built <date>) |
| 25 | +// |
| 26 | +// Empty / placeholder fields are filled from runtime/debug.ReadBuildInfo |
| 27 | +// when available so that `go install ...@latest` builds also produce a |
| 28 | +// useful banner. |
| 29 | +func Print(w io.Writer, name, version, commit, date string) { |
| 30 | + v, c, d := Resolve(version, commit, date) |
| 31 | + if len(c) > shortCommitLen { |
| 32 | + c = c[:shortCommitLen] |
| 33 | + } |
| 34 | + _, _ = fmt.Fprintf(w, "%s %s (%s, built %s)\n", name, v, c, d) |
| 35 | +} |
| 36 | + |
| 37 | +// Resolve returns the version triple, falling back to VCS info from the |
| 38 | +// embedded build info when the input fields are placeholders or empty. |
| 39 | +// Exported for testing. |
| 40 | +func Resolve(version, commit, date string) (string, string, string) { |
| 41 | + if isPlaceholder(version) || isPlaceholder(commit) || isPlaceholder(date) { |
| 42 | + if bi, ok := debug.ReadBuildInfo(); ok { |
| 43 | + if isPlaceholder(version) && bi.Main.Version != "" && bi.Main.Version != "(devel)" { |
| 44 | + version = bi.Main.Version |
| 45 | + } |
| 46 | + for _, s := range bi.Settings { |
| 47 | + switch s.Key { |
| 48 | + case "vcs.revision": |
| 49 | + if isPlaceholder(commit) { |
| 50 | + commit = s.Value |
| 51 | + } |
| 52 | + case "vcs.time": |
| 53 | + if isPlaceholder(date) { |
| 54 | + date = s.Value |
| 55 | + } |
| 56 | + } |
| 57 | + } |
| 58 | + } |
| 59 | + } |
| 60 | + if version == "" { |
| 61 | + version = devVersion |
| 62 | + } |
| 63 | + if commit == "" { |
| 64 | + commit = noCommit |
| 65 | + } |
| 66 | + if date == "" { |
| 67 | + date = unknownDate |
| 68 | + } |
| 69 | + return version, commit, date |
| 70 | +} |
| 71 | + |
| 72 | +func isPlaceholder(s string) bool { |
| 73 | + switch s { |
| 74 | + case "", devVersion, noCommit, unknownDate: |
| 75 | + return true |
| 76 | + } |
| 77 | + return false |
| 78 | +} |
0 commit comments