diff --git a/cmd/buildinfo.go b/cmd/buildinfo.go new file mode 100644 index 0000000..2aabe6a --- /dev/null +++ b/cmd/buildinfo.go @@ -0,0 +1,33 @@ +package cmd + +import "runtime/debug" + +func init() { + if version == "dev" { + applyBuildInfo() + } +} + +// applyBuildInfo reads Go's embedded build metadata and populates the version, +// commit, and buildDate vars when they were not injected via ldflags (e.g. go install). +func applyBuildInfo() { + info, ok := debug.ReadBuildInfo() + if !ok { + return + } + if v := info.Main.Version; v != "" && v != "(devel)" { + version = v + } + for _, s := range info.Settings { + switch s.Key { + case "vcs.revision": + if s.Value != "" { + commit = s.Value + } + case "vcs.time": + if s.Value != "" { + buildDate = s.Value + } + } + } +} diff --git a/cmd/buildinfo_test.go b/cmd/buildinfo_test.go new file mode 100644 index 0000000..bedc29c --- /dev/null +++ b/cmd/buildinfo_test.go @@ -0,0 +1,28 @@ +package cmd + +import "testing" + +func TestApplyBuildInfoDoesNotPanic(t *testing.T) { + originalVersion := version + originalCommit := commit + originalBuildDate := buildDate + t.Cleanup(func() { + version = originalVersion + commit = originalCommit + buildDate = originalBuildDate + }) + + applyBuildInfo() +} + +func TestApplyBuildInfoDoesNotSetDevilVersion(t *testing.T) { + originalVersion := version + t.Cleanup(func() { version = originalVersion }) + + version = "dev" + applyBuildInfo() + + if version == "(devel)" { + t.Fatal("applyBuildInfo must not set version to '(devel)'") + } +}