forked from hairyhenderson/gomplate
-
Notifications
You must be signed in to change notification settings - Fork 0
/
render.go
264 lines (232 loc) · 7.33 KB
/
render.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
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
package gomplate
import (
"context"
"fmt"
"io"
"net/http"
"net/url"
"os"
"text/template"
"time"
"github.com/hairyhenderson/gomplate/v4/data"
"github.com/hairyhenderson/gomplate/v4/internal/config"
)
// Options for template rendering.
//
// Experimental: subject to breaking changes before the next major release
type Options struct {
// Datasources - map of datasources to be read on demand when the
// 'datasource'/'ds'/'include' functions are used.
Datasources map[string]Datasource
// Context - map of datasources to be read immediately and added to the
// template's context
Context map[string]Datasource
// Templates - map of templates that can be referenced as nested templates
Templates map[string]Datasource
// Extra HTTP headers not attached to pre-defined datsources. Potentially
// used by datasources defined in the template.
ExtraHeaders map[string]http.Header
// Funcs - map of functions to be added to the default template functions.
// Duplicate functions will be overwritten by entries in this map.
Funcs template.FuncMap
// LeftDelim - set the left action delimiter for the template and all nested
// templates to the specified string. Defaults to "{{"
LDelim string
// RightDelim - set the right action delimiter for the template and all nested
// templates to the specified string. Defaults to "{{"
RDelim string
// Experimental - enable experimental features
Experimental bool
}
// optionsFromConfig - create a set of options from the internal config struct.
// Does not set the Funcs field.
func optionsFromConfig(cfg *config.Config) Options {
ds := make(map[string]Datasource, len(cfg.DataSources))
for k, v := range cfg.DataSources {
ds[k] = Datasource{
URL: v.URL,
Header: v.Header,
}
}
cs := make(map[string]Datasource, len(cfg.Context))
for k, v := range cfg.Context {
cs[k] = Datasource{
URL: v.URL,
Header: v.Header,
}
}
ts := make(map[string]Datasource, len(cfg.Templates))
for k, v := range cfg.Templates {
ts[k] = Datasource{
URL: v.URL,
Header: v.Header,
}
}
opts := Options{
Datasources: ds,
Context: cs,
Templates: ts,
ExtraHeaders: cfg.ExtraHeaders,
LDelim: cfg.LDelim,
RDelim: cfg.RDelim,
Experimental: cfg.Experimental,
}
return opts
}
// Datasource - a datasource URL with optional headers
//
// Experimental: subject to breaking changes before the next major release
type Datasource struct {
URL *url.URL
Header http.Header
}
// Renderer provides gomplate's core template rendering functionality.
// It should be initialized with NewRenderer.
//
// Experimental: subject to breaking changes before the next major release
type Renderer struct {
//nolint:staticcheck
data *data.Data
nested config.Templates
funcs template.FuncMap
lDelim string
rDelim string
tctxAliases []string
}
// NewRenderer creates a new template renderer with the specified options.
// The returned renderer can be reused, but it is not (yet) safe for concurrent
// use.
//
// Experimental: subject to breaking changes before the next major release
func NewRenderer(opts Options) *Renderer {
if Metrics == nil {
Metrics = newMetrics()
}
tctxAliases := []string{}
//nolint:staticcheck
sources := map[string]*data.Source{}
for alias, ds := range opts.Context {
tctxAliases = append(tctxAliases, alias)
//nolint:staticcheck
sources[alias] = &data.Source{
Alias: alias,
URL: ds.URL,
Header: ds.Header,
}
}
for alias, ds := range opts.Datasources {
//nolint:staticcheck
sources[alias] = &data.Source{
Alias: alias,
URL: ds.URL,
Header: ds.Header,
}
}
// convert the internal config.Templates to a map[string]Datasource
// TODO: simplify when config.Templates is removed
nested := config.Templates{}
for alias, ds := range opts.Templates {
nested[alias] = config.DataSource{
URL: ds.URL,
Header: ds.Header,
}
}
//nolint:staticcheck
d := &data.Data{
ExtraHeaders: opts.ExtraHeaders,
Sources: sources,
}
// make sure data cleanups are run on exit
addCleanupHook(d.Cleanup)
if opts.Funcs == nil {
opts.Funcs = template.FuncMap{}
}
return &Renderer{
nested: nested,
data: d,
funcs: opts.Funcs,
tctxAliases: tctxAliases,
lDelim: opts.LDelim,
rDelim: opts.RDelim,
}
}
// Template contains the basic data needed to render a template with a Renderer
//
// Experimental: subject to breaking changes before the next major release
type Template struct {
// Writer is the writer to output the rendered template to. If this writer
// is a non-os.Stdout io.Closer, it will be closed after the template is
// rendered.
Writer io.Writer
// Name is the name of the template - used for error messages
Name string
// Text is the template text
Text string
}
// RenderTemplates renders a list of templates, parsing each template's Text
// and executing it, outputting to its Writer. If a template's Writer is a
// non-os.Stdout io.Closer, it will be closed after the template is rendered.
//
// Experimental: subject to breaking changes before the next major release
func (t *Renderer) RenderTemplates(ctx context.Context, templates []Template) error {
// we need to inject the current context into the Data value, because
// the Datasource method may need it
// TODO: remove this in v4
t.data.Ctx = ctx
// configure the template context with the refreshed Data value
// only done here because the data context may have changed
tmplctx, err := createTmplContext(ctx, t.tctxAliases, t.data)
if err != nil {
return err
}
return t.renderTemplatesWithData(ctx, templates, tmplctx)
}
func (t *Renderer) renderTemplatesWithData(ctx context.Context, templates []Template, tmplctx interface{}) error {
// update funcs with the current context
// only done here to ensure the context is properly set in func namespaces
f := CreateFuncs(ctx, t.data)
// add user-defined funcs last so they override the built-in funcs
addToMap(f, t.funcs)
// track some metrics for debug output
start := time.Now()
defer func() { Metrics.TotalRenderDuration = time.Since(start) }()
for _, template := range templates {
err := t.renderTemplate(ctx, template, f, tmplctx)
if err != nil {
return fmt.Errorf("renderTemplate: %w", err)
}
}
return nil
}
func (t *Renderer) renderTemplate(ctx context.Context, template Template, f template.FuncMap, tmplctx interface{}) error {
if template.Writer != nil {
wr, ok := template.Writer.(io.Closer)
if ok && wr != os.Stdout {
defer wr.Close()
}
}
tstart := time.Now()
tmpl, err := parseTemplate(ctx, template.Name, template.Text,
f, tmplctx, t.nested, t.lDelim, t.rDelim)
if err != nil {
return err
}
err = tmpl.Execute(template.Writer, tmplctx)
Metrics.RenderDuration[template.Name] = time.Since(tstart)
if err != nil {
Metrics.Errors++
return fmt.Errorf("failed to render template %s: %w", template.Name, err)
}
Metrics.TemplatesProcessed++
return nil
}
// Render is a convenience method for rendering a single template. For more
// than one template, use RenderTemplates. If wr is a non-os.Stdout
// io.Closer, it will be closed after the template is rendered.
//
// Experimental: subject to breaking changes before the next major release
func (t *Renderer) Render(ctx context.Context, name, text string, wr io.Writer) error {
return t.RenderTemplates(ctx, []Template{
{Name: name, Text: text, Writer: wr},
})
}