This repository has been archived by the owner on Jan 21, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 264
/
template.go
385 lines (328 loc) · 10.4 KB
/
template.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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
package template
import (
"bytes"
"fmt"
"io"
"reflect"
"strings"
"sync"
"text/template"
"github.com/Masterminds/sprig"
log "github.com/Sirupsen/logrus"
)
// Function contains the description of an exported template function
type Function struct {
// Name is the function name to bind in the template
Name string
// Description provides help for the function
Description []string `json:",omitempty"`
// Func is the reference to the actual function
Func interface{} `json:"-"`
// Function is the signature of the function
Function string
// Usage shows how to use it
Usage string `json:",omitempty"`
}
// FunctionExporter is implemented by any plugins wishing to show help on the function it exports.
type FunctionExporter interface {
// Funcs returns a list of special template functions of the form func(template.Context, arg1, arg2) interface{}
Funcs() []Function
}
// Context is a marker interface for a user-defined struct that is passed into the template engine (as context)
// and accessible in the exported template functions. Template functions can have the signature
// func(template.Context, arg1, arg2 ...) (string, error) and when functions like this are registered, the template
// engine will dynamically create and export a function of the form func(arg1, arg2...) (string, error) where
// the context instance becomes an out-of-band struct that can be mutated by functions. This in essence allows
// structured data as output of the template, in addition to a string from evaluating the template.
type Context interface {
// Funcs returns a list of special template functions of the form func(template.Context, arg1, arg2) interface{}
Funcs() []Function
}
// Options contains parameters for customizing the behavior of the engine
type Options struct {
// SocketDir is the directory for locating the socket file for
// a template URL of the form unix://socket_file/path/to/resource
SocketDir string
}
type defaultValue struct {
Name string
Value interface{}
Doc string
}
// Template is the templating engine
type Template struct {
options Options
url string
body []byte
parsed *template.Template
functions []func() []Function
funcs map[string]interface{}
globals map[string]interface{}
defaults map[string]defaultValue
context interface{}
registered []Function
lock sync.Mutex
parent *Template
}
// Void is used in the template functions return value type to indicate a void.
// Golang template does not allow functions with no return types to be bound.
type Void string
const voidValue Void = ""
// NewTemplate fetches the content at the url and returns a template. If the string begins
// with str:// as scheme, then the rest of the string is interpreted as the body of the template.
func NewTemplate(s string, opt Options) (*Template, error) {
var buff []byte
contextURL := s
// Special case of specifying the entire template as a string; otherwise treat as url
if strings.Index(s, "str://") == 0 {
buff = []byte(strings.Replace(s, "str://", "", 1))
contextURL = defaultContextURL()
} else {
b, err := Fetch(s, opt)
if err != nil {
return nil, err
}
buff = b
}
return NewTemplateFromBytes(buff, contextURL, opt)
}
// NewTemplateFromBytes builds the template from buffer with a contextURL which is used to deduce absolute
// path of any 'included' templates e.g. {{ include "./another.tpl" . }}
func NewTemplateFromBytes(buff []byte, contextURL string, opt Options) (*Template, error) {
if contextURL == "" {
log.Warningln("Context is not known. Included templates may not work properly.")
}
return &Template{
options: opt,
url: contextURL,
body: buff,
funcs: map[string]interface{}{},
globals: map[string]interface{}{},
defaults: map[string]defaultValue{},
functions: []func() []Function{},
}, nil
}
// SetOptions sets the runtime flags for the engine
func (t *Template) SetOptions(opt Options) *Template {
t.lock.Lock()
defer t.lock.Unlock()
t.options = opt
return t
}
// WithFunctions allows client code to extend the template by adding its own functions.
func (t *Template) WithFunctions(functions func() []Function) *Template {
t.lock.Lock()
defer t.lock.Unlock()
t.functions = append(t.functions, functions)
return t
}
// AddFunc adds a new function to support in template
func (t *Template) AddFunc(name string, f interface{}) *Template {
t.lock.Lock()
defer t.lock.Unlock()
t.funcs[name] = f
return t
}
// Ref returns the value keyed by name in the context of this template. See 'ref' template function.
func (t *Template) Ref(name string) interface{} {
if found, has := t.globals[name]; has {
return found
} else if v, has := t.defaults[name]; has {
return v.Value
}
return nil
}
// Dot returns the '.' in this template.
func (t *Template) Dot() interface{} {
return t.context
}
func (t *Template) forkFrom(parent *Template) (dotCopy interface{}, err error) {
t.lock.Lock()
defer t.lock.Unlock()
// copy the globals in the parent scope into the child
for k, v := range parent.globals {
t.globals[k] = v
}
// copy the defaults in the parent scope into the child
for k, v := range parent.defaults {
t.defaults[k] = v
}
// inherit the functions defined for this template
for k, v := range parent.funcs {
t.AddFunc(k, v)
}
// inherit other functions
for _, ff := range parent.functions {
t.functions = append(t.functions, ff)
}
if parent.context != nil {
return DeepCopyObject(parent.context)
}
return nil, nil
}
// Global sets the a key, value in the context of this template. It is visible to all the 'included'
// and 'sourced' templates by the calling template.
func (t *Template) Global(name string, value interface{}) *Template {
for here := t; here != nil; here = here.parent {
here.updateGlobal(name, value)
}
return t
}
func (t *Template) updateGlobal(name string, value interface{}) {
t.lock.Lock()
defer t.lock.Unlock()
t.globals[name] = value
}
// Def is equivalent to a {{ def "key" value "description" }} in defining a variable with a default value.
// The value is accessible via a {{ ref "key" }} in the template.
func (t *Template) Def(name string, value interface{}, doc string) *Template {
for here := t; here != nil; here = here.parent {
here.updateDef(name, value, doc)
}
return t
}
func (t *Template) updateDef(name string, val interface{}, doc ...string) *Template {
t.lock.Lock()
defer t.lock.Unlock()
t.defaults[name] = defaultValue{
Name: name,
Value: val,
Doc: strings.Join(doc, " "),
}
return t
}
// Validate parses the template and checks for validity.
func (t *Template) Validate() (*Template, error) {
t.lock.Lock()
t.parsed = nil
t.lock.Unlock()
return t, t.build(nil)
}
// Funcs returns a list of registered functions used by the template when it rendered the view.
func (t *Template) Funcs() []Function {
return t.registered
}
func (t *Template) build(context Context) error {
t.lock.Lock()
defer t.lock.Unlock()
if t.parsed != nil {
return nil
}
registered := []Function{}
fm := map[string]interface{}{}
for k, v := range sprig.TxtFuncMap() {
fm[k] = v
}
for k, v := range t.funcs {
if tf, err := makeTemplateFunc(context, v); err == nil {
fm[k] = tf
} else {
return err
}
}
// the default functions cannot be overriden
for _, f := range t.DefaultFuncs() {
tf, err := makeTemplateFunc(context, f.Func)
if err != nil {
return err
}
fm[f.Name] = tf
registered = append(registered, f)
}
// If there are any function sources that was set via WithFunctions()
for _, exp := range t.functions {
for _, f := range exp() {
tf, err := makeTemplateFunc(context, f.Func)
if err != nil {
return err
}
fm[f.Name] = tf
registered = append(registered, f)
}
}
// If the context implements the FunctionExporter interface, it can add more functions
// and potentially override existing.
if context != nil {
for _, f := range context.Funcs() {
if tf, err := makeTemplateFunc(context, f.Func); err == nil {
fm[f.Name] = tf
registered = append(registered, f)
} else {
return err
}
}
}
t.registered = registered
parsed, err := template.New(t.url).Funcs(fm).Parse(string(t.body))
if err != nil {
return err
}
t.parsed = parsed
return nil
}
// Execute is a drop-in replace of the execute method of template
func (t *Template) Execute(output io.Writer, context interface{}) error {
if err := t.build(toContext(context)); err != nil {
return err
}
t.context = context
return t.parsed.Execute(output, context)
}
// returns as Context if input implements the interface; otherwise nil
func toContext(in interface{}) Context {
var context Context
if in != nil {
if s, is := in.(Context); is {
context = s
}
}
return context
}
// Render renders the template given the context
func (t *Template) Render(context interface{}) (string, error) {
if err := t.build(toContext(context)); err != nil {
return "", err
}
var buff bytes.Buffer
err := t.Execute(&buff, context)
return buff.String(), err
}
// converts a function of f(Context, ags...) to a regular template function
func makeTemplateFunc(ctx Context, f interface{}) (interface{}, error) {
contextType := reflect.TypeOf((*Context)(nil)).Elem()
ff := reflect.Indirect(reflect.ValueOf(f))
// first we check to see if f has the special signature where the first
// parameter is the context parameter...
if ff.Kind() != reflect.Func {
return nil, fmt.Errorf("not a function:%v", f)
}
if ff.Type().NumIn() > 0 && ff.Type().In(0).AssignableTo(contextType) {
in := make([]reflect.Type, ff.Type().NumIn()-1) // exclude the context param
out := make([]reflect.Type, ff.Type().NumOut())
for i := 1; i < ff.Type().NumIn(); i++ {
in[i-1] = ff.Type().In(i)
}
variadic := false
if len(in) > 0 {
variadic = in[len(in)-1].Kind() == reflect.Slice
}
for i := 0; i < ff.Type().NumOut(); i++ {
out[i] = ff.Type().Out(i)
}
funcType := reflect.FuncOf(in, out, variadic)
funcImpl := func(in []reflect.Value) []reflect.Value {
if !variadic {
return ff.Call(append([]reflect.Value{reflect.ValueOf(ctx)}, in...))
}
variadicParam := in[len(in)-1]
last := make([]reflect.Value, variadicParam.Len())
for i := 0; i < variadicParam.Len(); i++ {
last[i] = variadicParam.Index(i)
}
return ff.Call(append(append([]reflect.Value{reflect.ValueOf(ctx)}, in[0:len(in)-1]...), last...))
}
newFunc := reflect.MakeFunc(funcType, funcImpl)
return newFunc.Interface(), nil
}
return ff.Interface(), nil
}