Merge pull request #991 from vasser/fix/issue-928-version-info

Fixed version info be set when go install
This commit is contained in:
Michael Muré 2023-01-19 11:12:13 +01:00 committed by GitHub
commit 06e8396e6f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -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
}