forked from rainycape/gondola
-
Notifications
You must be signed in to change notification settings - Fork 0
/
templateutil.go
318 lines (305 loc) · 7.66 KB
/
templateutil.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
// Package templateutil contains functions for parsing and walking go
// template trees.
package templateutil
import (
"bytes"
"fmt"
"io"
"os"
"regexp"
"strconv"
"strings"
"text/template/parse"
)
const (
leftDelim = "{{"
rightDelim = "}}"
BeginTranslatableBlock = "begintrans"
EndTranslatableBlock = "endtrans"
)
var (
funcNotDefinedRe = regexp.MustCompile("function \"(\\w+)\" not defined")
varNotDefinedRe = regexp.MustCompile("undefined variable \"\\$(\\w+)\"")
defineRe = regexp.MustCompile(`(\{\{\s*?define.*?\}\})`)
)
// DumpTree writes a *parse.Tree element by element to the given
// io.Writer. If w is nil, the result is printed to stdout.
func DumpTree(w io.Writer, tree *parse.Tree) error {
if w == nil {
w = os.Stdout
}
var err error
WalkTree(tree, func(n, p parse.Node) {
if err != nil {
return
}
fmt.Fprintf(w, "%T %v\n", n, n)
})
return err
}
// WalkTree visits all the nodes in the tree, calling f
// for every node with its parent.
func WalkTree(tree *parse.Tree, f func(n, p parse.Node)) {
WalkNode(tree.Root, nil, f)
}
// WalkNode visits all nodes starting from node, calling f
// with its parent. For the first call, the parent value is
// the one received as the second argument.
func WalkNode(node, parent parse.Node, f func(n, p parse.Node)) {
if node == nil {
return
}
f(node, parent)
switch x := node.(type) {
case *parse.ActionNode:
WalkNode(x.Pipe, x, f)
case *parse.PipeNode:
for _, v := range x.Decl {
WalkNode(v, x, f)
}
for _, v := range x.Cmds {
WalkNode(v, x, f)
}
case *parse.CommandNode:
for _, v := range x.Args {
WalkNode(v, x, f)
}
case *parse.ListNode:
for _, v := range x.Nodes {
WalkNode(v, x, f)
}
case *parse.IfNode:
if x.List != nil {
WalkNode(x.List, x, f)
}
if x.ElseList != nil {
WalkNode(x.ElseList, x, f)
}
case *parse.WithNode:
if x.List != nil {
WalkNode(x.List, x, f)
}
if x.ElseList != nil {
WalkNode(x.ElseList, x, f)
}
case *parse.RangeNode:
if x.List != nil {
WalkNode(x.List, x, f)
}
if x.ElseList != nil {
WalkNode(x.ElseList, x, f)
}
case *parse.TemplateNode:
if x.Pipe != nil {
WalkNode(x.Pipe, x, f)
}
}
}
// ReplaceNode replaces the n node in parent p with nn.
func ReplaceNode(n parse.Node, p parse.Node, nn parse.Node) error {
found := false
switch pn := p.(type) {
/*case *parse.ActionNode:
case *parse.PipeNode:*/
case *parse.CommandNode:
for ii, v := range pn.Args {
if v == n {
pn.Args[ii] = nn
found = true
break
}
}
case *parse.ListNode:
for ii, v := range pn.Nodes {
if v == n {
var nodes []parse.Node
nodes = append(nodes, pn.Nodes[:ii]...)
nodes = append(nodes, nn)
nodes = append(nodes, pn.Nodes[ii+1:]...)
pn.Nodes = nodes
found = true
break
}
}
/*case *parse.IfNode:
case *parse.WithNode:
case *parse.RangeNode:*/
default:
return fmt.Errorf("can't replace node in %T", pn)
}
if !found {
return fmt.Errorf("could not find node %v in parent %v", n, p)
}
return nil
}
// Parse parses the given text as a set of template trees, adding placeholders
// for undefined functions and variables.
func Parse(name string, text string) (map[string]*parse.Tree, error) {
text = ReplaceVariableShorthands(text, '@', "")
funcs := make(map[string]interface{})
var treeSet map[string]*parse.Tree
var err error
for {
treeSet, err = parse.Parse(name, text, leftDelim, rightDelim, funcs)
if err != nil {
if m := funcNotDefinedRe.FindStringSubmatch(err.Error()); m != nil {
funcs[m[1]] = func() {}
continue
}
if m := varNotDefinedRe.FindStringSubmatch(err.Error()); m != nil {
prepend := fmt.Sprintf("{{ $%s := . }}\n", m[1])
text = prepend + defineRe.ReplaceAllString(text, "$0"+strings.Replace(prepend, "$", "$$", -1))
continue
}
return nil, err
}
break
}
return treeSet, nil
}
func ReplaceVariableShorthands(text string, chr byte, name string) string {
repl := fmt.Sprintf("$%s.", name)
var buf bytes.Buffer
buf.Grow(len(text))
cmd := false
quoted := false
runes := []rune(text)
for ii, v := range runes {
if byte(v) == chr && cmd && !quoted {
buf.WriteString(repl)
continue
}
if cmd && v == '}' {
cmd = ii < len(runes)-1 && runes[ii+1] != '}'
} else if !cmd && v == '{' {
cmd = ii < len(runes)-1 && runes[ii+1] == '{'
}
if cmd {
if v == '"' && (ii == 0 || runes[ii-1] != '\\') {
quoted = !quoted
}
}
buf.WriteRune(v)
}
return buf.String()
}
// IsPseudoFunction returns true iff n is a *parse.ActionNode
// consisting solely of a fn call without any arguments.
func IsPseudoFunction(n parse.Node, fn string) bool {
return n.Type() == parse.NodeAction && n.String() == leftDelim+fn+rightDelim
}
// ReplaceTranslatableBlocks replaces begintrans/endtrans blocks
// with an equivalent action using the translation function named
// by fn.
func ReplaceTranslatableBlocks(tr *parse.Tree, fn string) error {
var err error
WalkTree(tr, func(n, p parse.Node) {
if err != nil {
return
}
if IsPseudoFunction(n, BeginTranslatableBlock) {
list, ok := p.(*parse.ListNode)
if !ok {
loc, ctx := tr.ErrorContext(n)
err = fmt.Errorf("%s:%s:%s not in ListNode (%T)", loc, ctx, BeginTranslatableBlock, p)
return
}
cmd := &parse.CommandNode{
NodeType: parse.NodeCommand,
Pos: n.Position(),
}
pipe := &parse.PipeNode{
NodeType: parse.NodePipe,
Pos: n.Position(),
Cmds: []*parse.CommandNode{cmd},
}
repl := &parse.ActionNode{
NodeType: parse.NodeAction,
Pos: n.Position(),
Pipe: pipe,
}
if repl != nil {
}
pos := -1
for ii, v := range list.Nodes {
if v == n {
pos = ii
break
}
}
var pipes []parse.Node
var buf bytes.Buffer
endPos := -1
Nodes:
for ii, v := range list.Nodes[pos+1:] {
switch x := v.(type) {
case *parse.TextNode:
buf.Write(x.Text)
case *parse.ActionNode:
if IsPseudoFunction(x, EndTranslatableBlock) {
endPos = ii
break Nodes
}
if len(x.Pipe.Decl) > 0 {
loc, ctx := tr.ErrorContext(n)
err = fmt.Errorf("%s:%s:%s translatable block can't contain a pipe with declaractions", loc, ctx, v)
}
buf.WriteString("%v")
pipes = append(pipes, x.Pipe)
default:
loc, ctx := tr.ErrorContext(n)
err = fmt.Errorf("%s translatable block can't contain %T %s", loc, v, ctx)
return
}
}
if buf.Len() > 0 {
text := buf.String()
quoted := strconv.Quote(text)
innerPipe := &parse.PipeNode{
NodeType: parse.NodePipe,
Pos: n.Position(),
Cmds: []*parse.CommandNode{
&parse.CommandNode{
NodeType: parse.NodeCommand,
Pos: n.Position(),
Args: []parse.Node{parse.NewIdentifier(fn), &parse.StringNode{
NodeType: parse.NodeString,
Pos: n.Position(),
Quoted: quoted,
Text: text,
}},
},
},
}
cmd.Args = append(cmd.Args, parse.NewIdentifier("printf"), innerPipe)
cmd.Args = append(cmd.Args, pipes...)
}
nodes := list.Nodes[:pos]
nodes = append(nodes, repl)
nodes = append(nodes, list.Nodes[endPos+pos+1:]...)
list.Nodes = nodes
}
})
return err
}
// TemplateNode returns a *parse.Template node invoking the given
// template passing . as the argument.
func TemplateNode(name string, pos parse.Pos) *parse.TemplateNode {
dot := &parse.DotNode{Pos: pos}
cmd := &parse.CommandNode{
NodeType: parse.NodeCommand,
Pos: pos,
Args: []parse.Node{dot},
}
pipe := &parse.PipeNode{
NodeType: parse.NodePipe,
Pos: pos,
Cmds: []*parse.CommandNode{cmd},
}
return &parse.TemplateNode{
NodeType: parse.NodeTemplate,
Pos: pos,
Name: name,
Pipe: pipe,
}
}