From fce89c88d1c7a1a7a6e6e01dc75812adfaaa9665 Mon Sep 17 00:00:00 2001 From: Christophe Fergeau Date: Wed, 15 Nov 2023 12:06:52 +0100 Subject: [PATCH] version: Add moduleVersionFromBuildInfo This adds correct version information for `gvproxy -version` when it's installed using: ``` go install github.com/containers/gvisor-tap-vsock/cmd/gvproxy ``` Signed-off-by: Christophe Fergeau --- pkg/types/version.go | 25 ++++++++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/pkg/types/version.go b/pkg/types/version.go index 4587d67ec..8e2ea6d94 100644 --- a/pkg/types/version.go +++ b/pkg/types/version.go @@ -3,6 +3,7 @@ package types import ( "flag" "fmt" + "runtime/debug" ) var ModuleVersion = "" @@ -19,7 +20,7 @@ func NewVersion(binaryName string) *version { //nolint:revive } func (ver *version) String() string { - return fmt.Sprintf("%s version %s", ver.binaryName, ModuleVersion) + return fmt.Sprintf("%s version %s", ver.binaryName, moduleVersion()) } func (ver *version) AddFlag() { @@ -29,3 +30,25 @@ func (ver *version) AddFlag() { func (ver *version) ShowVersion() bool { return ver.showVersion } + +func moduleVersion() string { + switch { + // This will be set when building from git using make + case ModuleVersion != "": + return ModuleVersion + // moduleVersionFromBuildInfo() will be set when using `go install` + default: + return moduleVersionFromBuildInfo() + } +} + +func moduleVersionFromBuildInfo() string { + info, ok := debug.ReadBuildInfo() + if !ok { + return "" + } + if info.Main.Version == "(devel)" { + return "" + } + return info.Main.Version +}