diff --git a/buildInfo.go b/buildInfo.go new file mode 100644 index 0000000..5daefa4 --- /dev/null +++ b/buildInfo.go @@ -0,0 +1,31 @@ +package buildinfo + +type buildInfo struct { + Name string + Version string + Commit string + BuildTime string + OS string + Arch string + ShowDeps bool + Deps []Dep +} + +type Dep struct { + Name string + Version string + Sum string +} + +func newBuildInfo() *buildInfo { + return &buildInfo{ + Name: Name, + Version: Version, + Commit: Commit, + BuildTime: BuildTime, + OS: OS, + Arch: Arch, + Deps: dependencies, + ShowDeps: ShowDeps, + } +} diff --git a/version.go b/version.go index 5064793..b7230bf 100644 --- a/version.go +++ b/version.go @@ -1,10 +1,13 @@ -package main +package buildinfo import ( "fmt" "io" "os" + "path/filepath" "runtime/debug" + "strings" + "text/template" ) var ( @@ -14,40 +17,58 @@ var ( BuildTime string = "" OS string = "" Arch string = "" - ShowDeps bool = false + ShowDeps bool = true - dependencies = []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 }} +` ) -func main() { - Print() +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() } - if Name == "" { - return + b := new(strings.Builder) + + err := fmtTmpl.Execute(b, newBuildInfo()) + if err != nil { + panic(err) } - 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) + fmt.Fprintln(w, strings.TrimSpace(b.String())) } func overwriteValueIfEmpty(value *string, newValue string) { @@ -74,7 +95,10 @@ func fillDebugInfo() { } for _, dep := range info.Deps { - str := fmt.Sprintf("%s %s", dep.Path, dep.Version) - dependencies = append(dependencies, str) + dependencies = append(dependencies, Dep{ + Name: dep.Path, + Version: dep.Version, + Sum: dep.Sum, + }) } }