From baa3250b8cb3bb878b15142ae22ee8133d02926d Mon Sep 17 00:00:00 2001 From: Umputun Date: Tue, 10 Feb 2026 13:30:45 -0600 Subject: [PATCH] fix: resolve version as unknown when installed via go install MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit use debug.ReadBuildInfo() fallback when ldflags revision is not set. priority: ldflags → module version (go install tag) → VCS commit hash → unknown. Related to #83 --- cmd/ralphex/main.go | 26 +++++++++++++++++++++++++- cmd/ralphex/main_test.go | 19 +++++++++++++++++++ 2 files changed, 44 insertions(+), 1 deletion(-) diff --git a/cmd/ralphex/main.go b/cmd/ralphex/main.go index 7f00c91..8190c42 100644 --- a/cmd/ralphex/main.go +++ b/cmd/ralphex/main.go @@ -10,6 +10,7 @@ import ( "os/exec" "os/signal" "path/filepath" + "runtime/debug" "strings" "syscall" "time" @@ -48,6 +49,29 @@ type opts struct { var revision = "unknown" +// resolveVersion returns the best available version string. +// priority: ldflags revision → module version from go install → VCS commit hash → "unknown". +func resolveVersion() string { + if revision != "unknown" { + return revision + } + bi, ok := debug.ReadBuildInfo() + if !ok { + return revision + } + // go install sets module version to the tag (e.g. v0.10.0) + if bi.Main.Version != "" && bi.Main.Version != "(devel)" { + return bi.Main.Version + } + // local build without ldflags — try VCS revision + for _, s := range bi.Settings { + if s.Key == "vcs.revision" && len(s.Value) >= 7 { + return s.Value[:7] + } + } + return revision +} + // stderrLog is a simple logger that writes to stderr. // satisfies notify.logger interface for use before progress logger is available. type stderrLog struct{} @@ -79,7 +103,7 @@ type executePlanRequest struct { } func main() { - fmt.Printf("ralphex %s\n", revision) + fmt.Printf("ralphex %s\n", resolveVersion()) var o opts parser := flags.NewParser(&o, flags.Default) diff --git a/cmd/ralphex/main_test.go b/cmd/ralphex/main_test.go index 44e3c23..78fc908 100644 --- a/cmd/ralphex/main_test.go +++ b/cmd/ralphex/main_test.go @@ -885,3 +885,22 @@ func setupTestRepo(t *testing.T) string { return dir } + +func TestResolveVersion(t *testing.T) { + t.Run("ldflags_set", func(t *testing.T) { + orig := revision + t.Cleanup(func() { revision = orig }) + revision = "v1.2.3-abc1234" + assert.Equal(t, "v1.2.3-abc1234", resolveVersion()) + }) + + t.Run("fallback_to_build_info", func(t *testing.T) { + orig := revision + t.Cleanup(func() { revision = orig }) + revision = "unknown" + // in test context, debug.ReadBuildInfo returns (devel) module version + // but VCS info should be available from the git repo + v := resolveVersion() + assert.NotEmpty(t, v) + }) +}