github.com/drone/go-convert@v0.0.0-20240307072510-6bd371c65e61/convert/gitlab/yaml/parallel.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 "errors" 18 19 type Parallel struct { 20 Count int `yaml:"-,omitempty"` 21 Matrix []map[string][]string `yaml:"matrix,omitempty"` 22 } 23 24 // UnmarshalYAML implements the unmarshal interface. 25 func (v *Parallel) UnmarshalYAML(unmarshal func(interface{}) error) error { 26 var out1 int 27 var out2 map[string][]map[string]interface{} 28 29 if err := unmarshal(&out1); err == nil { 30 v.Count = out1 31 return nil 32 } 33 34 if err := unmarshal(&out2); err == nil { 35 matrix := make([]map[string][]string, len(out2["matrix"])) 36 for i, item := range out2["matrix"] { 37 matrixItem := make(map[string][]string) 38 for key, value := range item { 39 switch v := value.(type) { 40 case string: 41 matrixItem[key] = []string{v} 42 case []interface{}: 43 strings := make([]string, len(v)) 44 for i, s := range v { 45 strings[i] = s.(string) 46 } 47 matrixItem[key] = strings 48 } 49 } 50 matrix[i] = matrixItem 51 } 52 v.Matrix = matrix 53 return nil 54 } 55 56 return errors.New("failed to unmarshal parallel") 57 } 58 59 func (v *Parallel) MarshalYAML() (interface{}, error) { 60 if v.Count > 0 { 61 return v.Count, nil 62 } 63 64 // Convert the complex structure of v.Matrix back into a simpler form 65 matrix := make([]map[string]interface{}, len(v.Matrix)) 66 for i, item := range v.Matrix { 67 matrixItem := make(map[string]interface{}) 68 for key, value := range item { 69 if len(value) == 1 { 70 matrixItem[key] = value[0] // Single string 71 } else { 72 matrixItem[key] = value // Slice of strings 73 } 74 } 75 matrix[i] = matrixItem 76 } 77 78 return map[string][]map[string]interface{}{"matrix": matrix}, nil 79 }