Skip to content

Commit

Permalink
Also support version on go install (#87)
Browse files Browse the repository at this point in the history
This makes the version command also works when the binary is installed using go install.
  • Loading branch information
thbkrkr authored Jul 25, 2024
1 parent 282ebc8 commit 0ad85c5
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 4 deletions.
4 changes: 2 additions & 2 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
49 changes: 47 additions & 2 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ package main
import (
"fmt"
"os"
"runtime/debug"
"strings"
"time"

Expand All @@ -38,7 +39,7 @@ func main() {
Short: "Generate CRD reference documentation",
SilenceUsage: true,
SilenceErrors: true,
Version: version(),
Version: printVersion(),
RunE: doRun,
}

Expand Down Expand Up @@ -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)"
}

0 comments on commit 0ad85c5

Please sign in to comment.