github.com/drone/go-convert@v0.0.0-20240307072510-6bd371c65e61/convert/gitlab/yaml/variable.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 ) 20 21 type Variable struct { 22 Value string `yaml:"value,omitempty"` 23 Desc string `yaml:"description,omitempty"` 24 Options Stringorslice `yaml:"options,omitempty"` 25 Expand *bool `yaml:"expand,omitempty"` 26 } 27 28 // UnmarshalYAML implements the unmarshal interface. 29 func (v *Variable) UnmarshalYAML(unmarshal func(interface{}) error) error { 30 var out1 string 31 var out2 = struct { 32 Value string `yaml:"value,omitempty"` 33 Desc string `yaml:"description,omitempty"` 34 Options Stringorslice `yaml:"options,omitempty"` 35 Expand interface{} `yaml:"expand"` 36 }{} 37 38 if err := unmarshal(&out1); err == nil { 39 expand := true 40 v.Value = out1 41 v.Expand = &expand 42 return nil 43 } 44 45 if err := unmarshal(&out2); err == nil { 46 v.Value = out2.Value 47 v.Desc = out2.Desc 48 v.Options = out2.Options 49 50 switch out2.Expand.(type) { 51 case bool: 52 expand := out2.Expand.(bool) 53 v.Expand = &expand 54 default: 55 expand := true 56 v.Expand = &expand 57 } 58 return nil 59 } 60 61 return errors.New("failed to unmarshal variable") 62 } 63 64 func (v *Variable) MarshalYAML() (interface{}, error) { 65 // If there's no description and expand is true or not set, just output the value as a string 66 if v.Desc == "" && (v.Expand == nil || *v.Expand) { 67 return v.Value, nil 68 } 69 70 return struct { 71 Value string `yaml:"value,omitempty"` 72 Desc string `yaml:"description,omitempty"` 73 Options Stringorslice `yaml:"options,omitempty"` 74 Expand *bool `yaml:"expand,omitempty"` 75 }{ 76 Value: v.Value, 77 Desc: v.Desc, 78 Options: v.Options, 79 Expand: v.Expand, 80 }, nil 81 }