aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorMichael Muré <batolettre@gmail.com>2023-01-19 11:12:13 +0100
committerGitHub <noreply@github.com>2023-01-19 11:12:13 +0100
commit06e8396e6fe83c691bbdfd74cfdd6bc28a0d20f1 (patch)
treeb0dac3095804a7e601a31e8801ea878a8b243d34
parenta35bd4cda22586a35caf9529c1e51ec641b9168e (diff)
parent5238d1ddee0dfee027ca9a4831dfd77931d8ec71 (diff)
downloadgit-bug-06e8396e6fe83c691bbdfd74cfdd6bc28a0d20f1.tar.gz
Merge pull request #991 from vasser/fix/issue-928-version-info
Fixed version info be set when go install
-rw-r--r--commands/root.go65
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
+}