|
1 | 1 | package util |
2 | 2 |
|
3 | 3 | import ( |
| 4 | + "runtime/debug" |
4 | 5 | "strings" |
5 | 6 | ) |
6 | 7 |
|
7 | | -const ( |
8 | | - defaultVersion = "dev" |
9 | | - defaultCommit = "none" |
10 | | - defaultDatetime = "none" |
11 | | -) |
12 | | - |
13 | 8 | var ( |
14 | 9 | // Use the following command to change this value: |
15 | 10 | // go build -ldflags "-X github.com/cqfn/refrax/internal/util.version=<version>" |
16 | | - version string = defaultVersion |
| 11 | + version string = "" |
17 | 12 |
|
18 | 13 | // Use the following command to change this value: |
19 | 14 | // go build -ldflags "-X github.com/cqfn/refrax/internal/util.commit=<commit-hash>" |
20 | | - commit string = defaultCommit |
| 15 | + commit string = "" |
21 | 16 |
|
22 | 17 | // Use the following command to change this value: |
23 | 18 | // go build -ldflags "-X github.com/cqfn/refrax/internal/util.datetime=<date-time>" |
24 | | - datetime string = defaultDatetime |
| 19 | + datetime string = "" |
25 | 20 | ) |
26 | 21 |
|
27 | 22 | func Version() string { |
28 | | - parts := []string{version} |
29 | | - if commit != defaultCommit { |
30 | | - parts = append(parts, "commit", commit) |
| 23 | + info := info() |
| 24 | + parts := []string{ver(info)} |
| 25 | + rev := revision(info) |
| 26 | + if rev != "" { |
| 27 | + parts = append(parts, "commit", rev) |
31 | 28 | } |
32 | | - if datetime != defaultDatetime { |
33 | | - parts = append(parts, "built at", datetime) |
| 29 | + time := timestamp(info) |
| 30 | + if time != "" { |
| 31 | + parts = append(parts, "built at", time) |
34 | 32 | } |
35 | 33 | return strings.Join(parts, " ") |
36 | 34 | } |
| 35 | + |
| 36 | +func ver(info map[string]string) string { |
| 37 | + if version != "" { |
| 38 | + return version |
| 39 | + } |
| 40 | + if iver, ok := info["version"]; ok { |
| 41 | + return iver |
| 42 | + } |
| 43 | + return "dev" |
| 44 | +} |
| 45 | + |
| 46 | +func revision(info map[string]string) string { |
| 47 | + if commit != "" { |
| 48 | + return commit |
| 49 | + } |
| 50 | + if rev, ok := info["vcs.revision"]; ok { |
| 51 | + return rev |
| 52 | + } |
| 53 | + return "" |
| 54 | +} |
| 55 | + |
| 56 | +func timestamp(info map[string]string) string { |
| 57 | + if datetime != "" { |
| 58 | + return datetime |
| 59 | + } |
| 60 | + if time, ok := info["vcs.time"]; ok { |
| 61 | + return time |
| 62 | + } |
| 63 | + return "" |
| 64 | +} |
| 65 | + |
| 66 | +func info() map[string]string { |
| 67 | + info, ok := debug.ReadBuildInfo() |
| 68 | + if !ok { |
| 69 | + panic("failed to read build info") |
| 70 | + } |
| 71 | + settings := make(map[string]string) |
| 72 | + for _, s := range info.Settings { |
| 73 | + settings[s.Key] = s.Value |
| 74 | + } |
| 75 | + vcsver := info.Main.Version |
| 76 | + if vcsver != "" && vcsver != "(devel)" { |
| 77 | + settings["version"] = vcsver |
| 78 | + } |
| 79 | + return settings |
| 80 | +} |
0 commit comments