github.com/kubeshop/testkube@v1.17.23/pkg/tcl/expressionstcl/conditional.go (about) 1 // Copyright 2024 Testkube. 2 // 3 // Licensed as a Testkube Pro file under the Testkube Community 4 // License (the "License"); you may not use this file except in compliance with 5 // the License. You may obtain a copy of the License at 6 // 7 // https://github.com/kubeshop/testkube/blob/main/licenses/TCL.txt 8 9 package expressionstcl 10 11 import ( 12 "fmt" 13 "maps" 14 ) 15 16 type conditional struct { 17 condition Expression 18 truthy Expression 19 falsy Expression 20 } 21 22 func newConditional(condition, truthy, falsy Expression) Expression { 23 if condition == nil { 24 condition = None 25 } 26 if truthy == nil { 27 truthy = None 28 } 29 if falsy == nil { 30 falsy = None 31 } 32 return &conditional{condition: condition, truthy: truthy, falsy: falsy} 33 } 34 35 func (s *conditional) Type() Type { 36 r1 := s.truthy.Type() 37 r2 := s.falsy.Type() 38 if r1 == r2 { 39 return r1 40 } 41 return TypeUnknown 42 } 43 44 func (s *conditional) String() string { 45 return fmt.Sprintf("%s ? %s : %s", s.condition.String(), s.truthy.String(), s.falsy.String()) 46 } 47 48 func (s *conditional) SafeString() string { 49 return "(" + s.String() + ")" 50 } 51 52 func (s *conditional) Template() string { 53 return "{{" + s.String() + "}}" 54 } 55 56 func (s *conditional) SafeResolve(m ...Machine) (v Expression, changed bool, err error) { 57 var ch bool 58 s.condition, ch, err = s.condition.SafeResolve(m...) 59 changed = changed || ch 60 if err != nil { 61 return nil, changed, err 62 } 63 if s.condition.Static() != nil { 64 var b bool 65 b, err = s.condition.Static().BoolValue() 66 if err != nil { 67 return nil, true, err 68 } 69 if b { 70 return s.truthy, true, err 71 } 72 return s.falsy, true, err 73 } 74 s.truthy, ch, err = s.truthy.SafeResolve(m...) 75 changed = changed || ch 76 if err != nil { 77 return nil, changed, err 78 } 79 s.falsy, ch, err = s.falsy.SafeResolve(m...) 80 changed = changed || ch 81 if err != nil { 82 return nil, changed, err 83 } 84 return s, changed, nil 85 } 86 87 func (s *conditional) Resolve(m ...Machine) (v Expression, err error) { 88 return deepResolve(s, m...) 89 } 90 91 func (s *conditional) Static() StaticValue { 92 return nil 93 } 94 95 func (s *conditional) Accessors() map[string]struct{} { 96 result := make(map[string]struct{}) 97 maps.Copy(result, s.condition.Accessors()) 98 maps.Copy(result, s.truthy.Accessors()) 99 maps.Copy(result, s.falsy.Accessors()) 100 return result 101 } 102 103 func (s *conditional) Functions() map[string]struct{} { 104 result := make(map[string]struct{}) 105 maps.Copy(result, s.condition.Functions()) 106 maps.Copy(result, s.truthy.Functions()) 107 maps.Copy(result, s.falsy.Functions()) 108 return result 109 }