package buildinfo import ( "fmt" "io" "os" "path/filepath" "runtime/debug" "strings" "text/template" ) var ( Name string = "" Version string = "" Commit string = "" BuildTime string = "" OS string = "" Arch string = "" ShowDeps bool = true dependencies = []Dep{} PrintFormat = ` {{- block "version" . -}} {{- if .Name -}} {{- .Name -}} {{- end }} {{- if .Version }} {{ .Version -}} {{- end }} {{- if and (.OS) (.Arch) }} {{ .OS -}} / {{- .Arch -}} {{- end }} {{- if (.BuildTime) }} (built at {{ .BuildTime -}}) {{- end }} {{- if and (not .Version) (.Commit) (not .BuildTime) }} (commit {{ .Commit -}}) {{- end }} {{- if and (not .Version) (.Commit) (.BuildTime) }} (commit {{ .Commit }} built at {{ .BuildTime -}}) {{- end }} {{- if and (not .Version) (not .Commit) (.BuildTime) }} (built at {{ .BuildTime -}}) {{- end }} {{ end -}} {{- block "deps" . -}} {{- if and (.ShowDeps) (len .Deps) -}} dependecies: {{- range .Deps }} {{ .Name }} {{ .Version -}} {{- end -}} {{- end -}} {{- end }} ` ) var ( fmtTmpl = template.Must(template.New("print-format").Parse(PrintFormat)) ) func Print() { Fprint(os.Stdout) } func Fprint(w io.Writer) { if Name == "" { Name = filepath.Base(os.Args[0]) } if OS == "" || Arch == "" || ShowDeps { fillDebugInfo() } b := new(strings.Builder) err := fmtTmpl.Execute(b, newBuildInfo()) if err != nil { panic(err) } fmt.Fprintln(w, strings.TrimSpace(b.String())) } 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 { dependencies = append(dependencies, Dep{ Name: dep.Path, Version: dep.Version, Sum: dep.Sum, }) } }