buildinfo/version.go

81 lines
1.3 KiB
Go
Raw Normal View History

2022-08-29 01:24:57 +02:00
package main
import (
"fmt"
"io"
"os"
"runtime/debug"
)
var (
Name string = ""
Version string = ""
Commit string = ""
BuildTime string = ""
OS string = ""
Arch string = ""
ShowDeps bool = false
dependencies = []string{}
)
func main() {
Print()
}
func Fprint(w io.Writer) {
if OS == "" || Arch == "" || ShowDeps {
fillDebugInfo()
}
if Name == "" {
return
}
if Version != "" {
fmt.Fprintf(w, "%s %s (built for %s/%s at %s)\n", Name, Version, OS, Arch, BuildTime)
} else if Commit != "" {
fmt.Fprintf(w, "%s (commit %s) (built at %s)\n", Name, Commit, BuildTime)
}
if ShowDeps {
fmt.Println("\ndependencies:")
for _, dep := range dependencies {
fmt.Fprintf(w, " %s\n", dep)
}
}
}
func Print() {
Fprint(os.Stdout)
}
func overwriteValueIfEmpty(value *string, newValue string) {
if *value == "" {
*value = newValue
}
}
func fillDebugInfo() {
info, ok := debug.ReadBuildInfo()
if !ok {
return
}
for _, setting := range info.Settings {
switch setting.Key {
case "GOOS":
overwriteValueIfEmpty(&OS, setting.Value)
case "GOARCH":
overwriteValueIfEmpty(&Arch, setting.Value)
case "vcs.revision":
overwriteValueIfEmpty(&Commit, setting.Value)
}
}
for _, dep := range info.Deps {
str := fmt.Sprintf("%s %s", dep.Path, dep.Version)
dependencies = append(dependencies, str)
}
}