-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstate.go
82 lines (68 loc) · 1.43 KB
/
state.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package jsondiff
import (
"log"
"strings"
"github.com/PaesslerAG/jsonpath"
)
type Option func(*state)
func WithLogger(v *log.Logger) Option {
return func(st *state) {
st.Logger = v
}
}
func WithIgnorePath(v string) Option {
if _, err := jsonpath.New(v); err != nil {
panic(err)
}
return func(st *state) {
st.IgnorePaths = append(st.IgnorePaths, v)
}
}
func WithSetPath(v string) Option {
if _, err := jsonpath.New(v); err != nil {
panic(err)
}
return func(st *state) {
st.SetPaths = append(st.SetPaths, v)
}
}
type state struct {
// NOTE: format only similar to $.property or $.array[0]
Path string
SetPaths []string
IgnorePaths []string
Logger *log.Logger
}
func (st state) PushState(suffix string) state {
st.Path = st.Path + suffix
return st
}
func (st state) matchAny(paths ...string) bool {
tester := createPathTester(strings.Split(st.Path, "."))
for _, p := range paths {
v, err := jsonpath.Get(p, tester)
// err means invalid jsonpath or "unknown key xxx"
// if invalid jsonpath error rejects by WithIgnorePath
// then this err means only "unkwnon key xxx"
if err != nil {
continue
}
switch val := v.(type) {
case []interface{}:
if len(val) > 0 {
return true
}
default:
if val != nil {
return true
}
}
}
return false
}
func (st state) IsIgnored() bool {
return st.matchAny(st.IgnorePaths...)
}
func (st state) IsSet() bool {
return st.matchAny(st.SetPaths...)
}