Skip to content

Commit

Permalink
Add commit ID to version output
Browse files Browse the repository at this point in the history
- 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 <[email protected]>
  • Loading branch information
mgoerens committed Jul 10, 2023
1 parent 4660b96 commit 1cb9515
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 1 deletion.
5 changes: 5 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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) .
Expand Down
30 changes: 29 additions & 1 deletion cmd/version.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package cmd

import (
_ "embed"
"encoding/json"
"fmt"
"io"
"os"
Expand All @@ -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())
}

// CommitIDLong contains the commit ID the binary was build on. It 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.Fprint(out, string(marshalledVersion))
} else {
fmt.Fprintf(out, "chart-verifier v%s <commit: %s>\n", apiversion.GetVersion(), CommitIDLong)
}
return nil
}

0 comments on commit 1cb9515

Please sign in to comment.