1package version // import "go.hein.dev/go-version" 2 3import ( 4 "encoding/json" 5 "fmt" 6 7 "sigs.k8s.io/yaml" 8) 9 10var ( 11 // JSON returns json so that we can change the output 12 JSON = "json" 13 // YAML returns yaml so that we can change the output 14 YAML = "yaml" 15) 16 17// Info creates a formattable struct for output 18type Info struct { 19 Version string `json:"Version,omitempty"` 20 Commit string `json:"Commit,omitempty"` 21 Date string `json:"Date,omitempty"` 22} 23 24// New will create a pointer to a new version object 25func New(version string, commit string, date string) *Info { 26 return &Info{ 27 Version: version, 28 Commit: commit, 29 Date: date, 30 } 31} 32 33// Func will return the versioning code with only JSON and raw text support 34func Func(shortened bool, version, commit, date string) string { 35 return FuncWithOutput(shortened, version, commit, date, JSON) 36} 37 38// FuncWithOutput will add the versioning code 39func FuncWithOutput(shortened bool, version, commit, date, output string) string { 40 var response string 41 versionOutput := New(version, commit, date) 42 43 if shortened { 44 response = versionOutput.ToShortened() 45 } else { 46 switch output { 47 case YAML: 48 response = versionOutput.ToYAML() 49 case JSON: 50 response = versionOutput.ToJSON() 51 default: // JSON as the default 52 response = versionOutput.ToJSON() 53 } 54 } 55 return fmt.Sprintf("%s", response) 56} 57 58// ToJSON converts the Info into a JSON String 59func (v *Info) ToJSON() string { 60 bytes, _ := json.Marshal(v) 61 return string(bytes) + "\n" 62} 63 64// ToYAML converts the Info into a JSON String 65func (v *Info) ToYAML() string { 66 bytes, _ := yaml.Marshal(v) 67 return string(bytes) 68} 69 70// ToShortened converts the Info into a JSON String 71func (v *Info) ToShortened() string { 72 return v.ToYAML() 73} 74 75func deleteEmpty(s []string) []string { 76 var r []string 77 for _, str := range s { 78 if str != "" { 79 r = append(r, str) 80 } 81 } 82 return r 83} 84