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 = "" 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(options Options) { Fprint(os.Stdout, options) } func Fprint(w io.Writer, options Options) { if Name == "" { Name = filepath.Base(os.Args[0]) } if OS == "" || Arch == "" || options.Deps { fillDebugInfo() } b := new(strings.Builder) err := fmtTmpl.Execute(b, newBuildInfo(options)) 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, }) } }