/
texttemplate.go
451 lines (375 loc) · 12.6 KB
/
texttemplate.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
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
/*
* Copyright (c) 2017, MegaEase
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package texttemplate
import (
"fmt"
"strings"
"github.com/tidwall/gjson"
"github.com/valyala/fasttemplate"
)
// The complete format of template sentence is
// ${beginToken}${tag1}${separator}${tag2}${separator}...${endtoken}
// e.g., if beginToken is '[[', endtoken is ']]', separator is '.'
// [[filter.{}.req.body.{gjson}]]
// [[filter.{}.req.body.{gjson}]]
// TemplateEngine is the abstract implementer
// Template is the part of user's input string's which we want the TemplateEngine to render it
// MetaTemplate is the description collections for TemplateEngine to identify user's valid template rules
const (
// regexpSyntax = "\\[\\[(.*?)\\]\\]"
// WidecardTag means accepting any none empty string
// if chose "{}" to accept any none empty string, then should provide another tag value at that level
WidecardTag = "{}"
// GJSONTag is the special hardcode tag for indicating GJSON syntax, must appear in the last
// of one template, if chose "{GJSON}", should provide another tag value at that level
GJSONTag = "{gjson}"
DefaultBeginToken = "[["
DefaultEndToken = "]]"
DefaultSeparator = "."
)
type node struct {
Value string // The tag,e.g. 'filter', 'req'
Children []*node
}
// TemplateEngine is the basic API collection for a template usage
type TemplateEngine interface {
// Render Rendering e.g., [[xxx.xx.dd.xx]]'s value is 'value0', [[yyy.www.zzz]]'s value is 'value1'
// "aaa-[[xxx.xx.dd.xx]]-bbb 10101-[[yyy.wwww.zzz]]-9292" will be rendered to "aaa-value0-bbb 10101-value1-9292"
// Also support GJSON syntax at last tag
Render(input string) (string, error)
// ExtractTemplateRuleMap extracts templates from input string
// return map's key is the template, the value is the matched and rendered metaTemplate
ExtractTemplateRuleMap(input string) map[string]string
// ExtractRawTemplateRuleMap extracts templates from input string
// return map's key is the template, the value is the matched and rendered metaTemplate or empty
ExtractRawTemplateRuleMap(input string) map[string]string
// HasTemplates checks whether it has templates in input string or not
HasTemplates(input string) bool
// MatchMetaTemplate return original template or replace with {gjson} at last tag, "" if not metaTemplate matched
MatchMetaTemplate(template string) string
// SetDict adds a temaplateRule and its value for later rendering
SetDict(template string, value interface{}) error
// GetDict returns the template's dictionary
GetDict() map[string]interface{}
}
// DummyTemplate return a empty implement
type DummyTemplate struct{}
// Render dummy implement
func (DummyTemplate) Render(input string) (string, error) {
return "", nil
}
// ExtractTemplateRuleMap dummy implement
func (DummyTemplate) ExtractTemplateRuleMap(input string) map[string]string {
m := make(map[string]string, 0)
return m
}
// ExtractRawTemplateRuleMap dummy implement
func (DummyTemplate) ExtractRawTemplateRuleMap(input string) map[string]string {
m := make(map[string]string, 0)
return m
}
// SetDict the dummy implement
func (DummyTemplate) SetDict(template string, value interface{}) error {
return nil
}
// MatchMetaTemplate dummy implement
func (DummyTemplate) MatchMetaTemplate(template string) string {
return ""
}
// GetDict the dummy implement
func (DummyTemplate) GetDict() map[string]interface{} {
m := make(map[string]interface{}, 0)
return m
}
// HasTemplates the dummy implement
func (DummyTemplate) HasTemplates(input string) bool {
return false
}
// TextTemplate wraps a fasttempalte rendering and a
// template syntax tree for validation, the valid template and its
// value can be added into dictionary for rendering
type TextTemplate struct {
ft *fasttemplate.Template
beginToken string
endToken string
separator string
metaTemplates []string // the user raw input candidate templates
root *node // The template syntax tree root node generated by use's input raw templates
dict map[string]interface{} // using `interface{}` for fasttemplate's API
}
// NewDefault returns Template interface implementer with default config and customize meatTemplates
func NewDefault(metaTemplates []string) (TemplateEngine, error) {
t := TextTemplate{
beginToken: DefaultBeginToken,
endToken: DefaultEndToken,
separator: DefaultSeparator,
metaTemplates: metaTemplates,
dict: map[string]interface{}{},
}
if err := t.buildTemplateTree(); err != nil {
return DummyTemplate{}, err
}
return t, nil
}
// New returns a new Template interface implementer, return a dummy template if something wrong,
// and in that case, the dedicated reason will set into error return
func New(beginToken, endToken, separator string, metaTemplates []string) (TemplateEngine, error) {
if len(beginToken) == 0 || len(endToken) == 0 || len(separator) == 0 || len(metaTemplates) == 0 {
return DummyTemplate{}, fmt.Errorf("invalid input, beingToken %s, endToken %s, separator = %s , metaTempaltes %v",
beginToken, endToken, separator, metaTemplates)
}
t := &TextTemplate{
beginToken: beginToken,
endToken: endToken,
separator: separator,
metaTemplates: metaTemplates,
dict: map[string]interface{}{},
}
if err := t.buildTemplateTree(); err != nil {
return DummyTemplate{}, err
}
return t, nil
}
// NewDummyTemplate returns a dummy template implement
func NewDummyTemplate() TemplateEngine {
return DummyTemplate{}
}
// GetDict return the dictionary of texttemplate
func (t TextTemplate) GetDict() map[string]interface{} {
return t.dict
}
func (t *TextTemplate) indexChild(children []*node, target string) int {
for i, v := range children {
if target == v.Value {
return i
}
}
return -1
}
func (t *TextTemplate) addNode(tags []string) {
if t.root == nil {
t.root = &node{}
}
parent := t.root
for _, v := range tags {
index := t.indexChild(parent.Children, v)
if index != -1 {
parent = parent.Children[index]
continue
} else {
tmp := &node{
Value: v,
}
parent.Children = append(parent.Children, tmp)
parent = tmp
}
}
}
func (t *TextTemplate) validateTree(root *node) error {
if len(root.Children) == 0 {
return nil
}
if index := t.indexChild(root.Children, WidecardTag); index != -1 {
if len(root.Children) != 1 {
return fmt.Errorf("{} wildcard and other tags exist at the same level")
}
}
if index := t.indexChild(root.Children, GJSONTag); index != -1 {
if len(root.Children) != 1 {
return fmt.Errorf("{gjson} GJSON and other tags exist at the same level")
}
}
for i := 0; i < len(root.Children); i++ {
if err := t.validateTree(root.Children[i]); err != nil {
return err
}
}
return nil
}
//
func (t *TextTemplate) buildTemplateTree() error {
if len(t.metaTemplates) == 0 {
return fmt.Errorf("empty templates")
}
for _, v := range t.metaTemplates {
arr := strings.Split(v, t.separator)
if len(arr) == 0 {
return fmt.Errorf("invalid template %s by separator %s",
v, t.separator)
}
for i, tag := range arr {
if len(tag) == 0 {
return fmt.Errorf("invalid empty tag, template %s index %d seprator %s",
v, i, t.separator)
}
if tag == GJSONTag && i != len(arr)-1 {
return fmt.Errorf("invalid %s: GJSON tag should only appear at the ending if need",
v)
}
}
}
// every single template is valid
for _, v := range t.metaTemplates {
arr := strings.Split(v, t.separator)
t.addNode(arr)
}
// validate the whole template tree
if err := t.validateTree(t.root); err != nil {
t.root = nil
return fmt.Errorf("invalid templates %v, err is %v ", t.metaTemplates, err)
}
return nil
}
// MatchMetaTemplate travels the metaTemplate syntax tree and return the first match template
// if matched found
// e.g. template is "filter.abc.req.body.friends.#(last=="Murphy").first" match "filter.{}.req.body.{gjson}"
// will return "filter.abc.req.body.{gjson}"
// e.g. template is "filter.abc.req.body" match "filter.{}.req.body"
// will return "filter.abc.req.body"
// if not any template matched found, then return ""
func (t TextTemplate) MatchMetaTemplate(template string) string {
tags := strings.Split(template, t.separator)
if len(tags) == 0 {
return ""
}
root := t.root
index := 0
hasGJSON := false
for ; index < len(tags); index++ {
// no tag remain to match, or it's an empty tag
if len(root.Children) == 0 || len(tags[index]) == 0 {
return ""
}
if len(root.Children) == 1 {
if root.Children[0].Value == GJSONTag {
hasGJSON = true
break
}
if root.Children[0].Value == WidecardTag || root.Children[0].Value == tags[index] {
root = root.Children[0]
continue
} else {
return ""
}
} else {
if index := t.indexChild(root.Children, tags[index]); index != -1 {
root = root.Children[index]
} else {
// no match at current level, return fail directly
return ""
}
}
}
if hasGJSON {
// replace left gjson syntax with GJSONTag
return strings.Join(tags[:index], t.separator) + t.separator + GJSONTag
}
return template
}
func (t TextTemplate) extractVarsAroundToken(input string) []string {
arr := []string{}
for len(input) != 0 {
bIdx := strings.Index(input, t.beginToken)
if bIdx == -1 {
break
}
input = input[bIdx+len(t.beginToken):] // jump over the beginning token
eIdx := strings.Index(input, t.endToken)
if eIdx == -1 {
break
}
arr = append(arr, input[:eIdx])
input = input[eIdx:]
}
return arr
}
// ExtractTemplateRuleMap extracts candidate templates from input string
// return map's key is the candidate template, the value is the matched template
func (t TextTemplate) ExtractTemplateRuleMap(input string) map[string]string {
results := t.extractVarsAroundToken(input)
m := map[string]string{}
for _, v := range results {
metaTemplate := t.MatchMetaTemplate(v)
if len(metaTemplate) != 0 {
m[v] = metaTemplate
}
}
return m
}
// ExtractRawTemplateRuleMap extracts all candidate templates (valid/invalid)
// from input string
func (t TextTemplate) ExtractRawTemplateRuleMap(input string) map[string]string {
results := t.extractVarsAroundToken(input)
m := map[string]string{}
for _, v := range results {
metaTemplate := t.MatchMetaTemplate(v)
if len(metaTemplate) != 0 {
m[v] = metaTemplate
} else {
m[v] = ""
}
}
return m
}
// SetDict adds a templateRule into dictionary if it contains any templates.
func (t TextTemplate) SetDict(template string, value interface{}) error {
if tmp := t.MatchMetaTemplate(template); len(tmp) != 0 {
t.dict[template] = value
return nil
}
return fmt.Errorf("matched none template , input %s ", template)
}
func (t *TextTemplate) setWithGJSON(template, metaTemplate string) error {
keyIndict := strings.TrimRight(metaTemplate, t.separator+GJSONTag)
gjsonSyntax := strings.TrimPrefix(template, keyIndict+t.separator)
if valueForGJSON, exist := t.dict[keyIndict]; exist {
if err := t.SetDict(template, gjson.Get(valueForGJSON.(string), gjsonSyntax).String()); err != nil {
return err
}
} else {
return fmt.Errorf("set gjson found no syntax target, template %s", template)
}
return nil
}
// HasTemplates check a string contain any valid templates
func (t TextTemplate) HasTemplates(input string) bool {
return len(t.ExtractTemplateRuleMap(input)) != 0
}
// Render uses a fasttemplate and dictionary to rendering
// e.g., [[xxx.xx.dd.xx]]'s value in dictionary is 'value0', [[yyy.www.zzz]]'s value is 'value1'
// "aaa-[[xxx.xx.dd.xx]]-bbb 10101-[[yyy.wwww.zzz]]-9292" will be rendered to "aaa-value0-bbb 10101-value1-9292"
// if containers any new GJSON syntax, it will use 'gjson.Get' to extract result then store into dictionary before
// rendering
func (t TextTemplate) Render(input string) (string, error) {
templateMap := t.ExtractTemplateRuleMap(input)
// find no template to render
if len(templateMap) == 0 {
return input, nil
}
for k, v := range templateMap {
// has new gjson syntax, add manually
if strings.Contains(v, GJSONTag) {
if _, exist := t.dict[k]; !exist {
if err := t.setWithGJSON(k, v); err != nil {
return "", err
}
}
}
}
t.ft = fasttemplate.New(input, t.beginToken, t.endToken)
return t.ft.ExecuteString(t.dict), nil
}