forked from nyaruka/goflow
-
Notifications
You must be signed in to change notification settings - Fork 0
/
refactor.go
50 lines (40 loc) · 1.23 KB
/
refactor.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
package tools
import (
"strings"
"github.com/nyaruka/goflow/excellent"
)
// RefactorTemplate refactors the passed in template
func RefactorTemplate(template string, allowedTopLevels []string) (string, error) {
buf := &strings.Builder{}
err := excellent.VisitTemplate(template, allowedTopLevels, func(tokenType excellent.XTokenType, token string) error {
switch tokenType {
case excellent.BODY:
buf.WriteString(token)
case excellent.IDENTIFIER, excellent.EXPRESSION:
refactored, err := refactorExpression(token)
// if we got an error, return that, and rewrite original expression
if err != nil {
buf.WriteString(wrapExpression(tokenType, token))
return err
}
// if not, append refactored expresion to the output
buf.WriteString(wrapExpression(tokenType, refactored))
}
return nil
})
return buf.String(), err
}
// RefactorTemplate refactors the passed in template
func refactorExpression(expression string) (string, error) {
parsed, err := excellent.Parse(expression, nil)
if err != nil {
return "", err
}
return parsed.String(), nil
}
func wrapExpression(tokenType excellent.XTokenType, token string) string {
if tokenType == excellent.IDENTIFIER {
return "@" + token
}
return "@(" + token + ")"
}