forked from crossplane-contrib/function-patch-and-transform
-
Notifications
You must be signed in to change notification settings - Fork 1
/
transforms.go
483 lines (442 loc) · 17.5 KB
/
transforms.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
package main
import (
"crypto/sha1" //nolint:gosec // Not used for secure hashing
"crypto/sha256"
"crypto/sha512"
"encoding/base64"
"encoding/hex"
"encoding/json"
"fmt"
"hash/adler32"
"regexp"
"strconv"
"strings"
extv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
"k8s.io/apimachinery/pkg/api/resource"
"k8s.io/utils/ptr"
"github.com/crossplane/crossplane-runtime/pkg/errors"
"github.com/stevendborrelli/function-conditional-patch-and-transform/input/v1beta1"
)
const (
errMathTransformTypeFailed = "type %s is not supported for math transform type"
errFmtMathInputNonNumber = "input is required to be a number for math transformer, got %T"
errFmtRequiredField = "%s is required by type %s"
errFmtConvertInputTypeNotSupported = "invalid input type %T"
errFmtConvertFormatPairNotSupported = "conversion from %s to %s is not supported with format %s"
errFmtTransformAtIndex = "transform at index %d returned error"
errFmtTypeNotSupported = "transform type %s is not supported"
errFmtTransformConfigMissing = "given transform type %s requires configuration"
errFmtTransformTypeFailed = "%s transform could not resolve"
errFmtMapTypeNotSupported = "type %s is not supported for map transform"
errFmtMapNotFound = "key %s is not found in map"
errFmtMapInvalidJSON = "value for key %s is not valid JSON"
errFmtMatchPattern = "cannot match pattern at index %d"
errFmtMatchParseResult = "cannot parse result of pattern at index %d"
errMatchParseFallbackValue = "cannot parse fallback value"
errMatchFallbackBoth = "cannot set both a fallback value and the fallback to input flag"
errFmtMatchPatternTypeInvalid = "unsupported pattern type '%s'"
errFmtMatchInputTypeInvalid = "unsupported input type '%s'"
errMatchRegexpCompile = "cannot compile regexp"
errStringTransformTypeFailed = "type %s is not supported for string transform type"
errStringTransformTypeFormat = "string transform of type %s fmt is not set"
errStringTransformTypeConvert = "string transform of type %s convert is not set"
errStringTransformTypeTrim = "string transform of type %s trim is not set"
errStringTransformTypeRegexp = "string transform of type %s regexp is not set"
errStringTransformTypeRegexpFailed = "could not compile regexp"
errStringTransformTypeRegexpNoMatch = "regexp %q had no matches for group %d"
errStringConvertTypeFailed = "type %s is not supported for string convert"
errDecodeString = "string is not valid base64"
errMarshalJSON = "cannot marshal to JSON"
errHash = "cannot generate hash"
errAdler = "unable to generate Adler checksum"
)
// Resolve the supplied Transform.
func Resolve(t v1beta1.Transform, input any) (any, error) { //nolint:gocyclo // This is a long but simple/same-y switch.
var out any
var err error
switch t.Type {
case v1beta1.TransformTypeMath:
if t.Math == nil {
return nil, errors.Errorf(errFmtTransformConfigMissing, t.Type)
}
out, err = ResolveMath(t.Math, input)
case v1beta1.TransformTypeMap:
if t.Map == nil {
return nil, errors.Errorf(errFmtTransformConfigMissing, t.Type)
}
out, err = ResolveMap(t.Map, input)
case v1beta1.TransformTypeMatch:
if t.Match == nil {
return nil, errors.Errorf(errFmtTransformConfigMissing, t.Type)
}
out, err = ResolveMatch(t.Match, input)
case v1beta1.TransformTypeString:
if t.String == nil {
return nil, errors.Errorf(errFmtTransformConfigMissing, t.Type)
}
out, err = ResolveString(t.String, input)
case v1beta1.TransformTypeConvert:
if t.Convert == nil {
return nil, errors.Errorf(errFmtTransformConfigMissing, t.Type)
}
out, err = ResolveConvert(t.Convert, input)
default:
return nil, errors.Errorf(errFmtTypeNotSupported, string(t.Type))
}
return out, errors.Wrapf(err, errFmtTransformTypeFailed, string(t.Type))
}
// ResolveMath resolves a Math transform.
func ResolveMath(t *v1beta1.MathTransform, input any) (any, error) {
if err := ValidateMathTransform(t); err != nil {
return nil, err
}
switch input.(type) {
case int, int64, float64:
default:
return nil, errors.Errorf(errFmtMathInputNonNumber, input)
}
switch t.Type {
case v1beta1.MathTransformTypeMultiply:
return resolveMathMultiply(t, input)
case v1beta1.MathTransformTypeClampMin, v1beta1.MathTransformTypeClampMax:
return resolveMathClamp(t, input)
default:
return nil, errors.Errorf(errMathTransformTypeFailed, string(t.Type))
}
}
// resolveMathMultiply resolves a multiply transform, returning an error if the
// input is not a number. If the input is a float, the result will be a float64, otherwise
// it will be an int64.
func resolveMathMultiply(t *v1beta1.MathTransform, input any) (any, error) {
switch i := input.(type) {
case int:
return int64(i) * *t.Multiply, nil
case int64:
return i * *t.Multiply, nil
case float64:
return i * float64(*t.Multiply), nil
default:
return nil, errors.Errorf(errFmtMathInputNonNumber, input)
}
}
// resolveMathClamp resolves a clamp transform, returning an error if the input
// is not a number. depending on the type of clamp, the result will be either
// the input or the clamp value, preserving their original types.
func resolveMathClamp(t *v1beta1.MathTransform, input any) (any, error) {
in := int64(0)
switch i := input.(type) {
case int:
in = int64(i)
case int64:
in = i
case float64:
in = int64(i)
default:
// should never happen as we validate the input type in ResolveMath
return nil, errors.Errorf(errFmtMathInputNonNumber, input)
}
switch t.Type { //nolint:exhaustive // We validate the type in ResolveMath
case v1beta1.MathTransformTypeClampMin:
if in < *t.ClampMin {
return *t.ClampMin, nil
}
case v1beta1.MathTransformTypeClampMax:
if in > *t.ClampMax {
return *t.ClampMax, nil
}
default:
return nil, errors.Errorf(errMathTransformTypeFailed, string(t.Type))
}
return input, nil
}
// ResolveMap resolves a Map transform.
func ResolveMap(t *v1beta1.MapTransform, input any) (any, error) {
switch i := input.(type) {
case string:
p, ok := t.Pairs[i]
if !ok {
return nil, errors.Errorf(errFmtMapNotFound, i)
}
var val interface{}
if err := json.Unmarshal(p.Raw, &val); err != nil {
return nil, errors.Wrapf(err, errFmtMapInvalidJSON, i)
}
return val, nil
default:
return nil, errors.Errorf(errFmtMapTypeNotSupported, fmt.Sprintf("%T", input))
}
}
// ResolveMatch resolves a Match transform.
func ResolveMatch(t *v1beta1.MatchTransform, input any) (any, error) {
var output any
for i, p := range t.Patterns {
matches, err := Matches(p, input)
if err != nil {
return nil, errors.Wrapf(err, errFmtMatchPattern, i)
}
if matches {
if err := unmarshalJSON(p.Result, &output); err != nil {
return nil, errors.Wrapf(err, errFmtMatchParseResult, i)
}
return output, nil
}
}
// Fallback to input if no pattern matches and fallback to input is set
if t.FallbackTo == v1beta1.MatchFallbackToTypeInput {
if t.FallbackValue.Size() != 0 {
return nil, errors.New(errMatchFallbackBoth)
}
return input, nil
}
// Use fallback value if no pattern matches (or if there are no patterns)
if err := unmarshalJSON(t.FallbackValue, &output); err != nil {
return nil, errors.Wrap(err, errMatchParseFallbackValue)
}
return output, nil
}
// Matches returns true if the pattern matches the supplied input.
func Matches(p v1beta1.MatchTransformPattern, input any) (bool, error) {
switch p.Type {
case v1beta1.MatchTransformPatternTypeLiteral:
return matchesLiteral(p, input)
case v1beta1.MatchTransformPatternTypeRegexp:
return matchesRegexp(p, input)
}
return false, errors.Errorf(errFmtMatchPatternTypeInvalid, string(p.Type))
}
func matchesLiteral(p v1beta1.MatchTransformPattern, input any) (bool, error) {
if p.Literal == nil {
return false, errors.Errorf(errFmtRequiredField, "literal", v1beta1.MatchTransformPatternTypeLiteral)
}
inputStr, ok := input.(string)
if !ok {
return false, errors.Errorf(errFmtMatchInputTypeInvalid, fmt.Sprintf("%T", input))
}
return inputStr == *p.Literal, nil
}
func matchesRegexp(p v1beta1.MatchTransformPattern, input any) (bool, error) {
if p.Regexp == nil {
return false, errors.Errorf(errFmtRequiredField, "regexp", v1beta1.MatchTransformPatternTypeRegexp)
}
re, err := regexp.Compile(*p.Regexp)
if err != nil {
return false, errors.Wrap(err, errMatchRegexpCompile)
}
if input == nil {
return false, errors.Errorf(errFmtMatchInputTypeInvalid, "null")
}
inputStr, ok := input.(string)
if !ok {
return false, errors.Errorf(errFmtMatchInputTypeInvalid, fmt.Sprintf("%T", input))
}
return re.MatchString(inputStr), nil
}
// unmarshalJSON is a small utility function that returns nil if j contains no
// data. json.Unmarshal seems to not be able to handle this.
func unmarshalJSON(j extv1.JSON, output *any) error {
if len(j.Raw) == 0 {
return nil
}
return json.Unmarshal(j.Raw, output)
}
// ResolveString resolves a String transform.
func ResolveString(t *v1beta1.StringTransform, input any) (string, error) {
switch t.Type {
case v1beta1.StringTransformTypeFormat:
if t.Format == nil {
return "", errors.Errorf(errStringTransformTypeFormat, string(t.Type))
}
return fmt.Sprintf(*t.Format, input), nil
case v1beta1.StringTransformTypeConvert:
if t.Convert == nil {
return "", errors.Errorf(errStringTransformTypeConvert, string(t.Type))
}
return stringConvertTransform(t.Convert, input)
case v1beta1.StringTransformTypeTrimPrefix, v1beta1.StringTransformTypeTrimSuffix:
if t.Trim == nil {
return "", errors.Errorf(errStringTransformTypeTrim, string(t.Type))
}
return stringTrimTransform(input, t.Type, *t.Trim), nil
case v1beta1.StringTransformTypeRegexp:
if t.Regexp == nil {
return "", errors.Errorf(errStringTransformTypeRegexp, string(t.Type))
}
return stringRegexpTransform(input, *t.Regexp)
default:
return "", errors.Errorf(errStringTransformTypeFailed, string(t.Type))
}
}
func stringConvertTransform(t *v1beta1.StringConversionType, input any) (string, error) {
str := fmt.Sprintf("%v", input)
switch *t {
case v1beta1.StringConversionTypeToUpper:
return strings.ToUpper(str), nil
case v1beta1.StringConversionTypeToLower:
return strings.ToLower(str), nil
case v1beta1.StringConversionTypeToJSON:
raw, err := json.Marshal(input)
return string(raw), errors.Wrap(err, errMarshalJSON)
case v1beta1.StringConversionTypeToBase64:
return base64.StdEncoding.EncodeToString([]byte(str)), nil
case v1beta1.StringConversionTypeFromBase64:
s, err := base64.StdEncoding.DecodeString(str)
return string(s), errors.Wrap(err, errDecodeString)
case v1beta1.StringConversionTypeToSHA1:
hash, err := stringGenerateHash(input, sha1.Sum)
return hex.EncodeToString(hash[:]), errors.Wrap(err, errHash)
case v1beta1.StringConversionTypeToSHA256:
hash, err := stringGenerateHash(input, sha256.Sum256)
return hex.EncodeToString(hash[:]), errors.Wrap(err, errHash)
case v1beta1.StringConversionTypeToSHA512:
hash, err := stringGenerateHash(input, sha512.Sum512)
return hex.EncodeToString(hash[:]), errors.Wrap(err, errHash)
case v1beta1.StringConversionTypeToAdler32:
checksum, err := stringGenerateHash(input, adler32.Checksum)
return strconv.FormatUint(uint64(checksum), 10), errors.Wrap(err, errAdler)
default:
return "", errors.Errorf(errStringConvertTypeFailed, *t)
}
}
func stringGenerateHash[THash any](input any, hashFunc func([]byte) THash) (THash, error) {
var b []byte
var err error
switch v := input.(type) {
case string:
b = []byte(v)
default:
b, err = json.Marshal(input)
if err != nil {
var ret THash
return ret, errors.Wrap(err, errMarshalJSON)
}
}
return hashFunc(b), nil
}
func stringTrimTransform(input any, t v1beta1.StringTransformType, trim string) string {
str := fmt.Sprintf("%v", input)
if t == v1beta1.StringTransformTypeTrimPrefix {
return strings.TrimPrefix(str, trim)
}
if t == v1beta1.StringTransformTypeTrimSuffix {
return strings.TrimSuffix(str, trim)
}
return str
}
func stringRegexpTransform(input any, r v1beta1.StringTransformRegexp) (string, error) {
re, err := regexp.Compile(r.Match)
if err != nil {
return "", errors.Wrap(err, errStringTransformTypeRegexpFailed)
}
groups := re.FindStringSubmatch(fmt.Sprintf("%v", input))
// Return the entire match (group zero) by default.
g := ptr.Deref[int](r.Group, 0)
if len(groups) == 0 || g >= len(groups) {
return "", errors.Errorf(errStringTransformTypeRegexpNoMatch, r.Match, g)
}
return groups[g], nil
}
// ResolveConvert resolves a Convert transform by looking up the appropriate
// conversion function for the given input type and invoking it.
func ResolveConvert(t *v1beta1.ConvertTransform, input any) (any, error) {
if err := ValidateConvertTransform(t); err != nil {
return nil, err
}
from := v1beta1.TransformIOType(fmt.Sprintf("%T", input))
if !from.IsValid() {
return nil, errors.Errorf(errFmtConvertInputTypeNotSupported, input)
}
f, err := GetConversionFunc(t, from)
if err != nil {
return nil, err
}
return f(input)
}
type conversionPair struct {
from v1beta1.TransformIOType
to v1beta1.TransformIOType
format v1beta1.ConvertTransformFormat
}
// GetConversionFunc returns the conversion function for the given input and output types, or an error if no conversion is
// supported. Will return a no-op conversion if the input and output types are the same.
func GetConversionFunc(t *v1beta1.ConvertTransform, from v1beta1.TransformIOType) (func(any) (any, error), error) {
originalFrom := from
to := t.ToType
if to == v1beta1.TransformIOTypeInt {
to = v1beta1.TransformIOTypeInt64
}
if from == v1beta1.TransformIOTypeInt {
from = v1beta1.TransformIOTypeInt64
}
if to == from {
return func(input any) (any, error) {
return input, nil
}, nil
}
f, ok := conversions[conversionPair{from: from, to: to, format: t.GetFormat()}]
if !ok {
return nil, errors.Errorf(v1beta1.ErrFmtConvertFormatPairNotSupported, originalFrom, to, t.GetFormat())
}
return f, nil
}
// The unparam linter is complaining that these functions always return a nil
// error, but we need this to be the case given some other functions in the map
// may return an error.
var conversions = map[conversionPair]func(any) (any, error){
{from: v1beta1.TransformIOTypeString, to: v1beta1.TransformIOTypeInt64, format: v1beta1.ConvertTransformFormatNone}: func(i any) (any, error) {
return strconv.ParseInt(i.(string), 10, 64)
},
{from: v1beta1.TransformIOTypeString, to: v1beta1.TransformIOTypeBool, format: v1beta1.ConvertTransformFormatNone}: func(i any) (any, error) {
return strconv.ParseBool(i.(string))
},
{from: v1beta1.TransformIOTypeString, to: v1beta1.TransformIOTypeFloat64, format: v1beta1.ConvertTransformFormatNone}: func(i any) (any, error) {
return strconv.ParseFloat(i.(string), 64)
},
{from: v1beta1.TransformIOTypeString, to: v1beta1.TransformIOTypeFloat64, format: v1beta1.ConvertTransformFormatQuantity}: func(i any) (any, error) {
q, err := resource.ParseQuantity(i.(string))
if err != nil {
return nil, err
}
return q.AsApproximateFloat64(), nil
},
{from: v1beta1.TransformIOTypeInt64, to: v1beta1.TransformIOTypeString, format: v1beta1.ConvertTransformFormatNone}: func(i any) (any, error) { //nolint:unparam // See note above.
return strconv.FormatInt(i.(int64), 10), nil
},
{from: v1beta1.TransformIOTypeInt64, to: v1beta1.TransformIOTypeBool, format: v1beta1.ConvertTransformFormatNone}: func(i any) (any, error) { //nolint:unparam // See note above.
return i.(int64) == 1, nil
},
{from: v1beta1.TransformIOTypeInt64, to: v1beta1.TransformIOTypeFloat64, format: v1beta1.ConvertTransformFormatNone}: func(i any) (any, error) { //nolint:unparam // See note above.
return float64(i.(int64)), nil
},
{from: v1beta1.TransformIOTypeBool, to: v1beta1.TransformIOTypeString, format: v1beta1.ConvertTransformFormatNone}: func(i any) (any, error) { //nolint:unparam // See note above.
return strconv.FormatBool(i.(bool)), nil
},
{from: v1beta1.TransformIOTypeBool, to: v1beta1.TransformIOTypeInt64, format: v1beta1.ConvertTransformFormatNone}: func(i any) (any, error) { //nolint:unparam // See note above.
if i.(bool) {
return int64(1), nil
}
return int64(0), nil
},
{from: v1beta1.TransformIOTypeBool, to: v1beta1.TransformIOTypeFloat64, format: v1beta1.ConvertTransformFormatNone}: func(i any) (any, error) { //nolint:unparam // See note above.
if i.(bool) {
return float64(1), nil
}
return float64(0), nil
},
{from: v1beta1.TransformIOTypeFloat64, to: v1beta1.TransformIOTypeString, format: v1beta1.ConvertTransformFormatNone}: func(i any) (any, error) { //nolint:unparam // See note above.
return strconv.FormatFloat(i.(float64), 'f', -1, 64), nil
},
{from: v1beta1.TransformIOTypeFloat64, to: v1beta1.TransformIOTypeInt64, format: v1beta1.ConvertTransformFormatNone}: func(i any) (any, error) { //nolint:unparam // See note above.
return int64(i.(float64)), nil
},
{from: v1beta1.TransformIOTypeFloat64, to: v1beta1.TransformIOTypeBool, format: v1beta1.ConvertTransformFormatNone}: func(i any) (any, error) { //nolint:unparam // See note above.
return i.(float64) == float64(1), nil
},
{from: v1beta1.TransformIOTypeString, to: v1beta1.TransformIOTypeObject, format: v1beta1.ConvertTransformFormatJSON}: func(i any) (any, error) {
o := map[string]any{}
return o, json.Unmarshal([]byte(i.(string)), &o)
},
{from: v1beta1.TransformIOTypeString, to: v1beta1.TransformIOTypeArray, format: v1beta1.ConvertTransformFormatJSON}: func(i any) (any, error) {
var o []any
return o, json.Unmarshal([]byte(i.(string)), &o)
},
}