Holger Hildebrandt | fa07499 | 2020-03-27 15:42:06 +0000 | [diff] [blame] | 1 | // Package version is used to inject build time information via -X variables |
| 2 | package version |
| 3 | |
| 4 | import ( |
| 5 | "fmt" |
| 6 | "io/ioutil" |
| 7 | "strings" |
| 8 | |
| 9 | "github.com/opencord/voltha-lib-go/v3/pkg/log" |
| 10 | ) |
| 11 | |
| 12 | // Default build-time variable. |
| 13 | // These values can (should) be overridden via ldflags when built with |
| 14 | // `make` |
| 15 | var ( |
| 16 | version = "unknown-version" |
| 17 | goVersion = "unknown-goversion" |
| 18 | vcsRef = "unknown-vcsref" |
| 19 | vcsDirty = "unknown-vcsdirty" |
| 20 | buildTime = "unknown-buildtime" |
| 21 | os = "unknown-os" |
| 22 | arch = "unknown-arch" |
| 23 | ) |
| 24 | |
| 25 | // InfoType is a collection of build time environment variables |
| 26 | type InfoType struct { |
| 27 | Version string `json:"version"` |
| 28 | GoVersion string `json:"goversion"` |
| 29 | VcsRef string `json:"vcsref"` |
| 30 | VcsDirty string `json:"vcsdirty"` |
| 31 | BuildTime string `json:"buildtime"` |
| 32 | Os string `json:"os"` |
| 33 | Arch string `json:"arch"` |
| 34 | } |
| 35 | |
| 36 | // VersionInfo is an instance of build time environment variables populated at build time via -X arguments |
| 37 | var VersionInfo InfoType |
| 38 | |
| 39 | func init() { |
| 40 | VersionInfo = InfoType{ |
| 41 | Version: version, |
| 42 | VcsRef: vcsRef, |
| 43 | VcsDirty: vcsDirty, |
| 44 | GoVersion: goVersion, |
| 45 | Os: os, |
| 46 | Arch: arch, |
| 47 | BuildTime: buildTime, |
| 48 | } |
| 49 | _, _ = log.AddPackage(log.CONSOLE, log.DebugLevel, nil) |
| 50 | } |
| 51 | |
| 52 | func (v InfoType) String(indent string) string { |
| 53 | builder := strings.Builder{} |
| 54 | |
| 55 | builder.WriteString(fmt.Sprintf("%sVersion: %s\n", indent, VersionInfo.Version)) |
| 56 | builder.WriteString(fmt.Sprintf("%sGoVersion: %s\n", indent, VersionInfo.GoVersion)) |
| 57 | builder.WriteString(fmt.Sprintf("%sVCS Ref: %s\n", indent, VersionInfo.VcsRef)) |
| 58 | builder.WriteString(fmt.Sprintf("%sVCS Dirty: %s\n", indent, VersionInfo.VcsDirty)) |
| 59 | builder.WriteString(fmt.Sprintf("%sBuilt: %s\n", indent, VersionInfo.BuildTime)) |
| 60 | builder.WriteString(fmt.Sprintf("%sOS/Arch: %s/%s\n", indent, VersionInfo.Os, VersionInfo.Arch)) |
| 61 | return builder.String() |
| 62 | } |
| 63 | |
| 64 | func GetCodeVersion() string { |
| 65 | if VersionInfo.Version == "unknown-version" { |
| 66 | content, err := ioutil.ReadFile("VERSION") |
| 67 | if err == nil { |
| 68 | return (string(content)) |
| 69 | } else { |
| 70 | log.Error("VERSION-file not readable") |
| 71 | return VersionInfo.Version |
| 72 | } |
| 73 | } else { |
| 74 | return VersionInfo.Version |
| 75 | } |
| 76 | } |