2015-04-04 03:36:47 +00:00
|
|
|
package framework
|
|
|
|
|
|
|
|
import (
|
2015-04-04 04:00:23 +00:00
|
|
|
"bufio"
|
2015-04-04 03:36:47 +00:00
|
|
|
"bytes"
|
|
|
|
"strings"
|
|
|
|
"text/template"
|
2018-04-05 15:49:21 +00:00
|
|
|
|
|
|
|
"github.com/hashicorp/errwrap"
|
2015-04-04 03:36:47 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
func executeTemplate(tpl string, data interface{}) (string, error) {
|
2015-04-04 04:00:23 +00:00
|
|
|
// Define the functions
|
|
|
|
funcs := map[string]interface{}{
|
|
|
|
"indent": funcIndent,
|
|
|
|
}
|
|
|
|
|
2015-04-04 03:36:47 +00:00
|
|
|
// Parse the help template
|
2015-04-04 04:00:23 +00:00
|
|
|
t, err := template.New("root").Funcs(funcs).Parse(tpl)
|
2015-04-04 03:36:47 +00:00
|
|
|
if err != nil {
|
2018-04-05 15:49:21 +00:00
|
|
|
return "", errwrap.Wrapf("error parsing template: {{err}}", err)
|
2015-04-04 03:36:47 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Execute the template and store the output
|
|
|
|
var buf bytes.Buffer
|
|
|
|
if err := t.Execute(&buf, data); err != nil {
|
2018-04-05 15:49:21 +00:00
|
|
|
return "", errwrap.Wrapf("error executing template: {{err}}", err)
|
2015-04-04 03:36:47 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return strings.TrimSpace(buf.String()), nil
|
|
|
|
}
|
2015-04-04 04:00:23 +00:00
|
|
|
|
|
|
|
func funcIndent(count int, text string) string {
|
|
|
|
var buf bytes.Buffer
|
|
|
|
prefix := strings.Repeat(" ", count)
|
|
|
|
scan := bufio.NewScanner(strings.NewReader(text))
|
|
|
|
for scan.Scan() {
|
|
|
|
buf.WriteString(prefix + scan.Text() + "\n")
|
|
|
|
}
|
|
|
|
|
|
|
|
return strings.TrimRight(buf.String(), "\n")
|
|
|
|
}
|