github.com/hashicorp/vault/sdk@v0.13.0/framework/template.go (about) 1 // Copyright (c) HashiCorp, Inc. 2 // SPDX-License-Identifier: MPL-2.0 3 4 package framework 5 6 import ( 7 "bufio" 8 "bytes" 9 "strings" 10 "text/template" 11 12 "github.com/hashicorp/errwrap" 13 ) 14 15 func executeTemplate(tpl string, data interface{}) (string, error) { 16 // Define the functions 17 funcs := map[string]interface{}{ 18 "indent": funcIndent, 19 } 20 21 // Parse the help template 22 t, err := template.New("root").Funcs(funcs).Parse(tpl) 23 if err != nil { 24 return "", errwrap.Wrapf("error parsing template: {{err}}", err) 25 } 26 27 // Execute the template and store the output 28 var buf bytes.Buffer 29 if err := t.Execute(&buf, data); err != nil { 30 return "", errwrap.Wrapf("error executing template: {{err}}", err) 31 } 32 33 return strings.TrimSpace(buf.String()), nil 34 } 35 36 func funcIndent(count int, text string) string { 37 var buf bytes.Buffer 38 prefix := strings.Repeat(" ", count) 39 scan := bufio.NewScanner(strings.NewReader(text)) 40 for scan.Scan() { 41 buf.WriteString(prefix + scan.Text() + "\n") 42 } 43 44 return strings.TrimRight(buf.String(), "\n") 45 }