blob: ea2441d28883f893d206d93cf910005bfb940b68 [file] [log] [blame]
Holger Hildebrandtfa074992020-03-27 15:42:06 +00001// Package version is used to inject build time information via -X variables
2package version
3
4import (
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`
15var (
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
26type 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
37var VersionInfo InfoType
38
39func 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
52func (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
64func 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}