package cmd import ( "fmt" "runtime" "runtime/debug" "github.com/spf13/cobra" ) // Build metadata — overridden via -ldflags at release time. // // go build -ldflags "-X anchorage/internal/cmd.version=v0.1.0 -X anchorage/internal/cmd.commit= -X anchorage/internal/cmd.date=" var ( version = "dev" commit = "" date = "" ) // newVersionCmd prints build metadata and exits. // // Falls back to debug.ReadBuildInfo() for commit/date so `go install` and // `go run` produce useful output even without ldflags. func newVersionCmd() *cobra.Command { return &cobra.Command{ Use: "version", Short: "Print anchorage version and build metadata", Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, _ []string) error { v, c, d := resolveBuildInfo() out := cmd.OutOrStdout() fmt.Fprintf(out, "anchorage %s\n", v) if c != "" { fmt.Fprintf(out, " commit: %s\n", c) } if d != "" { fmt.Fprintf(out, " built: %s\n", d) } fmt.Fprintf(out, " runtime: %s %s/%s\n", runtime.Version(), runtime.GOOS, runtime.GOARCH) return nil }, } } // resolveBuildInfo prefers ldflag-injected values and falls back to the // module's embedded vcs info when unset. func resolveBuildInfo() (v, c, d string) { v, c, d = version, commit, date if c != "" && d != "" { return } info, ok := debug.ReadBuildInfo() if !ok { return } for _, s := range info.Settings { switch s.Key { case "vcs.revision": if c == "" { c = s.Value } case "vcs.time": if d == "" { d = s.Value } } } return }