|
1 | 1 | package version |
2 | 2 |
|
3 | 3 | import ( |
4 | | - "fmt" |
| 4 | + _ "embed" |
5 | 5 | "runtime/debug" |
| 6 | + "strings" |
6 | 7 | ) |
7 | 8 |
|
8 | 9 | var ( |
9 | | - version = "" |
10 | | - sum = "" |
| 10 | + //go:embed version.txt |
| 11 | + version string |
| 12 | + commit string |
| 13 | + dirty bool |
11 | 14 | ) |
12 | 15 |
|
13 | 16 | func init() { |
14 | | - info, ok := debug.ReadBuildInfo() |
15 | | - if !ok || info.Main.Version == "(devel)" || info.Main.Version == "" { |
16 | | - version = "unknown" |
17 | | - } else { |
18 | | - if version == "" { |
19 | | - version = info.Main.Version |
| 17 | + version = strings.TrimSpace(version) |
| 18 | + // Attempt to get build info from the Go runtime. We only use this if not |
| 19 | + // built from a tagged version. |
| 20 | + if info, ok := debug.ReadBuildInfo(); ok && info.Main.Version == "(devel)" { |
| 21 | + commit = getCommit(info) |
| 22 | + dirty = getDirty(info) |
| 23 | + } |
| 24 | +} |
| 25 | + |
| 26 | +func getDirty(info *debug.BuildInfo) bool { |
| 27 | + for _, setting := range info.Settings { |
| 28 | + if setting.Key == "vcs.modified" { |
| 29 | + return setting.Value == "true" |
20 | 30 | } |
21 | | - if sum == "" { |
22 | | - sum = info.Main.Sum |
| 31 | + } |
| 32 | + return false |
| 33 | +} |
| 34 | + |
| 35 | +func getCommit(info *debug.BuildInfo) string { |
| 36 | + for _, setting := range info.Settings { |
| 37 | + if setting.Key == "vcs.revision" { |
| 38 | + return setting.Value[:7] |
23 | 39 | } |
24 | 40 | } |
| 41 | + return "" |
25 | 42 | } |
26 | 43 |
|
| 44 | +// GetVersion returns the version of Task. By default, this is retrieved from |
| 45 | +// the embedded version.txt file which is kept up-to-date by our release script. |
| 46 | +// However, it can also be overridden at build time using: |
| 47 | +// -ldflags="-X 'github.com/go-task/task/v3/internal/version.version=vX.X.X'". |
27 | 48 | func GetVersion() string { |
28 | 49 | return version |
29 | 50 | } |
30 | 51 |
|
31 | | -func GetVersionWithSum() string { |
32 | | - return fmt.Sprintf("%s (%s)", version, sum) |
| 52 | +// GetVersionWithBuildInfo is the same as [GetVersion], but it also includes |
| 53 | +// the commit hash and dirty status if available. This will only work when built |
| 54 | +// within inside of a Git checkout. |
| 55 | +func GetVersionWithBuildInfo() string { |
| 56 | + var buildInfo string |
| 57 | + if commit != "" { |
| 58 | + buildInfo += commit |
| 59 | + } |
| 60 | + if dirty { |
| 61 | + buildInfo += "-dirty" |
| 62 | + } |
| 63 | + if buildInfo != "" { |
| 64 | + return version + "-" + buildInfo |
| 65 | + } |
| 66 | + return version |
33 | 67 | } |
0 commit comments