...
1 package exec
2
3 import (
4 "github.com/pkg/errors"
5
6 "github.com/noirbizarre/gonja/nodes"
7 )
8
9
10 type FilterFunction func(e *Evaluator, in *Value, params *VarArgs) *Value
11
12 type FilterSet map[string]FilterFunction
13
14
15 func (fs FilterSet) Exists(name string) bool {
16 _, existing := fs[name]
17 return existing
18 }
19
20
21
22
23
24
25
26
27 func (fs *FilterSet) Register(name string, fn FilterFunction) error {
28 if fs.Exists(name) {
29 return errors.Errorf("filter with name '%s' is already registered", name)
30 }
31 (*fs)[name] = fn
32 return nil
33 }
34
35
36
37 func (fs *FilterSet) Replace(name string, fn FilterFunction) error {
38 if !fs.Exists(name) {
39 return errors.Errorf("filter with name '%s' does not exist (therefore cannot be overridden)", name)
40 }
41 (*fs)[name] = fn
42 return nil
43 }
44
45 func (fs *FilterSet) Update(other FilterSet) FilterSet {
46 for name, filter := range other {
47 (*fs)[name] = filter
48 }
49 return *fs
50 }
51
52
53 func (e *Evaluator) EvaluateFiltered(expr *nodes.FilteredExpression) *Value {
54 value := e.Eval(expr.Expression)
55
56 for _, filter := range expr.Filters {
57 value = e.ExecuteFilter(filter, value)
58 if value.IsError() {
59 return AsValue(errors.Wrapf(value, `Unable to evaluate filter %s`, filter))
60 }
61 }
62
63
64
65
66 return value
67 }
68
69
70 func (e *Evaluator) ExecuteFilter(fc *nodes.FilterCall, v *Value) *Value {
71 params := NewVarArgs()
72
73 for _, param := range fc.Args {
74 value := e.Eval(param)
75 if value.IsError() {
76 return AsValue(errors.Wrapf(value, `Unable to evaluate parameter %s`, param))
77 }
78 params.Args = append(params.Args, value)
79 }
80
81 for key, param := range fc.Kwargs {
82 value := e.Eval(param)
83 if value.IsError() {
84 return AsValue(errors.Wrapf(value, `Unable to evaluate parameter %s=%s`, key, param))
85 }
86 params.KwArgs[key] = value
87 }
88 return e.ExecuteFilterByName(fc.Name, v, params)
89 }
90
91
92 func (e *Evaluator) ExecuteFilterByName(name string, in *Value, params *VarArgs) *Value {
93 if !e.Filters.Exists(name) {
94 return AsValue(errors.Errorf(`Filter "%s" not found`, name))
95 }
96 fn, _ := (*e.Filters)[name]
97
98 return fn(e, in, params)
99 }
100
View as plain text