commit b4077ca2249ca9945e131fa859c87d5f18199464 Author: Timon Ringwald Date: Mon Aug 29 01:24:57 2022 +0200 initial commit diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..986d59a --- /dev/null +++ b/go.mod @@ -0,0 +1,3 @@ +module git.milar.in/milarin/buildinfo + +go 1.19 diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..e69de29 diff --git a/version.go b/version.go new file mode 100644 index 0000000..5064793 --- /dev/null +++ b/version.go @@ -0,0 +1,80 @@ +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) + } +}