-
Notifications
You must be signed in to change notification settings - Fork 1
/
schema.go
470 lines (420 loc) · 10.3 KB
/
schema.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
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
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
package ski
import (
"context"
"errors"
"fmt"
"log/slog"
"reflect"
"strings"
"github.com/spf13/cast"
"gopkg.in/yaml.v3"
)
func init() {
Registers(NewExecutors{
"fetch": fetch,
"raw": raw,
"kind": kind,
"map": mapping,
"each": each,
"pipe": pipe,
"or": or,
"debug": debug,
"list.of": list_of,
"if.contains": if_contains,
"str.join": str_join,
"str.split": str_split,
"str.suffix": str_suffix,
"str.prefix": str_prefix,
"json.parse": json_parse,
"json.string": json_string,
})
}
// Meta from the yaml node, if Executor implements Meta, it will be called on compile
type Meta interface {
Meta(k, v *yaml.Node) error
}
// Compile the Executor from the YAML string.
func Compile(str string) (Executor, error) {
c := new(compiler)
if err := yaml.Unmarshal([]byte(str), c); err != nil {
return nil, err
}
return c.exec, nil
}
// CompileNode the Executor from the YAML node.
func CompileNode(node *yaml.Node) (Executor, error) {
c := new(compiler)
if err := c.UnmarshalYAML(node); err != nil {
return nil, err
}
return c.exec, nil
}
// Kind converts to a Kind type
type Kind uint
const (
KindAny Kind = iota
KindBool
KindInt // int32
KindInt64
KindFloat // float 32
KindFloat64
KindString
)
// kind converts to a Kind type
func kind(args Arguments) (Executor, error) {
var k Kind
if err := k.UnmarshalText([]byte(args.GetString(0))); err != nil {
return nil, err
}
return k, nil
}
var kindNames = [...]string{
KindAny: "any",
KindBool: "bool",
KindInt: "int",
KindInt64: "int64",
KindFloat: "float",
KindFloat64: "float64",
KindString: "string",
}
func (k Kind) String() string { return kindNames[k] }
func (k Kind) MarshalText() (text []byte, err error) { return []byte(kindNames[k]), nil }
func (k *Kind) UnmarshalText(text []byte) error {
switch string(text) {
case "", "any":
*k = KindAny
case "bool":
*k = KindBool
case "int", "int32":
*k = KindInt
case "int64":
*k = KindInt64
case "float", "float32":
*k = KindFloat
case "float64":
*k = KindFloat64
case "string":
*k = KindString
default:
return fmt.Errorf("unknown kind %s", text)
}
return nil
}
func (k Kind) Exec(_ context.Context, v any) (any, error) {
switch k {
case KindBool:
return cast.ToBoolE(v)
case KindInt:
return cast.ToInt32E(v)
case KindInt64:
return cast.ToInt64E(v)
case KindFloat:
return cast.ToFloat32E(v)
case KindFloat64:
return cast.ToFloat64E(v)
case KindString:
return cast.ToStringE(v)
default:
return v, nil
}
}
type compiler struct {
exec Executor
alias map[string][]Executor
}
func (c compiler) newError(message string, node *yaml.Node, err error) error {
if err != nil {
message = fmt.Sprintf("%s: %s", message, err)
}
return fmt.Errorf("line %d column %d %s", node.Line, node.Column, message)
}
// UnmarshalYAML compile the Executor from the YAML string.
func (c *compiler) UnmarshalYAML(node *yaml.Node) error {
c.alias = make(map[string][]Executor)
exec, err := c.compileNode(node)
if err != nil {
return err
}
switch len(exec) {
case 1:
c.exec = exec[0]
default:
c.exec = c.piping(exec)
}
return nil
}
// piping return the first arg if the length is 1, else return Pipe
func (c compiler) piping(args []Executor) Executor {
if len(args) == 1 {
return args[0]
}
return Pipe(args)
}
// compileExecutor return the Executor with the key and values
func (c compiler) compileExecutor(k, v *yaml.Node) (Executor, error) {
key := strings.TrimPrefix(k.Value, "$")
init, ok := GetExecutor(key)
if !ok {
return nil, c.newError("executor not found", k, errors.New(key))
}
args, err := c.compileNode(v)
if err != nil {
return nil, err
}
exec, err := init(args)
if err != nil {
return nil, c.newError(key, k, err)
}
if meta, ok := exec.(Meta); ok {
if err = meta.Meta(k, v); err != nil {
return nil, c.newError("meta", k, err)
}
}
switch {
case v.Anchor != "":
c.alias[v.Anchor] = args
case k.Anchor != "":
c.alias[k.Anchor] = args
}
return exec, nil
}
func (c compiler) getAlias(node *yaml.Node) ([]Executor, error) {
args, ok := c.alias[node.Value]
if !ok {
return c.compileNode(node.Alias)
}
return args, nil
}
func (c compiler) compileNode(node *yaml.Node) ([]Executor, error) {
switch node.Kind {
case yaml.MappingNode:
return c.compileMapping(node)
case yaml.SequenceNode:
return c.compileSequence(node)
case yaml.ScalarNode:
if node.Tag == "!!null" {
return []Executor{_raw{nil}}, nil
}
return []Executor{String(node.Value)}, nil
case yaml.AliasNode:
return c.getAlias(node)
default:
return nil, c.newError("invalid node type", node, nil)
}
}
func (c compiler) compileSequence(node *yaml.Node) ([]Executor, error) {
args := make([]Executor, 0, len(node.Content))
for _, item := range node.Content {
items, err := c.compileNode(item)
if err != nil {
return nil, err
}
args = append(args, c.piping(items))
}
return args, nil
}
func (c compiler) compileMapping(node *yaml.Node) ([]Executor, error) {
if len(node.Content) == 0 || len(node.Content)%2 != 0 {
return nil, c.newError("mapping node requires at least two elements", node, nil)
}
var prefixInit, prefix bool
ret := make([]Executor, 0, len(node.Content)/2)
for i := 0; i < len(node.Content); i += 2 {
keyNode, valueNode := node.Content[i], node.Content[i+1]
key := String(keyNode.Value)
if valueNode.Kind == yaml.AliasNode {
alias, err := c.getAlias(valueNode)
if err != nil {
return nil, err
}
switch {
case prefix:
// $key: *alias
name := strings.TrimPrefix(keyNode.Value, "$")
init, ok := GetExecutor(name)
if !ok {
return nil, c.newError("executor not found", keyNode, errors.New(keyNode.Value))
}
exec, err := init(alias)
if err != nil {
return nil, c.newError(name, keyNode, err)
}
if meta, ok := exec.(Meta); ok {
if err = meta.Meta(keyNode, valueNode); err != nil {
return nil, c.newError("meta", keyNode, err)
}
}
ret = append(ret, exec)
case keyNode.Tag == "!!merge":
// key: << *alias
ret = append(ret, alias...)
default:
// key: *alias
ret = append(ret, key, c.piping(alias))
}
continue
}
if valueNode.Kind == yaml.SequenceNode && keyNode.Tag == "!!merge" {
// key: [ *alias1, *alias2, ... ]
exec, err := c.compileSequence(valueNode)
if err != nil {
return nil, err
}
ret = append(ret, exec...)
continue
}
ok := strings.HasPrefix(keyNode.Value, "$")
if !prefixInit {
prefix = ok
prefixInit = true
}
switch {
case !ok && prefix || ok && !prefix:
return nil, c.newError("mix executor and map key", keyNode, nil)
case prefix:
// $key: value
exec, err := c.compileExecutor(keyNode, valueNode)
if err != nil {
return nil, err
}
ret = append(ret, exec)
default:
// key: value
value, err := c.compileNode(valueNode)
if err != nil {
return nil, err
}
ret = append(ret, key, c.piping(value))
}
}
return ret, nil
}
type _map []Executor
// mapping return a map with the key and values [k1, v1, k2, v2, ...]
// if the key Executor implements If and condition not met, it will be skipped
func mapping(args Arguments) (Executor, error) {
m := _map(args)
if len(m)%2 != 0 {
m = append(m, Raw(nil))
}
return m, nil
}
func (m _map) Exec(ctx context.Context, arg any) (any, error) {
var ret map[string]any
exec := func(arg any) {
for i := 0; i < len(m); i += 2 {
k, err := m[i].Exec(ctx, arg)
if err != nil {
continue
}
key, err := cast.ToStringE(k)
if err != nil {
continue
}
value, _ := m[i+1].Exec(ctx, arg)
ret[key] = value
}
}
v := reflect.ValueOf(arg)
switch v.Kind() {
case reflect.Slice:
ret = make(map[string]any, v.Len())
for i := 0; i < v.Len(); i++ {
exec(v.Index(i).Interface())
}
return ret, nil
default:
ret = make(map[string]any, len(m)/2)
exec(arg)
return ret, nil
}
}
type _each struct{ Executor }
// each loop the slice arg and execute the Executor,
// if Executor return ErrYield will be skipped.
func each(args Arguments) (Executor, error) {
if len(args) != 1 {
return nil, errors.New("each needs 1 parameter")
}
return _each{args.Get(0)}, nil
}
func (each _each) Exec(ctx context.Context, arg any) (any, error) {
v := reflect.ValueOf(arg)
switch v.Kind() {
case reflect.Slice:
ret := make([]any, 0, v.Len())
for i := 0; i < v.Len(); i++ {
v, err := each.Executor.Exec(ctx, v.Index(i).Interface())
if err != nil {
if errors.Is(err, ErrYield) {
continue
}
return nil, err
}
ret = append(ret, v)
}
return ret, nil
default:
ret, err := each.Executor.Exec(ctx, arg)
if err != nil {
return nil, err
}
return ret, nil
}
}
// Pipe executes a slice of Executor.
// if the Executor implements If and condition not met, it will be skipped.
type Pipe []Executor
// pipe executes a slice of Executor.
// if Executor return ErrYield will be stopped
func pipe(args Arguments) (Executor, error) { return Pipe(args), nil }
func (pipe Pipe) Exec(ctx context.Context, arg any) (ret any, err error) {
switch len(pipe) {
case 0:
return nil, nil
case 1:
return pipe[0].Exec(ctx, arg)
default:
ret = arg
for _, exec := range pipe {
ret, err = exec.Exec(ctx, ret)
switch {
case err != nil:
return nil, err
case ret == nil:
return nil, nil
}
}
return
}
}
// or executes a slice of Executor. return result if the Executor result is not nil.
func or(args Arguments) (Executor, error) { return _or(args), nil }
type _or []Executor
func (or _or) Exec(ctx context.Context, arg any) (any, error) {
for _, exec := range or {
v, err := exec.Exec(ctx, arg)
if err != nil {
continue
}
if v != nil {
return v, nil
}
}
return nil, nil
}
// Raw the Executor for raw value, return the original value
func Raw(arg any) Executor { return _raw{arg} }
// Raw the Executor for raw value, return the original value
func raw(args Arguments) (Executor, error) { return args.Get(0), nil }
type _raw struct{ any }
func (raw _raw) Exec(context.Context, any) (any, error) { return raw.any, nil }
// debug output the debug message and the origin arg
func debug(args Arguments) (Executor, error) {
return _debug(args.GetString(0)), nil
}
type _debug string
func (debug _debug) Exec(ctx context.Context, v any) (any, error) {
Logger(ctx).LogAttrs(ctx, slog.LevelDebug, string(debug), slog.Any("value", v))
return v, nil
}