-
Notifications
You must be signed in to change notification settings - Fork 11
/
template.go
276 lines (240 loc) · 8.92 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
package template
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"reflect"
"strings"
"sync"
"text/template"
"github.com/coveo/gotemplate/collections"
"github.com/coveo/gotemplate/utils"
logging "github.com/op/go-logging"
)
// String is an alias to collections.String
type String = collections.String
var templateMutex sync.Mutex
// Template let us extend the functionalities of base go template library.
type Template struct {
*template.Template
TempFolder string
substitutes []utils.RegexReplacer
context interface{}
delimiters []string
parent *Template
folder string
children map[string]*Template
aliases funcTableMap
functions funcTableMap
options OptionsSet
optionsEnabled OptionsSet
}
// Environment variables that could be defined to override default behaviors.
const (
EnvAcceptNoValue = "GOTEMPLATE_NO_VALUE"
EnvStrictErrorCheck = "GOTEMPLATE_STRICT_ERROR"
EnvSubstitutes = "GOTEMPLATE_SUBSTITUTES"
EnvDebug = "GOTEMPLATE_DEBUG"
EnvExtensionPath = "GOTEMPLATE_PATH"
// TODO: Deprecated, to remove in future version
EnvDeprecatedAssign = "GOTEMPLATE_DEPRECATED_ASSIGN"
)
const (
noGoTemplate = "no-gotemplate!"
noRazor = "no-razor!"
explicitGoTemplate = "gotemplate!"
)
// Common variables
var (
// ExtensionDepth the depth level of search of gotemplate extension from the current directory (default = 2).
ExtensionDepth = 2
toStrings = collections.ToStrings
acceptNoValue = String(os.Getenv(EnvAcceptNoValue)).ParseBool()
strictError = String(os.Getenv(EnvStrictErrorCheck)).ParseBool()
Print = utils.ColorPrint
Printf = utils.ColorPrintf
Println = utils.ColorPrintln
ErrPrintf = utils.ColorErrorPrintf
ErrPrintln = utils.ColorErrorPrintln
ErrPrint = utils.ColorErrorPrint
)
// IsRazor determines if the supplied code appears to have Razor code (using default delimiters).
func IsRazor(code string) bool { return strings.Contains(code, "@") }
// IsCode determines if the supplied code appears to have gotemplate code (using default delimiters).
func IsCode(code string) bool {
return IsRazor(code) || strings.Contains(code, "{{") || strings.Contains(code, "}}")
}
// NewTemplate creates an Template object with default initialization.
func NewTemplate(folder string, context interface{}, delimiters string, options OptionsSet, substitutes ...string) (result *Template, err error) {
defer func() {
if rec := recover(); rec != nil {
result, err = nil, fmt.Errorf("%v", rec)
}
}()
t := Template{Template: template.New("Main")}
must(t.Parse(""))
t.options = iif(options != nil, options, DefaultOptions()).(OptionsSet)
if acceptNoValue {
t.options[AcceptNoValue] = true
}
if strictError {
t.options[StrictErrorCheck] = true
}
t.optionsEnabled = make(OptionsSet)
t.folder, _ = filepath.Abs(iif(folder != "", folder, utils.Pwd()).(string))
t.context = iif(context != nil, context, collections.CreateDictionary())
t.aliases = make(funcTableMap)
t.delimiters = []string{"{{", "}}", "@"}
// Set the regular expression replacements
baseSubstitutesRegex := []string{`/(?m)^\s*#!\s*$/`}
if substitutesFromEnv := os.Getenv(EnvSubstitutes); substitutesFromEnv != "" {
baseSubstitutesRegex = append(baseSubstitutesRegex, strings.Split(substitutesFromEnv, "\n")...)
}
t.substitutes = utils.InitReplacers(append(baseSubstitutesRegex, substitutes...)...)
if t.options[Extension] {
t.initExtension()
}
// Set the options supplied by caller
t.init("")
if delimiters != "" {
for i, delimiter := range strings.Split(delimiters, ",") {
if i == len(t.delimiters) {
return nil, fmt.Errorf("Invalid delimiters '%s', must be a maximum of three comma separated parts", delimiters)
}
if delimiter != "" {
t.delimiters[i] = delimiter
}
}
}
return &t, nil
}
// MustNewTemplate creates an Template object with default initialization.
// It panics if an error occurs.
func MustNewTemplate(folder string, context interface{}, delimiters string, options OptionsSet, substitutes ...string) *Template {
return must(NewTemplate(folder, context, delimiters, options, substitutes...)).(*Template)
}
// GetNewContext returns a distint context for each folder.
func (t Template) GetNewContext(folder string, useCache bool) *Template {
folder = iif(folder != "", folder, t.folder).(string)
if context, found := t.children[folder]; useCache && found {
return context
}
newTemplate := Template(t)
newTemplate.Template = template.New(folder)
newTemplate.init(folder)
newTemplate.parent = &t
newTemplate.addFunctions(t.aliases)
newTemplate.importTemplates(t)
newTemplate.options = make(OptionsSet)
// We duplicate the options because the new context may alter them afterwhile and
// it should not modify the original values.
for k, v := range t.options {
newTemplate.options[k] = v
}
if !useCache {
return &newTemplate
}
// We register the new template as a child of the main template
t.children[folder] = &newTemplate
return t.children[folder]
}
// IsCode determines if the supplied code appears to have gotemplate code.
func (t Template) IsCode(code string) bool {
return !strings.Contains(code, noGoTemplate) && (t.IsRazor(code) || strings.Contains(code, t.LeftDelim()) || strings.Contains(code, t.RightDelim()))
}
// IsRazor determines if the supplied code appears to have Razor code.
func (t Template) IsRazor(code string) bool {
return strings.Contains(code, t.RazorDelim()) && !strings.Contains(code, noGoTemplate) && !strings.Contains(code, noRazor)
}
// LeftDelim returns the left delimiter.
func (t Template) LeftDelim() string { return t.delimiters[0] }
// RightDelim returns the right delimiter.
func (t Template) RightDelim() string { return t.delimiters[1] }
// RazorDelim returns the razor delimiter.
func (t Template) RazorDelim() string { return t.delimiters[2] }
// SetOption allows setting of template option after initialization.
func (t *Template) SetOption(option Options, value bool) { t.options[option] = value }
func (t Template) isTemplate(file string) bool {
for i := range templateExt {
if strings.HasSuffix(file, templateExt[i]) {
return true
}
}
return false
}
func (t *Template) initExtension() {
ext := t.GetNewContext("", false)
ext.options = DefaultOptions()
// We temporary set the logging level one grade lower
logLevel := logging.GetLevel(logger)
logging.SetLevel(logLevel-1, logger)
defer func() { logging.SetLevel(logLevel, logger) }()
var extensionfiles []string
if extensionFolders := strings.TrimSpace(os.Getenv(EnvExtensionPath)); extensionFolders != "" {
for _, path := range strings.Split(extensionFolders, string(os.PathListSeparator)) {
if path != "" {
files, _ := utils.FindFilesMaxDepth(path, ExtensionDepth, false, "*.gte")
extensionfiles = append(extensionfiles, files...)
}
}
}
extensionfiles = append(extensionfiles, utils.MustFindFilesMaxDepth(ext.folder, ExtensionDepth, false, "*.gte")...)
// Retrieve the template extension files
for _, file := range extensionfiles {
// We just load all the template files available to ensure that all template definition are loaded
// We do not use ParseFiles because it names the template with the base name of the file
// which result in overriding templates with the same base name in different folders.
content := string(must(ioutil.ReadFile(file)).([]byte))
// We execute the content, but we ignore errors. The goal is only to register the sub templates and aliases properly
// We also do not ask to clone the context as we wish to let extension to be able to alter the supplied context
if _, err := ext.processContentInternal(content, file, nil, 0, false); err != nil {
log.Error(err)
}
}
// Add the children contexts to the main context
for _, context := range ext.children {
t.importTemplates(*context)
}
// We reset the list of templates
t.children = make(map[string]*Template)
}
// Initialize a new template with same attributes as the current context.
func (t *Template) init(folder string) {
if folder != "" {
t.folder, _ = filepath.Abs(folder)
}
t.addFuncs()
t.Parse("")
t.children = make(map[string]*Template)
t.Delims(t.delimiters[0], t.delimiters[1])
t.setConstant(false, "\n", "NL", "CR", "NEWLINE")
t.setConstant(false, true, "true")
t.setConstant(false, false, "false")
t.setConstant(false, nil, "null")
}
func (t *Template) setConstant(stopOnFirst bool, value interface{}, names ...string) {
c, err := collections.TryAsDictionary(t.context)
if err != nil {
return
}
context := c.AsMap()
for i := range names {
if val, isSet := context[names[i]]; !isSet {
context[names[i]] = value
if stopOnFirst {
return
}
} else if isSet && reflect.DeepEqual(value, val) {
return
}
}
}
// Import templates from another template.
func (t *Template) importTemplates(source Template) {
for _, subTemplate := range source.Templates() {
if subTemplate.Name() != subTemplate.ParseName {
t.AddParseTree(subTemplate.Name(), subTemplate.Tree)
}
}
}