From 65d98982db8e53b5ce54a20a95dd5bfb0df5b86e Mon Sep 17 00:00:00 2001 From: mgoerens Date: Mon, 10 Jul 2023 14:24:39 +0200 Subject: [PATCH] Add commit ID to version output - add a "build" make target, which injects the git commit ID using ldflags - add the commit ID to the version output - add the possibility to get the version and commit information in a JSON format close #362 Signed-off-by: mgoerens --- Makefile | 5 +++++ cmd/version.go | 30 +++++++++++++++++++++++++++++- 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/Makefile b/Makefile index 2d4f8a9a..1bfb48db 100644 --- a/Makefile +++ b/Makefile @@ -3,6 +3,7 @@ IMAGE_BUILDER?=podman IMAGE_REPO?=quay.io/redhat-certification COMMIT_ID=$(shell git rev-parse --short HEAD) +COMMIT_ID_LONG=$(shell git rev-parse HEAD) default: bin @@ -47,6 +48,10 @@ bin_win: test: go test -v ./... +.PHONY: build +build: + go build -ldflags "-X 'github.com/redhat-certification/chart-verifier/cmd.CommitIdLong=$(COMMIT_ID_LONG)'" + .PHONY: build-image build-image: $(IMAGE_BUILDER) build -t $(IMAGE_REPO)/chart-verifier:$(COMMIT_ID) . diff --git a/cmd/version.go b/cmd/version.go index 5368c3f0..11afa431 100644 --- a/cmd/version.go +++ b/cmd/version.go @@ -2,6 +2,7 @@ package cmd import ( _ "embed" + "encoding/json" "fmt" "io" "os" @@ -11,23 +12,50 @@ import ( apiversion "github.com/redhat-certification/chart-verifier/pkg/chartverifier/version" ) +// Print version and commit ID as json blob +var asData bool + func init() { rootCmd.AddCommand(NewVersionCmd()) } +// This variable is populated at build time by ldflags. +// If you're running from a local debugger it will show an empty commit ID. +var CommitIdLong string + +type VersionContext struct { + Version string `json:"version"` + Commit string `json:"commit"` +} + +var Version = VersionContext{ + Version: apiversion.GetVersion(), + Commit: CommitIdLong, +} + func NewVersionCmd() *cobra.Command { cmd := &cobra.Command{ Use: "version", Short: "print the chart-verifier version information", + Long: "git commit information for this particular binary build is included at build time and can be accessed by this command", Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, args []string) error { return runVersion(os.Stdout) }, } + cmd.Flags().BoolVar(&asData, "as-data", false, "output the version and commit ID information in JSON format") return cmd } func runVersion(out io.Writer) error { - fmt.Fprintf(out, "v%s\n", apiversion.GetVersion()) + if asData { + marshalledVersion, err := json.Marshal(Version) + if err != nil { + return err + } + fmt.Fprintf(out, string(marshalledVersion)) + } else { + fmt.Fprintf(out, "chart-verifier v%s \n", apiversion.GetVersion(), CommitIdLong) + } return nil }