gitlab.com/jfprevost/gitlab-runner-notlscheck@v11.11.4+incompatible/helpers/gitlab_ci_yaml_parser/data_bag.go (about) 1 package gitlab_ci_yaml_parser 2 3 import ( 4 "encoding/json" 5 "fmt" 6 "strings" 7 8 "gitlab.com/gitlab-org/gitlab-runner/helpers" 9 ) 10 11 type DataBag map[string]interface{} 12 13 func (m *DataBag) Get(keys ...string) (interface{}, bool) { 14 return helpers.GetMapKey(*m, keys...) 15 } 16 17 func (m *DataBag) GetSlice(keys ...string) ([]interface{}, bool) { 18 slice, ok := helpers.GetMapKey(*m, keys...) 19 if slice != nil { 20 return slice.([]interface{}), ok 21 } 22 return nil, false 23 } 24 25 func (m *DataBag) GetStringSlice(keys ...string) (slice []string, ok bool) { 26 rawSlice, ok := m.GetSlice(keys...) 27 if !ok { 28 return 29 } 30 31 for _, rawElement := range rawSlice { 32 if element, ok := rawElement.(string); ok { 33 slice = append(slice, element) 34 } 35 } 36 return 37 } 38 39 func (m *DataBag) GetSubOptions(keys ...string) (result DataBag, ok bool) { 40 value, ok := helpers.GetMapKey(*m, keys...) 41 if ok { 42 result, ok = value.(map[string]interface{}) 43 } 44 return 45 } 46 47 func (m *DataBag) GetString(keys ...string) (result string, ok bool) { 48 value, ok := helpers.GetMapKey(*m, keys...) 49 if ok { 50 result, ok = value.(string) 51 } 52 return 53 } 54 55 func (m *DataBag) Decode(result interface{}, keys ...string) error { 56 value, ok := m.Get(keys...) 57 if !ok { 58 return fmt.Errorf("key not found %v", strings.Join(keys, ".")) 59 } 60 61 data, err := json.Marshal(value) 62 if err != nil { 63 return err 64 } 65 66 return json.Unmarshal(data, result) 67 } 68 69 func convertMapToStringMap(in interface{}) (out interface{}, err error) { 70 mapString, ok := in.(map[string]interface{}) 71 if ok { 72 for k, v := range mapString { 73 mapString[k], err = convertMapToStringMap(v) 74 if err != nil { 75 return 76 } 77 } 78 return mapString, nil 79 } 80 81 mapInterface, ok := in.(map[interface{}]interface{}) 82 if ok { 83 mapString := make(map[string]interface{}) 84 for k, v := range mapInterface { 85 key, ok := k.(string) 86 if !ok { 87 return nil, fmt.Errorf("failed to convert %v to string", k) 88 } 89 90 mapString[key], err = convertMapToStringMap(v) 91 if err != nil { 92 return 93 } 94 } 95 return mapString, nil 96 } 97 98 return in, nil 99 } 100 101 func (m *DataBag) Sanitize() (err error) { 102 n := make(DataBag) 103 for k, v := range *m { 104 n[k], err = convertMapToStringMap(v) 105 if err != nil { 106 return 107 } 108 } 109 *m = n 110 return 111 } 112 113 func getOptionsMap(optionKey string, primary, secondary DataBag) (value DataBag) { 114 value, ok := primary.GetSubOptions(optionKey) 115 if !ok { 116 value, _ = secondary.GetSubOptions(optionKey) 117 } 118 119 return 120 } 121 122 func getOptions(optionKey string, primary, secondary DataBag) (value []interface{}, ok bool) { 123 value, ok = primary.GetSlice(optionKey) 124 if !ok { 125 value, ok = secondary.GetSlice(optionKey) 126 } 127 128 return 129 }