cmd/tilstream/cmd/version.go

package cmd

import (
	"fmt"
	"runtime"
	"runtime/debug"

	"github.com/spf13/cobra"
)

// These are overridden by -ldflags at release time.
var (
	Version   = "dev"
	Commit    = "unknown"
	BuildDate = "unknown"
)

var versionCmd = &cobra.Command{
	Use:   "version",
	Short: "Print version information",
	RunE:  runVersion,
}

func runVersion(cmd *cobra.Command, args []string) error {
	info := Info()
	fmt.Fprintln(cmd.OutOrStdout(), info)
	return nil
}

// Info returns a human-readable version string.
func Info() string {
	commit := Commit
	if commit == "unknown" {
		if bi, ok := debug.ReadBuildInfo(); ok {
			for _, s := range bi.Settings {
				if s.Key == "vcs.revision" && s.Value != "" {
					commit = s.Value
					break
				}
			}
		}
	}
	return fmt.Sprintf("tilstream %s (commit %s, built %s, %s/%s)",
		Version, commit, BuildDate, runtime.GOOS, runtime.GOARCH)
}

// SetVersion overrides the compile-time Version from other packages. Used
// in tests that need a deterministic string.
func SetVersion(v, c, d string) {
	Version = v
	Commit = c
	BuildDate = d
}

// GoVersion exposes the Go runtime used at build time. Included in
// `tilstream doctor` output.
func GoVersion() string { return runtime.Version() }