-
Notifications
You must be signed in to change notification settings - Fork 812
/
functions.go
911 lines (807 loc) · 22.1 KB
/
functions.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
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
package jmespath
import (
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"path/filepath"
"reflect"
"regexp"
"sort"
"strconv"
"strings"
"time"
trunc "github.com/aquilax/truncate"
"github.com/blang/semver/v4"
gojmespath "github.com/jmespath/go-jmespath"
wildcard "github.com/kyverno/go-wildcard"
"sigs.k8s.io/yaml"
)
var (
JpObject = gojmespath.JpObject
JpString = gojmespath.JpString
JpNumber = gojmespath.JpNumber
JpArray = gojmespath.JpArray
JpArrayString = gojmespath.JpArrayString
JpAny = gojmespath.JpAny
JpBool = gojmespath.JpType("bool")
)
type (
JpType = gojmespath.JpType
ArgSpec = gojmespath.ArgSpec
)
// function names
var (
compare = "compare"
equalFold = "equal_fold"
replace = "replace"
replaceAll = "replace_all"
toUpper = "to_upper"
toLower = "to_lower"
trim = "trim"
split = "split"
regexReplaceAll = "regex_replace_all"
regexReplaceAllLiteral = "regex_replace_all_literal"
regexMatch = "regex_match"
patternMatch = "pattern_match"
labelMatch = "label_match"
add = "add"
subtract = "subtract"
multiply = "multiply"
divide = "divide"
modulo = "modulo"
base64Decode = "base64_decode"
base64Encode = "base64_encode"
timeSince = "time_since"
pathCanonicalize = "path_canonicalize"
truncate = "truncate"
semverCompare = "semver_compare"
parseJson = "parse_json"
parseYAML = "parse_yaml"
items = "items"
objectFromLists = "object_from_lists"
)
const errorPrefix = "JMESPath function '%s': "
const invalidArgumentTypeError = errorPrefix + "%d argument is expected of %s type"
const genericError = errorPrefix + "%s"
const zeroDivisionError = errorPrefix + "Zero divisor passed"
const undefinedQuoError = errorPrefix + "Undefined quotient"
const nonIntModuloError = errorPrefix + "Non-integer argument(s) passed for modulo"
type FunctionEntry struct {
Entry *gojmespath.FunctionEntry
Note string
ReturnType []JpType
}
func (f *FunctionEntry) String() string {
args := []string{}
for _, a := range f.Entry.Arguments {
aTypes := []string{}
for _, t := range a.Types {
aTypes = append(aTypes, string(t))
}
args = append(args, strings.Join(aTypes, "|"))
}
returnArgs := []string{}
for _, ra := range f.ReturnType {
returnArgs = append(returnArgs, string(ra))
}
output := fmt.Sprintf("%s(%s) %s", f.Entry.Name, strings.Join(args, ", "), strings.Join(returnArgs, ","))
if f.Note != "" {
output += fmt.Sprintf(" (%s)", f.Note)
}
return output
}
func GetFunctions() []*FunctionEntry {
return []*FunctionEntry{
{
Entry: &gojmespath.FunctionEntry{Name: compare,
Arguments: []ArgSpec{
{Types: []JpType{JpString}},
{Types: []JpType{JpString}},
},
Handler: jpfCompare,
},
ReturnType: []JpType{JpBool},
},
{
Entry: &gojmespath.FunctionEntry{Name: equalFold,
Arguments: []ArgSpec{
{Types: []JpType{JpString}},
{Types: []JpType{JpString}},
},
Handler: jpfEqualFold,
},
ReturnType: []JpType{JpBool},
},
{
Entry: &gojmespath.FunctionEntry{Name: replace,
Arguments: []ArgSpec{
{Types: []JpType{JpString}},
{Types: []JpType{JpString}},
{Types: []JpType{JpString}},
{Types: []JpType{JpNumber}},
},
Handler: jpfReplace,
},
ReturnType: []JpType{JpString},
},
{
Entry: &gojmespath.FunctionEntry{Name: replaceAll,
Arguments: []ArgSpec{
{Types: []JpType{JpString}},
{Types: []JpType{JpString}},
{Types: []JpType{JpString}},
},
Handler: jpfReplaceAll,
},
ReturnType: []JpType{JpString},
},
{
Entry: &gojmespath.FunctionEntry{Name: toUpper,
Arguments: []ArgSpec{
{Types: []JpType{JpString}},
},
Handler: jpfToUpper,
},
ReturnType: []JpType{JpString},
},
{
Entry: &gojmespath.FunctionEntry{Name: toLower,
Arguments: []ArgSpec{
{Types: []JpType{JpString}},
},
Handler: jpfToLower,
},
ReturnType: []JpType{JpString},
},
{
Entry: &gojmespath.FunctionEntry{Name: trim,
Arguments: []ArgSpec{
{Types: []JpType{JpString}},
{Types: []JpType{JpString}},
},
Handler: jpfTrim,
},
ReturnType: []JpType{JpString},
},
{
Entry: &gojmespath.FunctionEntry{Name: split,
Arguments: []ArgSpec{
{Types: []JpType{JpString}},
{Types: []JpType{JpString}},
},
Handler: jpfSplit,
},
ReturnType: []JpType{JpArrayString},
},
{
Entry: &gojmespath.FunctionEntry{Name: regexReplaceAll,
Arguments: []ArgSpec{
{Types: []JpType{JpString}},
{Types: []JpType{JpString, JpNumber}},
{Types: []JpType{JpString, JpNumber}},
},
Handler: jpRegexReplaceAll,
},
ReturnType: []JpType{JpString},
Note: "converts all parameters to string",
},
{
Entry: &gojmespath.FunctionEntry{Name: regexReplaceAllLiteral,
Arguments: []ArgSpec{
{Types: []JpType{JpString}},
{Types: []JpType{JpString, JpNumber}},
{Types: []JpType{JpString, JpNumber}},
},
Handler: jpRegexReplaceAllLiteral,
},
ReturnType: []JpType{JpString},
Note: "converts all parameters to string",
},
{
Entry: &gojmespath.FunctionEntry{Name: regexMatch,
Arguments: []ArgSpec{
{Types: []JpType{JpString}},
{Types: []JpType{JpString, JpNumber}},
},
Handler: jpRegexMatch,
},
ReturnType: []JpType{JpBool},
},
{
Entry: &gojmespath.FunctionEntry{Name: patternMatch,
Arguments: []ArgSpec{
{Types: []JpType{JpString}},
{Types: []JpType{JpString, JpNumber}},
},
Handler: jpPatternMatch,
},
ReturnType: []JpType{JpBool},
Note: "'*' matches zero or more alphanumeric characters, '?' matches a single alphanumeric character",
},
{
// Validates if label (param1) would match pod/host/etc labels (param2)
Entry: &gojmespath.FunctionEntry{Name: labelMatch,
Arguments: []ArgSpec{
{Types: []JpType{JpObject}},
{Types: []JpType{JpObject}},
},
Handler: jpLabelMatch,
},
ReturnType: []JpType{JpBool},
Note: "object arguments must be enclosed in backticks; ex. `{{request.object.spec.template.metadata.labels}}`",
},
{
Entry: &gojmespath.FunctionEntry{Name: add,
Arguments: []ArgSpec{
{Types: []JpType{JpAny}},
{Types: []JpType{JpAny}},
},
Handler: jpAdd,
},
ReturnType: []JpType{JpAny},
},
{
Entry: &gojmespath.FunctionEntry{Name: subtract,
Arguments: []ArgSpec{
{Types: []JpType{JpAny}},
{Types: []JpType{JpAny}},
},
Handler: jpSubtract,
},
ReturnType: []JpType{JpAny},
},
{
Entry: &gojmespath.FunctionEntry{Name: multiply,
Arguments: []ArgSpec{
{Types: []JpType{JpAny}},
{Types: []JpType{JpAny}},
},
Handler: jpMultiply,
},
ReturnType: []JpType{JpAny},
},
{
Entry: &gojmespath.FunctionEntry{Name: divide,
Arguments: []ArgSpec{
{Types: []JpType{JpAny}},
{Types: []JpType{JpAny}},
},
Handler: jpDivide,
},
ReturnType: []JpType{JpAny},
Note: "divisor must be non zero",
},
{
Entry: &gojmespath.FunctionEntry{Name: modulo,
Arguments: []ArgSpec{
{Types: []JpType{JpAny}},
{Types: []JpType{JpAny}},
},
Handler: jpModulo,
},
ReturnType: []JpType{JpAny},
Note: "divisor must be non-zero, arguments must be integers",
},
{
Entry: &gojmespath.FunctionEntry{Name: base64Decode,
Arguments: []ArgSpec{
{Types: []JpType{JpString}},
},
Handler: jpBase64Decode,
},
ReturnType: []JpType{JpString},
},
{
Entry: &gojmespath.FunctionEntry{Name: base64Encode,
Arguments: []ArgSpec{
{Types: []JpType{JpString}},
},
Handler: jpBase64Encode,
},
ReturnType: []JpType{JpString},
},
{
Entry: &gojmespath.FunctionEntry{Name: timeSince,
Arguments: []ArgSpec{
{Types: []JpType{JpString}},
{Types: []JpType{JpString}},
{Types: []JpType{JpString}},
},
Handler: jpTimeSince,
},
ReturnType: []JpType{JpString},
},
{
Entry: &gojmespath.FunctionEntry{Name: pathCanonicalize,
Arguments: []ArgSpec{
{Types: []JpType{JpString}},
},
Handler: jpPathCanonicalize,
},
ReturnType: []JpType{JpString},
},
{
Entry: &gojmespath.FunctionEntry{Name: truncate,
Arguments: []ArgSpec{
{Types: []JpType{JpString}},
{Types: []JpType{JpNumber}},
},
Handler: jpTruncate,
},
ReturnType: []JpType{JpString},
Note: "length argument must be enclosed in backticks; ex. \"{{request.object.metadata.name | truncate(@, `9`)}}\"",
},
{
Entry: &gojmespath.FunctionEntry{Name: semverCompare,
Arguments: []ArgSpec{
{Types: []JpType{JpString}},
{Types: []JpType{JpString}},
},
Handler: jpSemverCompare,
},
ReturnType: []JpType{JpBool},
},
{
Entry: &gojmespath.FunctionEntry{Name: parseJson,
Arguments: []ArgSpec{
{Types: []JpType{JpString}},
},
Handler: jpParseJson,
},
ReturnType: []JpType{JpAny},
Note: "decodes a valid JSON encoded string to the appropriate type. Opposite of `to_string` function",
},
{
Entry: &gojmespath.FunctionEntry{Name: parseYAML,
Arguments: []ArgSpec{
{Types: []JpType{JpString}},
},
Handler: jpParseYAML,
},
ReturnType: []JpType{JpAny},
Note: "decodes a valid YAML encoded string to the appropriate type provided it can be represented as JSON",
},
{
Entry: &gojmespath.FunctionEntry{Name: items,
Arguments: []ArgSpec{
{Types: []JpType{JpObject}},
{Types: []JpType{JpString}},
{Types: []JpType{JpString}},
},
Handler: jpItems,
},
ReturnType: []JpType{JpArray},
Note: "converts a map to an array of objects where each key:value is an item in the array",
},
{
Entry: &gojmespath.FunctionEntry{Name: objectFromLists,
Arguments: []ArgSpec{
{Types: []JpType{JpArray}},
{Types: []JpType{JpArray}},
},
Handler: jpObjectFromLists,
},
ReturnType: []JpType{JpObject},
Note: "converts a pair of lists containing keys and values to an object",
},
}
}
func jpfCompare(arguments []interface{}) (interface{}, error) {
var err error
a, err := validateArg(compare, arguments, 0, reflect.String)
if err != nil {
return nil, err
}
b, err := validateArg(compare, arguments, 1, reflect.String)
if err != nil {
return nil, err
}
return strings.Compare(a.String(), b.String()), nil
}
func jpfEqualFold(arguments []interface{}) (interface{}, error) {
var err error
a, err := validateArg(equalFold, arguments, 0, reflect.String)
if err != nil {
return nil, err
}
b, err := validateArg(equalFold, arguments, 1, reflect.String)
if err != nil {
return nil, err
}
return strings.EqualFold(a.String(), b.String()), nil
}
func jpfReplace(arguments []interface{}) (interface{}, error) {
var err error
str, err := validateArg(replace, arguments, 0, reflect.String)
if err != nil {
return nil, err
}
old, err := validateArg(replace, arguments, 1, reflect.String)
if err != nil {
return nil, err
}
new, err := validateArg(replace, arguments, 2, reflect.String)
if err != nil {
return nil, err
}
n, err := validateArg(replace, arguments, 3, reflect.Float64)
if err != nil {
return nil, err
}
return strings.Replace(str.String(), old.String(), new.String(), int(n.Float())), nil
}
func jpfReplaceAll(arguments []interface{}) (interface{}, error) {
var err error
str, err := validateArg(replaceAll, arguments, 0, reflect.String)
if err != nil {
return nil, err
}
old, err := validateArg(replaceAll, arguments, 1, reflect.String)
if err != nil {
return nil, err
}
new, err := validateArg(replaceAll, arguments, 2, reflect.String)
if err != nil {
return nil, err
}
return strings.ReplaceAll(str.String(), old.String(), new.String()), nil
}
func jpfToUpper(arguments []interface{}) (interface{}, error) {
var err error
str, err := validateArg(toUpper, arguments, 0, reflect.String)
if err != nil {
return nil, err
}
return strings.ToUpper(str.String()), nil
}
func jpfToLower(arguments []interface{}) (interface{}, error) {
var err error
str, err := validateArg(toLower, arguments, 0, reflect.String)
if err != nil {
return nil, err
}
return strings.ToLower(str.String()), nil
}
func jpfTrim(arguments []interface{}) (interface{}, error) {
var err error
str, err := validateArg(trim, arguments, 0, reflect.String)
if err != nil {
return nil, err
}
cutset, err := validateArg(trim, arguments, 1, reflect.String)
if err != nil {
return nil, err
}
return strings.Trim(str.String(), cutset.String()), nil
}
func jpfSplit(arguments []interface{}) (interface{}, error) {
var err error
str, err := validateArg(split, arguments, 0, reflect.String)
if err != nil {
return nil, err
}
sep, err := validateArg(split, arguments, 1, reflect.String)
if err != nil {
return nil, err
}
split := strings.Split(str.String(), sep.String())
arr := make([]interface{}, len(split))
for i, v := range split {
arr[i] = v
}
return arr, nil
}
func jpRegexReplaceAll(arguments []interface{}) (interface{}, error) {
var err error
regex, err := validateArg(regexReplaceAll, arguments, 0, reflect.String)
if err != nil {
return nil, err
}
src, err := ifaceToString(arguments[1])
if err != nil {
return nil, fmt.Errorf(invalidArgumentTypeError, regexReplaceAll, 2, "String or Real")
}
repl, err := ifaceToString(arguments[2])
if err != nil {
return nil, fmt.Errorf(invalidArgumentTypeError, regexReplaceAll, 3, "String or Real")
}
reg, err := regexp.Compile(regex.String())
if err != nil {
return nil, fmt.Errorf(genericError, regexReplaceAll, err.Error())
}
return string(reg.ReplaceAll([]byte(src), []byte(repl))), nil
}
func jpRegexReplaceAllLiteral(arguments []interface{}) (interface{}, error) {
var err error
regex, err := validateArg(regexReplaceAllLiteral, arguments, 0, reflect.String)
if err != nil {
return nil, err
}
src, err := ifaceToString(arguments[1])
if err != nil {
return nil, fmt.Errorf(invalidArgumentTypeError, regexReplaceAllLiteral, 2, "String or Real")
}
repl, err := ifaceToString(arguments[2])
if err != nil {
return nil, fmt.Errorf(invalidArgumentTypeError, regexReplaceAllLiteral, 3, "String or Real")
}
reg, err := regexp.Compile(regex.String())
if err != nil {
return nil, fmt.Errorf(genericError, regexReplaceAllLiteral, err.Error())
}
return string(reg.ReplaceAllLiteral([]byte(src), []byte(repl))), nil
}
func jpRegexMatch(arguments []interface{}) (interface{}, error) {
var err error
regex, err := validateArg(regexMatch, arguments, 0, reflect.String)
if err != nil {
return nil, err
}
src, err := ifaceToString(arguments[1])
if err != nil {
return nil, fmt.Errorf(invalidArgumentTypeError, regexMatch, 2, "String or Real")
}
return regexp.Match(regex.String(), []byte(src))
}
func jpPatternMatch(arguments []interface{}) (interface{}, error) {
pattern, err := validateArg(regexMatch, arguments, 0, reflect.String)
if err != nil {
return nil, err
}
src, err := ifaceToString(arguments[1])
if err != nil {
return nil, fmt.Errorf(invalidArgumentTypeError, regexMatch, 2, "String or Real")
}
return wildcard.Match(pattern.String(), src), nil
}
func jpLabelMatch(arguments []interface{}) (interface{}, error) {
labelMap, ok := arguments[0].(map[string]interface{})
if !ok {
return nil, fmt.Errorf(invalidArgumentTypeError, labelMatch, 0, "Object")
}
matchMap, ok := arguments[1].(map[string]interface{})
if !ok {
return nil, fmt.Errorf(invalidArgumentTypeError, labelMatch, 1, "Object")
}
for key, value := range labelMap {
if val, ok := matchMap[key]; !ok || val != value {
return false, nil
}
}
return true, nil
}
func jpAdd(arguments []interface{}) (interface{}, error) {
op1, op2, err := ParseArithemticOperands(arguments, add)
if err != nil {
return nil, err
}
return op1.Add(op2)
}
func jpSubtract(arguments []interface{}) (interface{}, error) {
op1, op2, err := ParseArithemticOperands(arguments, subtract)
if err != nil {
return nil, err
}
return op1.Subtract(op2)
}
func jpMultiply(arguments []interface{}) (interface{}, error) {
op1, op2, err := ParseArithemticOperands(arguments, multiply)
if err != nil {
return nil, err
}
return op1.Multiply(op2)
}
func jpDivide(arguments []interface{}) (interface{}, error) {
op1, op2, err := ParseArithemticOperands(arguments, divide)
if err != nil {
return nil, err
}
return op1.Divide(op2)
}
func jpModulo(arguments []interface{}) (interface{}, error) {
op1, op2, err := ParseArithemticOperands(arguments, modulo)
if err != nil {
return nil, err
}
return op1.Modulo(op2)
}
func jpBase64Decode(arguments []interface{}) (interface{}, error) {
var err error
str, err := validateArg("", arguments, 0, reflect.String)
if err != nil {
return nil, err
}
decodedStr, err := base64.StdEncoding.DecodeString(str.String())
if err != nil {
return nil, err
}
return string(decodedStr), nil
}
func jpBase64Encode(arguments []interface{}) (interface{}, error) {
var err error
str, err := validateArg("", arguments, 0, reflect.String)
if err != nil {
return nil, err
}
return base64.StdEncoding.EncodeToString([]byte(str.String())), nil
}
func jpTimeSince(arguments []interface{}) (interface{}, error) {
var err error
layout, err := validateArg("", arguments, 0, reflect.String)
if err != nil {
return nil, err
}
ts1, err := validateArg("", arguments, 1, reflect.String)
if err != nil {
return nil, err
}
ts2, err := validateArg("", arguments, 2, reflect.String)
if err != nil {
return nil, err
}
var t1, t2 time.Time
if layout.String() != "" {
t1, err = time.Parse(layout.String(), ts1.String())
} else {
t1, err = time.Parse(time.RFC3339, ts1.String())
}
if err != nil {
return nil, err
}
t2 = time.Now()
if ts2.String() != "" {
if layout.String() != "" {
t2, err = time.Parse(layout.String(), ts2.String())
} else {
t2, err = time.Parse(time.RFC3339, ts2.String())
}
if err != nil {
return nil, err
}
}
return t2.Sub(t1).String(), nil
}
func jpPathCanonicalize(arguments []interface{}) (interface{}, error) {
var err error
str, err := validateArg(pathCanonicalize, arguments, 0, reflect.String)
if err != nil {
return nil, err
}
return filepath.Join(str.String()), nil
}
func jpTruncate(arguments []interface{}) (interface{}, error) {
var err error
var normalizedLength float64
str, err := validateArg(truncate, arguments, 0, reflect.String)
if err != nil {
return nil, err
}
length, err := validateArg(truncate, arguments, 1, reflect.Float64)
if err != nil {
return nil, err
}
if length.Float() < 0 {
normalizedLength = float64(0)
} else {
normalizedLength = length.Float()
}
return trunc.Truncator(str.String(), int(normalizedLength), trunc.CutStrategy{}), nil
}
func jpSemverCompare(arguments []interface{}) (interface{}, error) {
var err error
v, err := validateArg(semverCompare, arguments, 0, reflect.String)
if err != nil {
return nil, err
}
r, err := validateArg(semverCompare, arguments, 1, reflect.String)
if err != nil {
return nil, err
}
version, _ := semver.Parse(v.String())
expectedRange, err := semver.ParseRange(r.String())
if err != nil {
return nil, err
}
if expectedRange(version) {
return true, nil
}
return false, nil
}
func jpParseJson(arguments []interface{}) (interface{}, error) {
input, err := validateArg(parseJson, arguments, 0, reflect.String)
if err != nil {
return nil, err
}
var output interface{}
err = json.Unmarshal([]byte(input.String()), &output)
return output, err
}
func jpParseYAML(arguments []interface{}) (interface{}, error) {
input, err := validateArg(parseYAML, arguments, 0, reflect.String)
if err != nil {
return nil, err
}
jsonData, err := yaml.YAMLToJSON([]byte(input.String()))
if err != nil {
return nil, err
}
var output interface{}
err = json.Unmarshal(jsonData, &output)
return output, err
}
func jpItems(arguments []interface{}) (interface{}, error) {
input, ok := arguments[0].(map[string]interface{})
if !ok {
return nil, fmt.Errorf(invalidArgumentTypeError, arguments, 0, "Object")
}
keyName, ok := arguments[1].(string)
if !ok {
return nil, fmt.Errorf(invalidArgumentTypeError, arguments, 1, "String")
}
valName, ok := arguments[2].(string)
if !ok {
return nil, fmt.Errorf(invalidArgumentTypeError, arguments, 2, "String")
}
arrayOfObj := make([]map[string]interface{}, 0)
keys := []string{}
// Sort the keys so that the output is deterministic
for key := range input {
keys = append(keys, key)
}
sort.Strings(keys)
for _, key := range keys {
m := make(map[string]interface{})
m[keyName] = key
m[valName] = input[key]
arrayOfObj = append(arrayOfObj, m)
}
return arrayOfObj, nil
}
func jpObjectFromLists(arguments []interface{}) (interface{}, error) {
keys, ok := arguments[0].([]interface{})
if !ok {
return nil, fmt.Errorf(invalidArgumentTypeError, arguments, 0, "Array")
}
values, ok := arguments[1].([]interface{})
if !ok {
return nil, fmt.Errorf(invalidArgumentTypeError, arguments, 1, "Array")
}
output := map[string]interface{}{}
for i, ikey := range keys {
key, err := ifaceToString(ikey)
if err != nil {
return nil, fmt.Errorf(invalidArgumentTypeError, arguments, 0, "StringArray")
}
if i < len(values) {
output[key] = values[i]
} else {
output[key] = nil
}
}
return output, nil
}
// InterfaceToString casts an interface to a string type
func ifaceToString(iface interface{}) (string, error) {
switch i := iface.(type) {
case int:
return strconv.Itoa(i), nil
case float64:
return strconv.FormatFloat(i, 'f', -1, 32), nil
case float32:
return strconv.FormatFloat(float64(i), 'f', -1, 32), nil
case string:
return i, nil
case bool:
return strconv.FormatBool(i), nil
default:
return "", errors.New("error, undefined type cast")
}
}
func validateArg(f string, arguments []interface{}, index int, expectedType reflect.Kind) (reflect.Value, error) {
arg := reflect.ValueOf(arguments[index])
if arg.Type().Kind() != expectedType {
return reflect.Value{}, fmt.Errorf(invalidArgumentTypeError, f, index+1, expectedType.String())
}
return arg, nil
}