github.com/drone/go-convert@v0.0.0-20240307072510-6bd371c65e61/convert/travis/yaml/env.go (about) 1 // Copyright 2022 Harness, Inc. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package yaml 16 17 import ( 18 "errors" 19 "strings" 20 ) 21 22 type Env struct { 23 Global []map[string]string `yaml:"global,omitempty"` 24 Jobs []map[string]string `yaml:"jobs,omitempty"` 25 } 26 27 // UnmarshalYAML implements the unmarshal interface. 28 func (v *Env) UnmarshalYAML(unmarshal func(interface{}) error) error { 29 var out1 *Envmap 30 var out2 []*Envmap 31 var out3 = struct { 32 Global []*Envmap `yaml:"global"` 33 Jobs []*Envmap `yaml:"jobs"` 34 }{} 35 36 if err := unmarshal(&out1); err == nil { 37 v.Global = append(v.Global, out1.Items) 38 return nil 39 } 40 41 if err := unmarshal(&out2); err == nil { 42 for _, vv := range out2 { 43 v.Global = append(v.Global, vv.Items) 44 } 45 return nil 46 } 47 48 if err := unmarshal(&out3); err == nil { 49 for _, vv := range out3.Global { 50 v.Global = append(v.Global, vv.Items) 51 } 52 for _, vv := range out3.Jobs { 53 v.Jobs = append(v.Jobs, vv.Items) 54 } 55 return nil 56 } 57 58 return errors.New("failed to unmarshal env") 59 } 60 61 type Envmap struct { 62 Items map[string]string 63 } 64 65 // UnmarshalYAML implements the unmarshal interface. 66 func (v *Envmap) UnmarshalYAML(unmarshal func(interface{}) error) error { 67 var out1 string 68 var out2 []string 69 var out3 map[string]string 70 71 // fist we attempt to unmarshal a string in key=value format 72 if err := unmarshal(&out1); err == nil { 73 v.Items = map[string]string{} 74 parts := strings.SplitN(out1, "=", 2) 75 if len(parts) == 2 { 76 key := parts[0] 77 val := parts[1] 78 v.Items[key] = val 79 } 80 return nil 81 } 82 // then we attempt to unmarshal a string slice in key=value format 83 if err := unmarshal(&out2); err == nil { 84 v.Items = map[string]string{} 85 for _, vv := range out2 { 86 parts := strings.SplitN(vv, "=", 2) 87 if len(parts) == 2 { 88 key := parts[0] 89 val := parts[1] 90 v.Items[key] = val 91 } 92 } 93 return nil 94 } 95 // then we attempt to unmarshal a map 96 if err := unmarshal(&out3); err == nil { 97 v.Items = map[string]string{} 98 for key, val := range out3 { 99 v.Items[key] = val 100 } 101 return nil 102 } 103 104 return errors.New("failed to unmarshal env") 105 }