From 6f46d941f8df2adf0b9dedc57b7264a323f6faed Mon Sep 17 00:00:00 2001 From: Jimmy Zelinskie Date: Thu, 21 Apr 2022 16:06:23 -0400 Subject: [PATCH] version: use buildinfo vcs revision --- version.go | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/version.go b/version.go index 98f24dd..2052a4e 100644 --- a/version.go +++ b/version.go @@ -6,10 +6,20 @@ import ( "runtime/debug" "strings" + "github.com/jzelinskie/stringz" "github.com/spf13/cobra" "github.com/spf13/pflag" ) +func vcsRevision(bi *debug.BuildInfo) string { + for _, setting := range bi.Settings { + if setting.Key == "vcs.revision" { + return setting.Value + } + } + return "" +} + // Version is variable that holds program's version string. // This should be set with the follow flags to the `go build` command: // -ldflags '-X github.com/jzelinskie/cobrautil.Version=$YOUR_VERSION_HERE' @@ -23,11 +33,9 @@ func UsageVersion(programName string, includeDeps bool) string { panic("failed to read BuildInfo because the program was compiled with Go " + runtime.Version()) } - if Version == "" { - // The version wasn't set by ldflags, so fallback to the Go module version. - // Although, this value is pretty much guaranteed to just be "(devel)". - Version = bi.Main.Version - } + // The version wasn't set by ldflags, so fallback to the VCS revision, and + // finally Go module version. + Version = stringz.DefaultEmpty(stringz.DefaultEmpty(Version, vcsRevision(bi)), bi.Main.Version) if !includeDeps { if Version == "(devel)" {