-
Notifications
You must be signed in to change notification settings - Fork 16
/
cond.go
60 lines (52 loc) · 1.09 KB
/
cond.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
package dynaml
import (
"fmt"
"github.com/mandelsoft/spiff/yaml"
)
type CondExpr struct {
C Expression
T Expression
F Expression
}
func (e CondExpr) Evaluate(binding Binding, locally bool) (interface{}, EvaluationInfo, bool) {
resolved := true
info := DefaultInfo()
var infoc EvaluationInfo
var result interface{}
a, info, ok := ResolveExpressionOrPushEvaluation(&e.C, &resolved, &info, binding, false)
if !ok {
// fmt.Printf("*** COND failed: %s\n", info.Issue)
return nil, info, false
}
if !resolved {
return e, info, true
}
if toBool(a) {
result, infoc, ok = e.T.Evaluate(binding, false)
} else {
result, infoc, ok = e.F.Evaluate(binding, false)
}
return result, infoc.Join(info), ok
}
func (e CondExpr) String() string {
return fmt.Sprintf("%s ? %s : %s", e.C, e.T, e.F)
}
func toBool(v interface{}) bool {
if v == nil {
return false
}
switch eff := v.(type) {
case bool:
return eff
case string:
return len(eff) > 0
case int64:
return eff != 0
case []yaml.Node:
return len(eff) != 0
case map[string]yaml.Node:
return len(eff) != 0
default:
return true
}
}