-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcomparison.go
640 lines (562 loc) · 16.8 KB
/
comparison.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
package validation
import (
"context"
"fmt"
"math/big"
"strings"
"sync"
"github.com/dcarbone/terraform-plugin-framework-utils/v3/conv"
"github.com/dcarbone/terraform-plugin-framework-utils/v3/internal/util"
"github.com/hashicorp/terraform-plugin-framework/attr"
"github.com/hashicorp/terraform-plugin-framework/types"
)
type CompareOp string
const (
Equal CompareOp = "=="
LessThan CompareOp = "<"
LessThanOrEqualTo CompareOp = "<="
GreaterThan CompareOp = ">"
GreaterThanOrEqualTo CompareOp = ">="
NotEqual CompareOp = "<>"
OneOf CompareOp = "|"
NotOneOf CompareOp = "^|"
)
func (op CompareOp) String() string {
return string(op)
}
func (op CompareOp) Name() string {
switch op {
case Equal:
return "equal"
case LessThan:
return "less_than"
case LessThanOrEqualTo:
return "less_than_or_equal_to"
case GreaterThan:
return "greater_than"
case GreaterThanOrEqualTo:
return "greater_than_or_equal_to"
case NotEqual:
return "not_equal"
case OneOf:
return "one_of"
case NotOneOf:
return "not_one_of"
default:
return string(op)
}
}
// ComparisonFunc executes a specific comparison of an attribute value to the targeted value. You are guaranteed that
// the target type will be the type or one of the types the function was registered with. If you register a single func
// with more than type target type, you must perform type assertion / conversion yourself.
//
// The returned error is expected to be testable for type:
//
// nil - Comparison succeeded
// ErrComparisonFailed - Must be returned when any comparison operation fails
// ErrTypeConversionFailed - Must be returned if the function performs an internal type conversion before comparison that errored
// any other error - Treated as unhandled error
//
// To see the default list of functions, see DefaultComparisonFuncs.
//
// To register a new function or overwrite an existing function, see SetComparisonFunc
type ComparisonFunc func(ctx context.Context, av attr.Value, op CompareOp, target interface{}, meta ...interface{}) error
var (
comparisonFuncsMu sync.Mutex
comparisonFuncs map[string]ComparisonFunc
)
func compareBool(ctx context.Context, av attr.Value, op CompareOp, target interface{}, _ ...interface{}) error {
actBool := conv.BoolValueToBool(av)
expBool, err := util.TryCoerceToBool(target)
if err != nil {
return UnexpectedComparisonTargetTypeError("compare_bool", target, op, true, err)
}
switch op {
case Equal:
if actBool == expBool {
return nil
}
case NotEqual:
if actBool != expBool {
return nil
}
default:
return NoComparisonFuncRegisteredError(op, av)
}
return ComparisonFailedError(actBool, op, expBool)
}
func compareFloat64(_ context.Context, av attr.Value, op CompareOp, target interface{}, _ ...interface{}) error {
actF64, _, err := conv.AttributeValueToFloat64(av)
if err != nil {
return TypeConversionFailedError(err)
}
expF64, err := util.TryCoerceToFloat64(target)
if err != nil {
return UnexpectedComparisonTargetTypeError("compare_float64", target, op, float64(0), err)
}
switch op {
case Equal:
if actF64 == expF64 {
return nil
}
case NotEqual:
if actF64 != expF64 {
return nil
}
case GreaterThan:
if actF64 > expF64 {
return nil
}
case GreaterThanOrEqualTo:
if actF64 >= expF64 {
return nil
}
case LessThan:
if actF64 < expF64 {
return nil
}
case LessThanOrEqualTo:
if actF64 <= expF64 {
return nil
}
default:
return NoComparisonFuncRegisteredError(op, av)
}
return ComparisonFailedError(actF64, op, expF64)
}
func compareInt64(_ context.Context, av attr.Value, op CompareOp, target interface{}, _ ...interface{}) error {
actI64, _, err := conv.AttributeValueToInt64(av)
if err != nil {
return TypeConversionFailedError(err)
}
tgtI64, err := util.TryCoerceToInt64(target)
if err != nil {
return UnexpectedComparisonTargetTypeError("compare_int64", target, op, int64(0), err)
}
switch op {
case Equal:
if actI64 == tgtI64 {
return nil
}
case NotEqual:
if actI64 != tgtI64 {
return nil
}
case GreaterThan:
if actI64 > tgtI64 {
return nil
}
case GreaterThanOrEqualTo:
if actI64 >= tgtI64 {
return nil
}
case LessThan:
if actI64 < tgtI64 {
return nil
}
case LessThanOrEqualTo:
if actI64 <= tgtI64 {
return nil
}
default:
return NoComparisonFuncRegisteredError(op, av)
}
return ComparisonFailedError(actI64, op, tgtI64)
}
func compareInt(ctx context.Context, av attr.Value, op CompareOp, target interface{}, _ ...interface{}) error {
return compareInt64(ctx, av, op, int64(target.(int)))
}
func compareBigFloat(_ context.Context, av attr.Value, op CompareOp, target interface{}, _ ...interface{}) error {
actualBF := conv.NumberValueToBigFloat(av)
expectedBF, err := util.TryCoerceToBigFloat(target)
if err != nil {
return UnexpectedComparisonTargetTypeError("compare_bigfloat", target, op, (*big.Float)(nil), nil)
}
cmp := actualBF.Cmp(expectedBF)
switch op {
case Equal:
if cmp == 0 {
return nil
}
case NotEqual:
if cmp == 0 {
exp, _ := expectedBF.Float64()
act, _ := actualBF.Float64()
return ComparisonFailedError(act, op, exp)
}
case GreaterThan:
if cmp == 1 {
return nil
}
case GreaterThanOrEqualTo:
if cmp == 0 || cmp == 1 {
return nil
}
case LessThan:
if cmp == -1 {
return nil
}
case LessThanOrEqualTo:
if cmp == -1 || cmp == 0 {
return nil
}
default:
return NoComparisonFuncRegisteredError(op, av)
}
exp, _ := expectedBF.Float64()
act, _ := actualBF.Float64()
return ComparisonFailedError(act, op, exp)
}
func compareString(_ context.Context, av attr.Value, op CompareOp, target interface{}, meta ...interface{}) error {
var caseInsensitive bool
if len(meta) > 0 {
if b, ok := meta[0].(bool); ok {
caseInsensitive = b
}
}
actStr := conv.AttributeValueToString(av)
tgtStr, ok := target.(string)
if !ok {
return UnexpectedComparisonTargetTypeError("compare_string", target, op, "", nil)
}
if caseInsensitive {
actStr = strings.ToLower(actStr)
tgtStr = strings.ToLower(tgtStr)
}
switch op {
case Equal:
if actStr == tgtStr {
return nil
}
case NotEqual:
if actStr != tgtStr {
return nil
}
default:
return NoComparisonFuncRegisteredError(op, av)
}
return ComparisonFailedError(actStr, op, tgtStr)
}
func compareStringToStrings(av types.String, op CompareOp, targets []string, caseInsensitive bool) error {
var actStr string
if caseInsensitive {
actStr = strings.ToLower(av.ValueString())
for i, v := range targets {
targets[i] = strings.ToLower(v)
}
} else {
actStr = av.ValueString()
}
switch op {
case OneOf:
for _, v := range targets {
if actStr == v {
return nil
}
}
case NotOneOf:
for _, v := range targets {
if actStr == v {
return ComparisonFailedError(targets, op, actStr)
}
}
return nil
default:
return NoComparisonFuncRegisteredError(op, targets)
}
return ComparisonFailedError(av.ValueString(), op, targets)
}
func compareStringsToStrings(actuals []string, op CompareOp, targets []string, caseInsensitive bool) error {
if caseInsensitive {
for i, v := range targets {
targets[i] = strings.ToLower(v)
}
for i, v := range actuals {
actuals[i] = strings.ToLower(v)
}
}
actualsLen := len(actuals)
targetsLen := len(targets)
switch op {
case Equal:
if actualsLen == targetsLen {
for i, v := range actuals {
if targets[i] != v {
return ComparisonFailedError(actuals[i], op, targets[i])
}
}
return nil
}
case NotEqual:
if actualsLen != targetsLen {
return nil
}
for i, v := range actuals {
if targets[i] != v {
return nil
}
}
default:
return NoComparisonFuncRegisteredError(op, make([]string, 0))
}
return ComparisonFailedError(actuals, op, targets)
}
func compareListToStrings(ctx context.Context, av types.List, op CompareOp, targets []string, caseInsensitive bool) error {
if av.ElementType(ctx) != types.StringType {
return UnexpectedComparisonActualTypeError("compare_list_strings", av.ElementType(ctx), op, types.StringType, nil)
}
return compareStringsToStrings(conv.StringListToStrings(av), op, targets, caseInsensitive)
}
func compareSetToStrings(ctx context.Context, av types.Set, op CompareOp, targets []string, caseInsensitive bool) error {
if av.ElementType(ctx) != types.StringType {
return UnexpectedComparisonActualTypeError("compare_set_strings", av.ElementType(ctx), op, types.StringType, nil)
}
return compareStringsToStrings(conv.StringSetToStrings(av), op, targets, caseInsensitive)
}
func compareStrings(ctx context.Context, av attr.Value, op CompareOp, target interface{}, meta ...interface{}) error {
caseInsensitive := false
if len(meta) > 0 {
if b, ok := meta[0].(bool); ok {
caseInsensitive = b
}
}
tgtStrs, ok := target.([]string)
if !ok {
return UnexpectedComparisonTargetTypeError("compare_strings", target, op, make([]string, 0), nil)
}
switch av.(type) {
case types.String, *types.String:
return compareStringToStrings(conv.ValueToStringType(av), op, tgtStrs, caseInsensitive)
case types.List, *types.List:
return compareListToStrings(ctx, conv.ValueToListType(av), op, tgtStrs, caseInsensitive)
case types.Set, *types.Set:
return compareSetToStrings(ctx, conv.ValueToSetType(av), op, tgtStrs, caseInsensitive)
default:
return UnexpectedComparisonActualTypeError("compare_strings", av, op, types.StringType, nil)
}
}
func compareInt64ToInts(_ context.Context, av types.Int64, op CompareOp, targets []int, _ ...interface{}) error {
asInt := int(av.ValueInt64())
switch op {
case OneOf:
for _, v := range targets {
if asInt == v {
return nil
}
}
case NotOneOf:
for _, v := range targets {
if asInt == v {
return ComparisonFailedError(targets, op, asInt)
}
}
return nil
default:
return NoComparisonFuncRegisteredError(op, targets)
}
return ComparisonFailedError(av.ValueInt64(), op, targets)
}
func compareNumberToInts(_ context.Context, av types.Number, op CompareOp, targets []int, _ ...interface{}) error {
if av.IsNull() {
return ComparisonFailedError(nil, op, targets)
}
asInt64, _ := av.ValueBigFloat().Int64()
asInt := int(asInt64)
switch op {
case OneOf:
for _, v := range targets {
if asInt == v {
return nil
}
}
case NotOneOf:
for _, v := range targets {
if asInt == v {
return ComparisonFailedError(targets, op, asInt)
}
}
return nil
default:
return NoComparisonFuncRegisteredError(op, targets)
}
v, _ := av.ValueBigFloat().Float64()
return ComparisonFailedError(v, op, targets)
}
func compareIntsToInts(actuals []int, op CompareOp, targets []int) error {
actualsLen := len(actuals)
targetsLen := len(targets)
switch op {
case Equal:
if actualsLen == targetsLen {
for i, v := range actuals {
if targets[i] != v {
return ComparisonFailedError(actuals[i], op, targets[i])
}
}
return nil
}
case NotEqual:
if actualsLen != targetsLen {
return nil
}
for i, v := range actuals {
if targets[i] != v {
return nil
}
}
default:
return NoComparisonFuncRegisteredError(op, make([]int, 0))
}
return ComparisonFailedError(actuals, op, targets)
}
func compareListToInts(ctx context.Context, av types.List, op CompareOp, targets []int, _ ...interface{}) error {
elemType := av.ElementType(ctx)
switch elemType {
case types.Int64Type:
return compareIntsToInts(conv.Int64ListToInts(av), op, targets)
case types.NumberType:
return compareIntsToInts(conv.NumberListToInts(av), op, targets)
default:
return UnexpectedComparisonActualTypeError("compare_ints", elemType, op, types.Int64Type, nil)
}
}
func compareSetToInts(ctx context.Context, av types.Set, op CompareOp, targets []int, _ ...interface{}) error {
elemType := av.ElementType(ctx)
switch elemType {
case types.Int64Type:
return compareIntsToInts(conv.Int64SetToInts(av), op, targets)
case types.NumberType:
return compareIntsToInts(conv.NumberSetToInts(av), op, targets)
default:
return UnexpectedComparisonActualTypeError("compare_ints", elemType, op, types.Int64Type, nil)
}
}
func compareInts(ctx context.Context, av attr.Value, op CompareOp, target interface{}, _ ...interface{}) error {
tgtInts, ok := target.([]int)
if !ok {
return UnexpectedComparisonTargetTypeError("compare_ints", target, op, make([]int, 0), nil)
}
switch av.(type) {
case types.Int64, *types.Int64:
return compareInt64ToInts(ctx, conv.ValueToInt64Type(av), op, tgtInts)
case types.Number, *types.Number:
return compareNumberToInts(ctx, conv.ValueToNumberType(av), op, tgtInts)
case types.List, *types.List:
return compareListToInts(ctx, conv.ValueToListType(av), op, tgtInts)
case types.Set, *types.Set:
return compareSetToInts(ctx, conv.ValueToSetType(av), op, tgtInts)
default:
return UnexpectedComparisonActualTypeError("compare_ints", av, op, types.Int64{}, nil)
}
}
// DefaultComparisonFuncs returns the complete list of default comparison functions
func DefaultComparisonFuncs() map[string]ComparisonFunc {
return map[string]ComparisonFunc{
util.KeyFN(false): compareBool,
util.KeyFN(0.0): compareFloat64,
util.KeyFN(int64(0)): compareInt64,
util.KeyFN(0): compareInt,
util.KeyFN((*big.Float)(nil)): compareBigFloat,
util.KeyFN(""): compareString,
util.KeyFN(make([]string, 0)): compareStrings,
util.KeyFN(make([]int, 0)): compareInts,
}
}
// SetComparisonFunc sets a comparison function to use for comparing attribute values to values of the specified type
func SetComparisonFunc(targetType interface{}, fn ComparisonFunc) {
comparisonFuncsMu.Lock()
defer comparisonFuncsMu.Unlock()
comparisonFuncs[util.KeyFN(targetType)] = fn
}
// GetComparisonFunc attempts to return a previously registered comparison function for a specified op : type
// combination
func GetComparisonFunc(targetType interface{}) (ComparisonFunc, bool) {
comparisonFuncsMu.Lock()
defer comparisonFuncsMu.Unlock()
if fn, ok := comparisonFuncs[util.KeyFN(targetType)]; ok {
return fn, true
}
return nil, false
}
func init() {
comparisonFuncs = DefaultComparisonFuncs()
}
// CompareAttrValues attempts to execute a comparison between the provided attribute value and the targeted value.
//
// If there is no comparison function registered for the target type, an ErrNoComparisonFuncRegistered
// is returned.
//
// If a function is registered and the comparison fails, an ErrComparisonFailed error will be returned
func CompareAttrValues(ctx context.Context, av attr.Value, op CompareOp, target interface{}, meta ...interface{}) error {
if fn, ok := GetComparisonFunc(target); ok {
return fn(ctx, av, op, target, meta...)
} else {
return fmt.Errorf("%w for operation %q with target type %T", ErrNoComparisonFuncRegistered, op, target)
}
}
func addComparisonFailedDiagnostic(op CompareOp, target interface{}, srcReq interface{}, srcResp interface{}, err error) {
var (
req GenericRequest
resp *GenericResponse
terr error
)
if req, resp, terr = toGenericTypes(srcReq, srcResp); terr != nil {
panic(terr.Error())
}
switch op {
case Equal:
resp.Diagnostics.AddAttributeError(
req.Path,
"Attribute value does not match expected",
fmt.Sprintf("Attribute value must equal %s; err=%v", util.GetPrintableTypeWithValue(target), err),
)
case NotEqual:
resp.Diagnostics.AddAttributeError(
req.Path,
"Attribute value is not allowed",
fmt.Sprintf("Attribute value must not equal %s; err=%v", util.GetPrintableTypeWithValue(target), err),
)
case LessThan:
resp.Diagnostics.AddAttributeError(
req.Path,
"Value is above threshold",
fmt.Sprintf("Attribute value must be less than %s; err=%v", util.GetPrintableTypeWithValue(target), err),
)
case LessThanOrEqualTo:
resp.Diagnostics.AddAttributeError(
req.Path,
"Value is above threshold",
fmt.Sprintf("Attribute value must be less than or equal to %s; err=%v", util.GetPrintableTypeWithValue(target), err),
)
case GreaterThan:
resp.Diagnostics.AddAttributeError(
req.Path,
"Value is below threshold",
fmt.Sprintf("Attribute value must be greater than %s; err=%v", util.GetPrintableTypeWithValue(target), err),
)
case GreaterThanOrEqualTo:
resp.Diagnostics.AddAttributeError(
req.Path,
"Value is below threshold",
fmt.Sprintf("Attribute value must be greater than or equal to %s; err=%v", util.GetPrintableTypeWithValue(target), err),
)
case OneOf:
resp.Diagnostics.AddAttributeError(
req.Path,
"Value is not within allowed list",
fmt.Sprintf("Attribute value must be one of %s; err=%v", util.GetPrintableTypeWithValue(target), err),
)
case NotOneOf:
resp.Diagnostics.AddAttributeError(
req.Path,
"Value is not within allowed list",
fmt.Sprintf("Attribute value must not be one of %s; err=%v", util.GetPrintableTypeWithValue(target), err),
)
default:
resp.Diagnostics.AddAttributeError(
req.Path,
"Unknown comparison operation",
fmt.Sprintf("Specified unknown comparison operation: %s", op),
)
}
}