|
| 1 | +package buildinfo |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "runtime/debug" |
| 6 | + "strings" |
| 7 | +) |
| 8 | + |
| 9 | +var ( |
| 10 | + // Version is the semantic version of the CLI. |
| 11 | + Version = "dev" |
| 12 | + // Commit is the VCS revision used for the build. |
| 13 | + Commit = "unknown" |
| 14 | + // Date is the build timestamp in UTC (RFC3339 format). |
| 15 | + Date = "unknown" |
| 16 | +) |
| 17 | + |
| 18 | +func info() (version, commit, date string, dirty bool) { |
| 19 | + version = Version |
| 20 | + commit = Commit |
| 21 | + date = Date |
| 22 | + |
| 23 | + bi, ok := debug.ReadBuildInfo() |
| 24 | + if !ok { |
| 25 | + return version, commit, date, false |
| 26 | + } |
| 27 | + |
| 28 | + if (version == "dev" || version == "(devel)") && bi.Main.Version != "" && bi.Main.Version != "(devel)" { |
| 29 | + version = bi.Main.Version |
| 30 | + } |
| 31 | + |
| 32 | + for _, setting := range bi.Settings { |
| 33 | + switch setting.Key { |
| 34 | + case "vcs.revision": |
| 35 | + if commit == "unknown" && setting.Value != "" { |
| 36 | + commit = setting.Value |
| 37 | + } |
| 38 | + case "vcs.time": |
| 39 | + if date == "unknown" && setting.Value != "" { |
| 40 | + date = setting.Value |
| 41 | + } |
| 42 | + case "vcs.modified": |
| 43 | + dirty = setting.Value == "true" |
| 44 | + } |
| 45 | + } |
| 46 | + |
| 47 | + return version, commit, date, dirty |
| 48 | +} |
| 49 | + |
| 50 | +// Short returns a concise version string suitable for --version output. |
| 51 | +func Short() string { |
| 52 | + version, commit, _, dirty := info() |
| 53 | + |
| 54 | + var parts []string |
| 55 | + parts = append(parts, version) |
| 56 | + if commit != "" && commit != "unknown" { |
| 57 | + shortCommit := commit |
| 58 | + if len(shortCommit) > 7 { |
| 59 | + shortCommit = shortCommit[:7] |
| 60 | + } |
| 61 | + parts = append(parts, shortCommit) |
| 62 | + } |
| 63 | + if dirty { |
| 64 | + parts = append(parts, "dirty") |
| 65 | + } |
| 66 | + |
| 67 | + return strings.Join(parts, " ") |
| 68 | +} |
| 69 | + |
| 70 | +// Long returns full build details. |
| 71 | +func Long() string { |
| 72 | + version, commit, date, _ := info() |
| 73 | + return fmt.Sprintf( |
| 74 | + "Version: %s\nCommit: %s\nDate: %s", |
| 75 | + version, |
| 76 | + commit, |
| 77 | + date, |
| 78 | + ) |
| 79 | +} |
0 commit comments