feat: version command respects verbose flag (#61)

This commit is contained in:
lkingland 2020-08-14 06:05:59 +09:00 committed by GitHub
parent ea7fe15376
commit 4c3a276c2f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 37 additions and 13 deletions

View File

@ -58,7 +58,7 @@ func init() {
// Environment Variables, command arguments and flags.
func Execute() {
// Sets version to a string partially populated by compile-time flags.
root.Version = verboseVersion()
root.Version = version(verbose)
// Execute the root of the command tree.
if err := root.Execute(); err != nil {

View File

@ -2,7 +2,9 @@ package cmd
import (
"fmt"
"strings"
"github.com/ory/viper"
"github.com/spf13/cobra"
)
@ -12,19 +14,19 @@ func init() {
var versionCmd = &cobra.Command{
Use: "version",
Short: "Print version",
Run: version,
Short: "Print version. With --verbose the build date stamp and commit hash are included if available.",
Run: printVersion,
}
func version(cmd *cobra.Command, args []string) {
fmt.Println(verboseVersion())
func printVersion(cmd *cobra.Command, args []string) {
fmt.Println(version(viper.GetBool("verbose")))
}
// Populated at build time by `make build`, plumbed through
// main using SetMeta()
var (
date string // datestamp
vers string // verstionof git commit or `tip`
vers string // version of git commit or `tip`
hash string // git hash built from
)
@ -35,12 +37,34 @@ func SetMeta(buildTimestamp, commitVersionTag, commitHash string) {
hash = commitHash
}
func verboseVersion() string {
// If building from source (i.e. from `go install` or `go build` directly,
// simply print 'v0.0.0-source`, a semver-valid version indicating no version
// number. Otherwise print the verbose version populated during `make build`.
if vers == "" { // not statically populatd
return "v0.0.0-source"
// return the version, optionally with verbose details as the suffix
func version(verbose bool) string {
// If 'vers' is not a semver already, then the binary was built either
// from an untagged git commit (set semver to v0.0.0), or was built
// directly from source (set semver to v0.0.0-source).
if strings.HasPrefix(vers, "v") {
// Was built via make with a tagged commit
if verbose {
return fmt.Sprintf("%s-%s-%s", vers, hash, date)
} else {
return vers
}
} else if vers == "tip" {
// Was built via make from an untagged commit
vers = "v0.0.0"
if verbose {
return fmt.Sprintf("%s-%s-%s", vers, hash, date)
} else {
return vers
}
} else {
// Was likely built from source
vers = "v0.0.0"
hash = "source"
if verbose {
return fmt.Sprintf("%s-%s", vers, hash)
} else {
return vers
}
}
return fmt.Sprintf("%s-%s-%s", vers, date, hash)
}