open-vault/sdk/framework/template.go

43 lines
952 B
Go
Raw Normal View History

2015-04-04 03:36:47 +00:00
package framework
import (
"bufio"
2015-04-04 03:36:47 +00:00
"bytes"
"strings"
"text/template"
"github.com/hashicorp/errwrap"
2015-04-04 03:36:47 +00:00
)
func executeTemplate(tpl string, data interface{}) (string, error) {
// Define the functions
funcs := map[string]interface{}{
"indent": funcIndent,
}
2015-04-04 03:36:47 +00:00
// Parse the help template
t, err := template.New("root").Funcs(funcs).Parse(tpl)
2015-04-04 03:36:47 +00:00
if err != nil {
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 {
return "", errwrap.Wrapf("error executing template: {{err}}", err)
2015-04-04 03:36:47 +00:00
}
return strings.TrimSpace(buf.String()), nil
}
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")
}