-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathquery.go
118 lines (100 loc) · 2.42 KB
/
query.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
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
package jqx
import (
"crypto/md5"
"crypto/sha1"
"crypto/sha256"
"crypto/sha512"
"encoding/hex"
"fmt"
"hash"
"iter"
"maps"
"math/rand/v2"
"slices"
"github.com/itchyny/gojq"
)
var builtins = must(gojq.Parse(`
def shuffle: shuffle("A seed");
`)).FuncDefs
type constString string
type FanOut func(any) iter.Seq[any]
type State struct {
Files map[string]any
Globals map[string]any
}
func (s *State) snapshot(input any, kv []any) (rt any) {
rt = input
filename, jsonData := kv[0], kv[1]
if s.Files == nil {
s.Files = map[string]any{}
}
s.Files[filename.(string)] = jsonData
return
}
func shuffle(input any, seed []any) any {
s := fmt.Sprint(seed[0])
r := rand.PCG{}
r.Seed(0x701877fa59de0c16, 0x99f94bdb8143b770)
for _, c := range s {
hi := r.Uint64() ^ uint64(len(s))
lo := r.Uint64() ^ uint64(c)
r.Seed(hi, lo)
}
rt := slices.Clone(input.([]any))
rand.New(&r).Shuffle(len(rt), func(i, j int) {
rt[i], rt[j] = rt[j], rt[i]
})
return rt
}
func hasher(f func() hash.Hash) func(any, []any) any {
return func(input any, _ []any) any {
h := f()
h.Write([]byte(input.(string)))
return hex.EncodeToString(h.Sum(nil))
}
}
func (s *State) Compile(code constString) FanOut {
parsed, err := gojq.Parse(string(code))
failif(err, "parsing query")
builtins := slices.Clone(builtins)
parsed.FuncDefs = append(builtins, parsed.FuncDefs...)
globalKeys := slices.Sorted(func(yield func(string) bool) {
for key := range maps.Keys(s.Globals) {
yield("$" + key)
}
})
globalValues := slices.Collect(func(yield func(any) bool) {
for _, globalKey := range globalKeys {
yield(s.Globals[globalKey[1:]])
}
})
globalKeys = append(globalKeys, "$vars")
globalValues = append(globalValues, s.Globals)
compiled, err := gojq.Compile(
parsed,
gojq.WithFunction("snapshot", 2, 2, s.snapshot),
gojq.WithFunction("shuffle", 1, 1, shuffle),
gojq.WithFunction("md5", 0, 0, hasher(md5.New)),
gojq.WithFunction("sha1", 0, 0, hasher(sha1.New)),
gojq.WithFunction("sha256", 0, 0, hasher(sha256.New)),
gojq.WithFunction("sha512", 0, 0, hasher(sha512.New)),
gojq.WithVariables(globalKeys),
)
failif(err, "compiling query")
return func(v any) iter.Seq[any] {
return func(yield func(any) bool) {
iter := compiled.Run(v, globalValues...)
for {
v, ok := iter.Next()
if !ok {
break
}
err, _ := v.(error)
failif(err, "running query")
if !yield(v) {
break
}
}
}
}
}