-
Notifications
You must be signed in to change notification settings - Fork 0
/
expr.go
49 lines (42 loc) · 1.06 KB
/
expr.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
package expr
import (
"errors"
"fmt"
"os"
"github.com/antonmedv/expr"
"github.com/antonmedv/expr/vm"
"github.com/suzuki-shunsuke/renovate-issue-action/pkg/domain"
)
var errMustBeBool = errors.New("must be a boolean")
type Param struct {
Metadata *domain.Metadata
Labels []string
Vars map[string]interface{}
}
func compileBool(s string) (*vm.Program, error) {
a, err := expr.Compile(s, expr.AsBool(), expr.Env(&Param{}))
if err != nil {
fmt.Fprintf(os.Stderr, "[ERROR] compile an expression\n%+v", err)
return nil, fmt.Errorf("compile an expression: %w", err)
}
return a, nil
}
func runBool(prog *vm.Program, param *Param) (bool, error) {
a, err := expr.Run(prog, param)
if err != nil {
fmt.Fprintf(os.Stderr, "[ERROR] evaluate an expression\n%+v", err)
return false, fmt.Errorf("evaluate an expression: %w", err)
}
f, ok := a.(bool)
if !ok {
return false, errMustBeBool
}
return f, nil
}
func ExecBool(s string, param *Param) (bool, error) {
prog, err := compileBool(s)
if err != nil {
return false, err
}
return runBool(prog, param)
}