diff --git a/bee.go b/bee.go index cda8ac4..840bf50 100644 --- a/bee.go +++ b/bee.go @@ -18,11 +18,11 @@ package main import ( "flag" "fmt" - "html/template" "io" "log" "os" "strings" + "text/template" ) const version = "1.5.2" @@ -41,10 +41,10 @@ type Command struct { UsageLine string // Short is the short description shown in the 'go help' output. - Short template.HTML + Short string // Long is the long message shown in the 'go help ' output. - Long template.HTML + Long string // Flag is a set of flags specific to this command. Flag flag.FlagSet @@ -189,7 +189,7 @@ var helpTemplate = `{{"USAGE" | headline}} {{if .Options}}{{endline}}{{"OPTIONS" | headline}}{{range $k,$v := .Options}} {{$k | printf "-%-11s" | bold}} {{$v}}{{end}}{{endline}}{{end}} {{"DESCRIPTION" | headline}} - {{.Long | trim}} + {{tmpltostr .Long . | trim}} ` var errorTemplate = `bee: %s. @@ -204,18 +204,11 @@ func usage() { func tmpl(text string, data interface{}) { output := NewColorWriter(os.Stderr) - t := template.New("top") - t.Funcs(template.FuncMap{ - "trim": func(s template.HTML) template.HTML { return template.HTML(strings.TrimSpace(string(s))) }, - "bold": bold, - "headline": MagentaBold, - "endline": EndLine, - }) - + t := template.New("usage").Funcs(BeeFuncMap()) template.Must(t.Parse(text)) - if err := t.Execute(output, data); err != nil { - panic(err) - } + + err := t.Execute(output, data) + MustCheck(err) } func help(args []string) { diff --git a/util.go b/util.go index a13ade2..fcfaeca 100644 --- a/util.go +++ b/util.go @@ -15,6 +15,7 @@ package main import ( + "bytes" "fmt" "io/ioutil" "os" @@ -24,6 +25,7 @@ import ( "regexp" "runtime" "strings" + "text/template" "time" ) @@ -281,3 +283,26 @@ func __LINE__() int { _, _, line, _ := runtime.Caller(1) return line } + +// BeeFuncMap returns a FuncMap of functions used in different templates. +func BeeFuncMap() template.FuncMap { + return template.FuncMap{ + "trim": strings.TrimSpace, + "bold": bold, + "headline": MagentaBold, + "endline": EndLine, + "tmpltostr": TmplToString, + } +} + +// TmplToString parses a text template and return the result as a string. +func TmplToString(tmpl string, data interface{}) string { + t := template.New("tmpl").Funcs(BeeFuncMap()) + template.Must(t.Parse(tmpl)) + + var doc bytes.Buffer + err := t.Execute(&doc, data) + MustCheck(err) + + return doc.String() +}