-
Notifications
You must be signed in to change notification settings - Fork 0
/
loader.go
352 lines (323 loc) · 10.4 KB
/
loader.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
package main
import (
"errors"
"fmt"
"os"
"path/filepath"
"regexp"
"sort"
"strings"
"text/template"
"github.com/Masterminds/sprig"
log "github.com/sirupsen/logrus"
)
type TemplateLoader struct {
opts *TemplateLoaderOptions
sources map[TemplateMode][]string
templates map[TemplateMode]map[string]*template.Template
// filepathTplRx contains a precompiled Rx for replacing template tags
// in file paths, token delims must be quoted before compiling such Rx.
filepathTplRx *regexp.Regexp
}
type TemplateMode string
const (
TemplateModeSingle TemplateMode = "single"
TemplateModeVerbatim TemplateMode = "verbatim"
TemplateModeCollection TemplateMode = "collection"
)
type TemplateLoaderOptions struct {
LeftDelim string
RightDelim string
ModePrefix string
}
func checkTemplateLoaderOptions(opts *TemplateLoaderOptions) *TemplateLoaderOptions {
if opts == nil {
opts = new(TemplateLoaderOptions)
}
if len(opts.LeftDelim) == 0 {
opts.LeftDelim = "{{"
}
if len(opts.RightDelim) == 0 {
opts.RightDelim = "}}"
}
if len(opts.ModePrefix) == 0 {
opts.ModePrefix = "_"
}
return opts
}
// NewTemplateLoader returns a new template loader with all files stat'd and
// categorized into rendiring modes [single, collection] based on name prefix.
func NewTemplateLoader(paths []string, opts *TemplateLoaderOptions) (*TemplateLoader, error) {
loader := &TemplateLoader{
opts: checkTemplateLoaderOptions(opts),
sources: make(map[TemplateMode][]string, 3),
templates: make(map[TemplateMode]map[string]*template.Template, 2),
}
loader.filepathTplRx = regexp.MustCompile(
regexp.QuoteMeta(loader.opts.LeftDelim) +
`\s*(?P<field>\.?[a-zA-Z0-9_.]+)\s*` +
regexp.QuoteMeta(loader.opts.RightDelim),
)
seen := make(map[string]struct{})
for _, path := range paths {
fullPath, err := filepath.Abs(path)
if err != nil {
log.WithFields(log.Fields{
"Path": path,
}).Warningln("unable to convert path to absolute, skipping")
continue
}
info, err := os.Stat(fullPath)
if err != nil {
log.WithFields(log.Fields{
"Path": path,
"FullPath": fullPath,
}).Warningln("unable to stat, skipping")
continue
}
if !info.IsDir() {
if _, ok := seen[fullPath]; ok {
continue
} else {
seen[fullPath] = struct{}{}
}
loader.addFileSource(fullPath)
continue
}
if err := filepath.Walk(fullPath, func(name string, info os.FileInfo, err error) error {
if info.IsDir() {
return nil
}
if _, ok := seen[name]; ok {
return nil
} else {
seen[name] = struct{}{}
}
loader.addFileSource(name)
return nil
}); err != nil {
log.WithFields(log.Fields{
"Path": fullPath,
}).Warningln("unable to walk down the path, skipping")
continue
}
}
sort.Strings(loader.sources[TemplateModeSingle])
sort.Strings(loader.sources[TemplateModeVerbatim])
sort.Strings(loader.sources[TemplateModeCollection])
singleSources := loader.sources[TemplateModeSingle]
for _, source := range singleSources {
set := loader.templates[TemplateModeSingle]
if set == nil {
set = make(map[string]*template.Template, len(singleSources))
loader.templates[TemplateModeSingle] = set
}
tpl, err := template.New(source).Funcs(sprig.TxtFuncMap()).ParseFiles(source)
if err != nil {
err = fmt.Errorf("template parse error: %v", err)
return nil, err
}
set[source] = tpl
}
collectionSources := loader.sources[TemplateModeCollection]
for _, source := range collectionSources {
set := loader.templates[TemplateModeCollection]
if set == nil {
set = make(map[string]*template.Template, len(collectionSources))
loader.templates[TemplateModeCollection] = set
}
tpl, err := template.New(source).Funcs(sprig.TxtFuncMap()).ParseFiles(source)
if isBinaryContent(err) {
set[source] = nil
continue
} else if err != nil {
err = fmt.Errorf("template parse error: %v", err)
return nil, err
}
set[source] = tpl
}
return loader, nil
}
func (l *TemplateLoader) addFileSource(path string) {
name := filepath.Base(path)
dir := filepath.Dir(path)
mode := TemplateModeVerbatim
if l.filepathTplRx.MatchString(path) {
mode = TemplateModeCollection
} else if strings.HasPrefix(name, l.opts.ModePrefix) {
path = filepath.Join(dir, name)
mode = TemplateModeSingle
}
l.sources[mode] = append(l.sources[mode], path)
}
// findCollectionPrefix finds the shortest prefix of a collection referenced in selector.
// It returns two new selectors: collection selector from TemplateContext,
// also field selector for elements in collection. It returns false,
// if no collection prefix found.
func findCollectionPrefix(c TemplateContext, selector string) (string, string, bool) {
parts := strings.Split(selector, ".")
prefix := parts[0]
if _, ok := c.LengthOf(prefix); ok {
if len(parts) == 1 {
// only collection specified
return prefix, "", true
}
// collection prefix and field selector specified
selector := strings.Join(parts[1:], ".")
return prefix, selector, true
} else if len(parts) == 1 {
// only one part specified and it's not a collection prefix
return "", "", false
}
for i := 1; i < len(parts); i++ {
prefix += "." + parts[i]
if _, ok := c.LengthOf(prefix); ok {
if i == len(parts)-1 {
// was last part — the whole selector is a collection prefix
return prefix, "", true
}
// collection prefix and field selector specified
selector := strings.Join(parts[i:], ".")
return prefix, selector, true
}
}
// no collection prefix found in the specified selector
return "", "", false
}
type collectionCache struct {
CollectionSelector string
ItemFieldSelector string
}
// RenderFilepath yields a map of one or multiple file paths based on path template. If template references a collection,
// the output mapping will have all keys mapped to the corresponding TemplateContext with "Current" field set.
//
// Example: "{{ .Friends.Name }}"" will be mapped as
// ("Alice" => TemplateContext), where TemplateContext.Current is TemplateContext.Friends[0].
// ("Bob" => TemplateContext), where TemplateContext.Current is TemplateContext.Friends[1].
func (l *TemplateLoader) RenderFilepath(
rootContext TemplateContext, pathTemplate string) (map[string]TemplateContext, error) {
var err error
var collectionSelector string
var collectionLength int
cache := make(map[string]collectionCache)
// replaceWithCurrent is a function that replaces all templated placeholders in pathTemplate,
// using idx as an offset in the collection, if collection references are used in pathTemplate.
//
// The template can only have one collection reference, but multiple collection item field references.
// For example, it can have {{.Friends.Name}}_{{.Friends.Age}} so the collection "Friends" will be traversed once,
// and on each idx like Friends[0], Friends[1], ..., Friends[idx] these placeholders will be replaced
// with "name" and "age" field values from the corresponding collection items.
replaceWithCurrent := func(idx int) (string, TemplateContext, error) {
var currentContext TemplateContext
var currentError error
path := l.filepathTplRx.ReplaceAllStringFunc(pathTemplate, func(field string) string {
field = strings.TrimPrefix(field, l.opts.LeftDelim)
field = strings.TrimSuffix(field, l.opts.RightDelim)
field = strings.TrimSpace(field)
if cached, ok := cache[field]; ok {
// already parsed field, on previous iteration, and it's a collection
currentContext = rootContext.CurrentAt(cached.CollectionSelector, idx)
if item, found := currentContext.CurrentItem(cached.ItemFieldSelector); found {
return fmt.Sprintf("%v", item)
}
return ""
}
selector := strings.TrimPrefix(field, ".")
collection, itemField, ok := findCollectionPrefix(rootContext, selector)
if ok {
// a collection prefix has been found
if len(collectionSelector) > 0 {
if collection != collectionSelector {
currentError = fmt.Errorf(
"multiple collections are not expected, first was: %s",
collectionSelector)
return ""
}
} else {
collectionSelector = collection
collectionLength, _ = rootContext.LengthOf(collection)
cache[field] = collectionCache{
CollectionSelector: collectionSelector,
ItemFieldSelector: itemField,
}
}
if len(itemField) > 0 {
currentContext = rootContext.CurrentAt(collection, idx)
if item, found := currentContext.CurrentItem(itemField); found {
return fmt.Sprintf("%v", item)
}
} else {
currentContext = rootContext.CurrentCollection(collection)
currentError = ErrIterStop
return fmt.Sprintf("%s", collection)
}
log.WithField("field", field).Warningln("filename template field is not resolved")
return ""
}
if item, ok := rootContext.Item(selector); ok {
return fmt.Sprintf("%v", item)
}
log.WithField("field", field).Warningln("filename template field is not resolved")
return ""
})
if currentContext == nil {
return path, rootContext, currentError
}
return path, currentContext, currentError
}
path, currentContext, err := replaceWithCurrent(0)
if err == ErrIterStop {
resultMap := map[string]TemplateContext{
path: currentContext,
}
return resultMap, nil
} else if err != nil {
return nil, err
}
resultMap := map[string]TemplateContext{
path: currentContext,
}
if collectionLength > 1 {
// we have more items to traverse in collection
for idx := 1; idx < collectionLength; idx++ {
path, currentContext, err = replaceWithCurrent(idx)
if err != nil {
return nil, err
}
resultMap[path] = currentContext
}
}
return resultMap, nil
}
var ErrIterStop = errors.New("stop iterating")
type SourceFunc func(source string) error
func (l *TemplateLoader) ForEachSource(mode TemplateMode, fn SourceFunc) error {
for _, source := range l.sources[mode] {
if err := fn(source); err != nil {
return err
}
}
return nil
}
type RenderFunc func(tpl *template.Template, source string) error
func (l *TemplateLoader) RenderEachTemplate(mode TemplateMode, fn RenderFunc) error {
if mode == TemplateModeVerbatim {
err := errors.New("wrong mode: verbatim doesn't use template engin")
return err
}
for _, source := range l.sources[mode] {
if err := fn(l.templates[mode][source], source); err != nil {
return err
}
}
return nil
}
func isBinaryContent(err error) bool {
if err == nil {
return false
}
if strings.Contains(err.Error(), "unexpected unrecognized character") {
return true
}
return false
}