|
| 1 | +package buildinfo |
| 2 | + |
| 3 | +import ( |
| 4 | + "path" |
| 5 | + "runtime/debug" |
| 6 | + "sync" |
| 7 | + "time" |
| 8 | + |
| 9 | + "golang.org/x/mod/semver" |
| 10 | +) |
| 11 | + |
| 12 | +var ( |
| 13 | + buildInfo *debug.BuildInfo |
| 14 | + buildInfoValid bool |
| 15 | + readBuildInfo sync.Once |
| 16 | + |
| 17 | + // Injected with ldflags at build! |
| 18 | + tag string |
| 19 | +) |
| 20 | + |
| 21 | +// Version returns the semantic version of the build. |
| 22 | +// Use golang.org/x/mod/semver to compare versions. |
| 23 | +func Version() string { |
| 24 | + revision, valid := revision() |
| 25 | + if valid { |
| 26 | + revision = "+" + revision[:7] |
| 27 | + } |
| 28 | + if tag == "" { |
| 29 | + return "v0.0.0-devel" + revision |
| 30 | + } |
| 31 | + if semver.Build(tag) == "" { |
| 32 | + tag += revision |
| 33 | + } |
| 34 | + return "v" + tag |
| 35 | +} |
| 36 | + |
| 37 | +// ExternalURL returns a URL referencing the current Coder version. |
| 38 | +// For production builds, this will link directly to a release. |
| 39 | +// For development builds, this will link to a commit. |
| 40 | +func ExternalURL() string { |
| 41 | + repo := "https://github.com/coder/coder" |
| 42 | + revision, valid := revision() |
| 43 | + if !valid { |
| 44 | + return repo |
| 45 | + } |
| 46 | + return path.Join(repo, "commit", revision) |
| 47 | +} |
| 48 | + |
| 49 | +// Time returns when the Git revision was published. |
| 50 | +func Time() (time.Time, bool) { |
| 51 | + value, valid := find("vcs.time") |
| 52 | + if !valid { |
| 53 | + return time.Time{}, false |
| 54 | + } |
| 55 | + parsed, err := time.Parse(time.RFC3339, value) |
| 56 | + if err != nil { |
| 57 | + panic("couldn't parse time: " + err.Error()) |
| 58 | + } |
| 59 | + return parsed, true |
| 60 | +} |
| 61 | + |
| 62 | +// revision returns the Git hash of the build. |
| 63 | +func revision() (string, bool) { |
| 64 | + return find("vcs.revision") |
| 65 | +} |
| 66 | + |
| 67 | +// find panics if a setting with the specific key was not |
| 68 | +// found in the build info. |
| 69 | +func find(key string) (string, bool) { |
| 70 | + readBuildInfo.Do(func() { |
| 71 | + buildInfo, buildInfoValid = debug.ReadBuildInfo() |
| 72 | + }) |
| 73 | + if !buildInfoValid { |
| 74 | + panic("couldn't read build info") |
| 75 | + } |
| 76 | + for _, setting := range buildInfo.Settings { |
| 77 | + if setting.Key != key { |
| 78 | + continue |
| 79 | + } |
| 80 | + return setting.Value, true |
| 81 | + } |
| 82 | + return "", false |
| 83 | +} |
0 commit comments