Skip to content

Commit

Permalink
refactor(builder): change output of version subcommand.
Browse files Browse the repository at this point in the history
If version information has not been inserted by `ldflags`,
the build information embedded in the binary being executed is output.

Return an error when failing to retrieve the version, and to use cobra's `RunE`.
  • Loading branch information
Takumi Katase committed Nov 28, 2023
1 parent 4966509 commit d0953f9
Showing 1 changed file with 22 additions and 2 deletions.
24 changes: 22 additions & 2 deletions cmd/builder/internal/version.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
},
}
}

0 comments on commit d0953f9

Please sign in to comment.