From f505b9a4327b5eec5579ceaa067962fc06f09fcd Mon Sep 17 00:00:00 2001 From: Pete Cornish Date: Sun, 21 Jun 2026 01:11:09 +0100 Subject: [PATCH] feat: support --version flag to print built version Add a Version variable in cmd/root.go that defaults to 'dev' and can be overridden at build time via ldflags -X. Wire it into Cobra's built-in --version flag, and inject the version in .goreleaser.yml and Dockerfile so released binaries include the correct version. --- .goreleaser.yml | 2 ++ Dockerfile | 3 ++- Makefile | 4 +++- cmd/root.go | 3 +++ 4 files changed, 10 insertions(+), 2 deletions(-) diff --git a/.goreleaser.yml b/.goreleaser.yml index 3eea0e0..f134bdb 100644 --- a/.goreleaser.yml +++ b/.goreleaser.yml @@ -5,6 +5,8 @@ before: builds: - env: - CGO_ENABLED=0 + ldflags: + - -s -w -X github.com/release-tools/since/cmd.Version={{ .Version }} goos: - linux - windows diff --git a/Dockerfile b/Dockerfile index 7408b33..7dc4d33 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,5 +1,6 @@ FROM golang:1.20 AS builder +ARG VERSION=dev WORKDIR /src COPY go.mod go.sum ./ @@ -7,7 +8,7 @@ RUN go mod download COPY . . -RUN CGO_ENABLED=0 go build -ldflags="-s -w" -o /since +RUN CGO_ENABLED=0 go build -ldflags="-s -w -X github.com/release-tools/since/cmd.Version=${VERSION}" -o /since FROM scratch diff --git a/Makefile b/Makefile index 3a3ca3d..101179e 100644 --- a/Makefile +++ b/Makefile @@ -1,8 +1,10 @@ export CGO_ENABLED ?= 0 +VERSION ?= dev + .PHONY: build build: - go build -o since + go build -ldflags="-s -w -X github.com/release-tools/since/cmd.Version=$(VERSION)" -o since .PHONY: fmt fmt: diff --git a/cmd/root.go b/cmd/root.go index b7f82f2..e6c9e51 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -23,6 +23,8 @@ import ( "os" ) +var Version = "dev" + var rootArgs struct { logLevel string quiet bool @@ -38,6 +40,7 @@ var rootCmd = &cobra.Command{ func init() { cobra.OnInitialize(initLogging) + rootCmd.Version = Version rootCmd.PersistentFlags().StringVarP(&rootArgs.logLevel, "log-level", "l", "debug", "Log level (debug, info, warn, error, fatal, panic)") rootCmd.PersistentFlags().BoolVarP(&rootArgs.quiet, "quiet", "q", false, "Disable logging (useful for scripting)") }