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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
package baosync
import (
"encoding/json"
"fmt"
"slices"
"sort"
"strconv"
"strings"
"time"
)
func Drifted(want, got map[string]any, skip ...string) string {
keys := make([]string, 0, len(want))
for k := range want {
if !slices.Contains(skip, k) {
keys = append(keys, k)
}
}
sort.Strings(keys)
for _, k := range keys {
if !same(want[k], got[k]) {
return k
}
}
return ""
}
func empty(v any) bool {
switch x := v.(type) {
case nil:
return true
case string:
return x == ""
case []string:
return len(x) == 0
case []any:
return len(x) == 0
case bool:
return !x
case int:
return x == 0
case float64:
return x == 0
}
return false
}
func number(v any) (float64, bool) {
switch x := v.(type) {
case float64:
return x, true
case int:
return float64(x), true
case int64:
return float64(x), true
case json.Number:
f, err := x.Float64()
return f, err == nil
}
return 0, false
}
func strs(v any) ([]string, bool) {
switch x := v.(type) {
case []string:
return x, true
case []any:
out := make([]string, 0, len(x))
for _, e := range x {
out = append(out, fmt.Sprint(e))
}
return out, true
case string:
if x == "" {
return nil, true
}
parts := strings.Split(x, ",")
for i := range parts {
parts[i] = strings.TrimSpace(parts[i])
}
return parts, true
}
return nil, false
}
func sameSet(a, b []string) bool {
x, y := slices.Clone(a), slices.Clone(b)
for i := range x {
x[i] = strings.ToLower(x[i])
}
for i := range y {
y[i] = strings.ToLower(y[i])
}
sort.Strings(x)
sort.Strings(y)
return slices.Equal(slices.Compact(x), slices.Compact(y))
}
func seconds(s string) (float64, bool) {
if s == "" {
return 0, true
}
if n, err := strconv.ParseFloat(s, 64); err == nil {
return n, true
}
d, err := time.ParseDuration(s)
if err != nil {
return 0, false
}
return d.Seconds(), true
}
func same(want, got any) bool {
if got == nil {
return empty(want)
}
switch w := want.(type) {
case string:
switch g := got.(type) {
case string:
return strings.TrimSpace(w) == strings.TrimSpace(g)
case bool:
return w == strconv.FormatBool(g)
case []any:
ws, _ := strs(w)
gs, _ := strs(g)
return sameSet(ws, gs)
}
if n, ok := number(got); ok {
s, ok := seconds(w)
return ok && s == n
}
case []string:
gs, ok := strs(got)
return ok && sameSet(w, gs)
case bool:
g, ok := got.(bool)
return ok && g == w
case int:
n, ok := number(got)
return ok && n == float64(w)
}
return fmt.Sprint(want) == fmt.Sprint(got)
}