Skip to content

Commit cb2035d

Browse files
committed
Initial commit
0 parents  commit cb2035d

File tree

3 files changed

+78
-0
lines changed

3 files changed

+78
-0
lines changed

error.go

+7
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
package build
2+
3+
type BuildInfoError struct{}
4+
5+
func (e BuildInfoError) Error() string {
6+
return "unable to read build information"
7+
}

go.mod

+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
module github.com/go-asset/build
2+
3+
go 1.18

main.go

+68
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
package build
2+
3+
import (
4+
"fmt"
5+
"runtime/debug"
6+
"strings"
7+
)
8+
9+
// VersionInformation contains everything we know about our appliation.
10+
//
11+
// Actually, that's a lie, it does not contain everything (yet), but contains
12+
// a lot of information.
13+
type VersionInformation struct {
14+
AppName string
15+
Version string
16+
Time string
17+
Revision string
18+
Dirty bool
19+
}
20+
21+
func (info VersionInformation) String() string {
22+
parts := []string{}
23+
24+
if info.AppName != "" {
25+
parts = append(parts, info.AppName)
26+
}
27+
28+
if info.Version != "" {
29+
parts = append(parts, info.Version)
30+
} else if info.Revision != "" {
31+
parts = append(parts, info.Revision)
32+
}
33+
34+
if info.Dirty {
35+
parts = append(parts, "*dirty*")
36+
}
37+
38+
if info.Time != "" {
39+
parts = append(parts, fmt.Sprintf("(%s)", info.Time))
40+
}
41+
42+
return strings.Join(parts, " ")
43+
}
44+
45+
// ReadVersion reads build information and tried to create a VersionInformation
46+
// out of it.
47+
func ReadVersion(appName string) (VersionInformation, error) {
48+
version := VersionInformation{AppName: appName}
49+
50+
info, ok := debug.ReadBuildInfo()
51+
if !ok {
52+
return version, BuildInfoError{}
53+
}
54+
55+
for _, setting := range info.Settings {
56+
if setting.Key == "-ldflags" && strings.HasPrefix(setting.Value, "-buildid=") {
57+
version.Version = strings.TrimPrefix(setting.Value, "-buildid=")
58+
} else if setting.Key == "vcs.revision" {
59+
version.Revision = setting.Value
60+
} else if setting.Key == "vcs.time" {
61+
version.Time = setting.Value
62+
} else if setting.Key == "vcs.modified" {
63+
version.Dirty = true
64+
}
65+
}
66+
67+
return version, nil
68+
}

0 commit comments

Comments
 (0)