From b0f618e21de14af902a587efc90e036680b97617 Mon Sep 17 00:00:00 2001 From: Takumi Katase <50615605+devoc09@users.noreply.github.com> Date: Sun, 10 Dec 2023 07:50:24 +0900 Subject: [PATCH] refactor(builder): change output of `version` subcommand. (#8994) With this change, running `builder version` on binaries installed with `go install` will output the version specified at the suffix. If it's under development, the following output will be obtained. ``` $ GO111MODULE=on CGO_ENABLED=0 go run . version ocb version (devel) ``` **Link to tracking Issue:** #8770 --------- Co-authored-by: Bogdan Drutu --- .chloggen/output_version_of_binary.yaml | 12 ++++++++++++ cmd/builder/internal/version.go | 24 ++++++++++++++++++++++-- 2 files changed, 34 insertions(+), 2 deletions(-) create mode 100755 .chloggen/output_version_of_binary.yaml diff --git a/.chloggen/output_version_of_binary.yaml b/.chloggen/output_version_of_binary.yaml new file mode 100755 index 00000000000..3ee2fb784c9 --- /dev/null +++ b/.chloggen/output_version_of_binary.yaml @@ -0,0 +1,12 @@ + +change_type: enhancement + +component: cmd/builder + +note: "running builder version on binaries installed with `go install` will output the version specified at the suffix." + +issues: [8770] + +subtext: + +change_logs: [user] diff --git a/cmd/builder/internal/version.go b/cmd/builder/internal/version.go index be1fe805b2b..7ffabed75fc 100644 --- a/cmd/builder/internal/version.go +++ b/cmd/builder/internal/version.go @@ -5,22 +5,42 @@ package internal // import "go.opentelemetry.io/collector/cmd/builder/internal" import ( "fmt" + "runtime/debug" "github.com/spf13/cobra" ) var ( - version = "dev" + version = "" date = "unknown" ) +// binVersion returns the version of the binary. +// If the version is not set, it attempts to read the build information. +// Returns an error if the build information cannot be read. +func binVersion() (string, error) { + if version != "" { + return version, nil + } + info, ok := debug.ReadBuildInfo() + if !ok { + return "", fmt.Errorf("failed to read build info") + } + return info.Main.Version, nil +} + func versionCommand() *cobra.Command { return &cobra.Command{ Use: "version", Short: "Version of ocb", Long: "Prints the version of the ocb binary", - Run: func(cmd *cobra.Command, args []string) { + RunE: func(cmd *cobra.Command, args []string) error { + version, err := binVersion() + if err != nil { + return err + } cmd.Println(fmt.Sprintf("%s version %s", cmd.Parent().Name(), version)) + return nil }, } }