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 }, } }