From 0ad85c56e5a611240525e8b4a641b9cee33acd9a Mon Sep 17 00:00:00 2001 From: Thibault Richard Date: Thu, 25 Jul 2024 13:52:07 +0200 Subject: [PATCH] Also support version on go install (#87) This makes the version command also works when the binary is installed using go install. --- .github/workflows/release.yml | 4 +-- main.go | 49 +++++++++++++++++++++++++++++++++-- 2 files changed, 49 insertions(+), 4 deletions(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 30b8bfa..b1109c2 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -31,9 +31,9 @@ jobs: - run: ./test.sh - name: Run GoReleaser - uses: goreleaser/goreleaser-action@v5 + uses: goreleaser/goreleaser-action@v6 env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} with: - version: '~> v1' + version: latest args: release --clean diff --git a/main.go b/main.go index caaf38c..22c9a1f 100644 --- a/main.go +++ b/main.go @@ -19,6 +19,7 @@ package main import ( "fmt" "os" + "runtime/debug" "strings" "time" @@ -38,7 +39,7 @@ func main() { Short: "Generate CRD reference documentation", SilenceUsage: true, SilenceErrors: true, - Version: version(), + Version: printVersion(), RunE: doRun, } @@ -144,12 +145,56 @@ func initLogging(level string) { zap.RedirectStdLog(logger.Named("stdlog")) } +// Global build information variables defined via ldflags during release. var ( buildVersion string buildDate string buildCommit string ) +// printVersion prints the version, git commit and build date using global variables defined via ldflags during release, +// or using values ​​from debug.ReadBuildInfo(). +func printVersion() string { + return fmt.Sprintf("Version: %s\nGitCommit: %s\nBuildDate: %s\n", version(), commit(), date()) +} + func version() string { - return fmt.Sprintf("Version: %s\nGitCommit: %s\nBuildDate: %s\n", buildVersion, buildCommit, buildDate) + if buildVersion != "" { + return buildVersion + } + bi, ok := debug.ReadBuildInfo() + if ok && bi != nil && bi.Main.Version != "" { + return bi.Main.Version + } + return "(unknown)" +} + +func date() string { + if buildDate != "" { + return buildDate + } + bi, ok := debug.ReadBuildInfo() + if ok { + for _, setting := range bi.Settings { + if setting.Key == "vcs.time" { + return setting.Value + } + } + } + return "(unknown)" +} + +func commit() string { + if buildCommit != "" { + return buildCommit + } + bi, ok := debug.ReadBuildInfo() + if ok { + for _, setting := range bi.Settings { + if setting.Key == "vcs.revision" { + return setting.Value + } + } + } + return "(unknown)" }