/
interpreter.go
67 lines (58 loc) · 1.9 KB
/
interpreter.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
package scripting
import (
"context"
"fmt"
"sync"
"github.com/rs/zerolog"
"github.com/skx/evalfilter/v2"
)
// Interpreter is a script interpreter
type Interpreter struct {
eval *evalfilter.Eval
operations *OperationStack
mu sync.Mutex
logger zerolog.Logger
}
// NewInterpreter create new script interpreter
func NewInterpreter(script string, logger zerolog.Logger) (*Interpreter, error) {
eval := evalfilter.New(script)
if err := eval.Prepare(); err != nil {
return nil, fmt.Errorf("unable to compile provided script: %w", err)
}
operations := OperationStack{}
interpreter := &Interpreter{
eval: eval,
operations: &operations,
logger: logger,
}
// init the interpreter
interpreter.init()
return interpreter, nil
}
func (i *Interpreter) init() {
// deactivate unwanted functions
i.eval.AddFunction("getenv", fnNoOp)
// alter builtins functions
i.eval.AddFunction("print", i.fnPrint)
i.eval.AddFunction("printf", i.fnPrintf)
// add custom functions
i.eval.AddFunction("triggerWebhook", i.buildSingleArgFunction(OpTriggerWebhook))
i.eval.AddFunction("sendNotification", i.buildNoArgFunction(OpSendNotification))
i.eval.AddFunction("setCategory", i.buildSingleArgFunction(OpSetCategory))
i.eval.AddFunction("setTitle", i.buildSingleArgFunction(OpSetTitle))
i.eval.AddFunction("setText", i.buildSingleArgFunction(OpSetTitle))
i.eval.AddFunction("disableGlobalNotification", i.buildNoArgFunction(OpDisableGlobalNotification))
}
// Exec a script by the interpreter
func (i *Interpreter) Exec(ctx context.Context, input ScriptInput) (OperationStack, error) {
i.mu.Lock()
defer i.mu.Unlock()
i.operations = &OperationStack{}
if result, err := i.eval.Run(input); err != nil {
return nil, fmt.Errorf("unable to execute script: %w", err)
} else if !result {
operations := append(*i.operations, *NewOperation(OpDrop))
i.operations = &operations
}
return *i.operations, nil
}