/
context_tmpl.go
150 lines (128 loc) · 4.25 KB
/
context_tmpl.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
package tmpl
import (
"bytes"
"fmt"
"path/filepath"
"strings"
"text/template"
"github.com/Masterminds/sprig/v3"
"github.com/pkg/errors"
)
const recursionMaxNums = 1000
// CreateFuncMap creates a template.FuncMap for the Context struct.
// It combines the functions from sprig.TxtFuncMap() with the functions
// defined in the Context's createFuncMap() method.
// It also adds aliases for certain functions based on the aliases map.
// The resulting FuncMap is returned.
func (c *Context) CreateFuncMap() template.FuncMap {
// function aliases
aliased := template.FuncMap{}
// map of function aliases
aliases := map[string]string{
"get": "sprigGet",
}
// get the default sprig functions
funcMap := sprig.TxtFuncMap()
// add aliases to the aliased FuncMap
for orig, alias := range aliases {
aliased[alias] = funcMap[orig]
}
// add functions from the Context's createFuncMap() method to the funcMap
for name, f := range c.createFuncMap() {
funcMap[name] = f
}
// add aliased functions to the funcMap
for name, f := range aliased {
funcMap[name] = f
}
return funcMap
}
type tplInfo struct {
name string
content string
}
// helperTPLs returns the contents of all files with names starting with "_" and ending with ".tpl"
// in the root directory of the Context. It reads each file and appends its content to the contents slice.
// If any error occurs during the file reading or globbing process, it returns an error.
func (c *Context) helperTPLs() ([]tplInfo, error) {
tplInfos := []tplInfo{}
files, err := c.fs.Glob(filepath.Join(c.basePath, "_*.tpl"))
if err != nil {
return nil, fmt.Errorf("failed to glob helper templates: %v", err)
}
for _, file := range files {
content, err := c.fs.ReadFile(file)
if err != nil {
return nil, fmt.Errorf("failed to read helper template %s: %v", file, err)
}
tplInfos = append(tplInfos, tplInfo{name: file, content: string(content)})
}
return tplInfos, nil
}
// newTemplate creates a new template based on the context.
// It initializes the template with the specified options and parses the helper templates.
// It also adds the 'include' function to the template's function map.
// The 'include' function allows including and rendering nested templates.
// The function returns the created template or an error if any occurred.
func (c *Context) newTemplate() (*template.Template, error) {
funcMap := c.CreateFuncMap()
tmpl := template.New("stringTemplate")
if c.preRender {
tmpl = tmpl.Option("missingkey=zero")
} else {
tmpl = tmpl.Option("missingkey=error")
}
includedNames := make(map[string]int)
// Add the 'include' function here so we can close over t.
funcMap["include"] = func(name string, data interface{}) (string, error) {
var buf strings.Builder
if v, ok := includedNames[name]; ok {
if v > recursionMaxNums {
return "", errors.Wrapf(fmt.Errorf("unable to execute template"), "rendering template has a nested reference name: %s", name)
}
includedNames[name]++
} else {
includedNames[name] = 1
}
err := tmpl.ExecuteTemplate(&buf, name, data)
includedNames[name]--
return buf.String(), err
}
tmpl.Funcs(funcMap)
tpls, err := c.helperTPLs()
if err != nil {
return nil, err
}
for _, tpl := range tpls {
tmpl, err = tmpl.Parse(tpl.content)
if err != nil {
return nil, fmt.Errorf("failed to parse helper template %s: %v", tpl.name, err)
}
}
return tmpl, nil
}
// RenderTemplateToBuffer renders the provided template string with the given data and returns the result as a *bytes.Buffer.
// The template string is parsed and executed using the Context's newTemplate method.
// If an error occurs during parsing or execution, it is returned along with the partially rendered template.
// The data parameter is optional and can be used to provide additional data for template rendering.
// If no data is provided, the template is rendered with an empty data context.
func (c *Context) RenderTemplateToBuffer(s string, data ...any) (*bytes.Buffer, error) {
t, err := c.newTemplate()
if err != nil {
return nil, err
}
t, err = t.Parse(s)
if err != nil {
return nil, err
}
var tplString bytes.Buffer
var d any
if len(data) > 0 {
d = data[0]
}
var execErr = t.Execute(&tplString, d)
if execErr != nil {
return &tplString, execErr
}
return &tplString, nil
}