From 17b8e53da3cac591a528c838849511e2498459f9 Mon Sep 17 00:00:00 2001 From: onyx-and-iris Date: Tue, 3 Jun 2025 16:35:19 +0100 Subject: [PATCH] read version from build info if version was not injected at build time (go install) inject version from tag at build time for local builds --- Taskfile.yaml | 6 ++++-- version.go | 12 +++++++++++- 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/Taskfile.yaml b/Taskfile.yaml index 4f0b537..e2ded2a 100644 --- a/Taskfile.yaml +++ b/Taskfile.yaml @@ -7,6 +7,8 @@ vars: PROGRAM: gobs-cli SHELL: '{{if eq .OS "Windows_NT"}}powershell{{end}}' BIN_DIR: bin + VERSION: + sh: 'git describe --tags $(git rev-list --tags --max-count=1)' tasks: default: @@ -35,13 +37,13 @@ tasks: build-windows: desc: Build the gobs-cli project for Windows cmds: - - GOOS=windows GOARCH=amd64 go build -ldflags "-X 'main.version=debug'" -o {{.BIN_DIR}}/{{.PROGRAM}}_windows_amd64.exe + - GOOS=windows GOARCH=amd64 go build -ldflags "-X 'main.version={{.VERSION}}'" -o {{.BIN_DIR}}/{{.PROGRAM}}_windows_amd64.exe internal: true build-linux: desc: Build the gobs-cli project for Linux cmds: - - GOOS=linux GOARCH=amd64 go build -ldflags "-X 'main.version=debug'" -o {{.BIN_DIR}}/{{.PROGRAM}}_linux_amd64 + - GOOS=linux GOARCH=amd64 go build -ldflags "-X 'main.version={{.VERSION}}'" -o {{.BIN_DIR}}/{{.PROGRAM}}_linux_amd64 internal: true test: diff --git a/version.go b/version.go index edc7ac8..4abfc6e 100644 --- a/version.go +++ b/version.go @@ -2,11 +2,13 @@ package main import ( "fmt" + "runtime/debug" + "strings" "github.com/alecthomas/kong" ) -var version = "unknown" +var version string // VersionFlag is a custom flag type for displaying version information. type VersionFlag string @@ -19,6 +21,14 @@ func (v VersionFlag) IsBool() bool { return true } // BeforeApply implements the kong.Flag interface for VersionFlag. func (v VersionFlag) BeforeApply(app *kong.Kong, _ kong.Vars) error { // nolint: unparam + if version == "" { + info, ok := debug.ReadBuildInfo() + if !ok { + return fmt.Errorf("failed to read build info") + } + version = strings.Split(info.Main.Version, "-")[0] + } + fmt.Printf("gobs-cli version: %s\n", version) app.Exit(0) // Exit the application after printing the version return nil