diff options
Diffstat (limited to 'commands')
-rw-r--r-- | commands/root.go | 65 |
1 files changed, 57 insertions, 8 deletions
diff --git a/commands/root.go b/commands/root.go index aace1956..01c817ee 100644 --- a/commands/root.go +++ b/commands/root.go @@ -4,6 +4,7 @@ package commands import ( "fmt" "os" + "runtime/debug" "github.com/spf13/cobra" @@ -32,14 +33,7 @@ the same git remote you are already using to collaborate with other people. PersistentPreRun: func(cmd *cobra.Command, args []string) { root := cmd.Root() - - if GitExactTag == "undefined" { - GitExactTag = "" - } - root.Version = GitLastTag - if GitExactTag == "" { - root.Version = fmt.Sprintf("%s-dev-%.10s", root.Version, GitCommit) - } + root.Version = getVersion() }, // For the root command, force the execution of the PreRun @@ -93,3 +87,58 @@ func Execute() { os.Exit(1) } } + +func getVersion() string { + if GitExactTag == "undefined" { + GitExactTag = "" + } + + if GitExactTag != "" { + // we are exactly on a tag --> release version + return GitLastTag + } + + if GitLastTag != "" { + // not exactly on a tag --> dev version + return fmt.Sprintf("%s-dev-%.10s", GitLastTag, GitCommit) + } + + // we don't have commit information, try golang build info + if commit, dirty, err := getCommitAndDirty(); err == nil { + if dirty { + return fmt.Sprintf("dev-%.10s-dirty", commit) + } + return fmt.Sprintf("dev-%.10s", commit) + } + + return "dev-unknown" +} + +func getCommitAndDirty() (commit string, dirty bool, err error) { + info, ok := debug.ReadBuildInfo() + if !ok { + return "", false, fmt.Errorf("unable to read build info") + } + + var commitFound bool + + // get the commit and modified status + // (that is the flag for repository dirty or not) + for _, kv := range info.Settings { + switch kv.Key { + case "vcs.revision": + commit = kv.Value + commitFound = true + case "vcs.modified": + if kv.Value == "true" { + dirty = true + } + } + } + + if !commitFound { + return "", false, fmt.Errorf("no commit found") + } + + return commit, dirty, nil +} |