github.com/drone/go-convert@v0.0.0-20240307072510-6bd371c65e61/convert/gitlab/yaml/inherit.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 Inherit struct { 20 Default *InheritKeys `yaml:"default,omitempty"` 21 Variables *InheritKeys `yaml:"variables,omitempty"` 22 } 23 24 type InheritKeys struct { 25 All bool `yaml:"all,omitempty"` 26 Keys []string `yaml:"keys,omitempty"` 27 } 28 29 // UnmarshalYAML implements the unmarshal interface for InheritKeys. 30 func (v *InheritKeys) UnmarshalYAML(unmarshal func(interface{}) error) error { 31 var out1 bool 32 var out2 []string 33 34 if err := unmarshal(&out1); err == nil { 35 v.All = !out1 36 return nil 37 } 38 39 if err := unmarshal(&out2); err == nil { 40 v.Keys = out2 41 return nil 42 } 43 44 return errors.New("failed to unmarshal inherit keys") 45 } 46 47 // UnmarshalYAML implements the unmarshal interface for Inherit. 48 func (v *Inherit) UnmarshalYAML(unmarshal func(interface{}) error) error { 49 var out1 bool 50 var out2 struct { 51 Default *InheritKeys `yaml:"default,omitempty"` 52 Variables *InheritKeys `yaml:"variables,omitempty"` 53 } 54 55 if err := unmarshal(&out1); err == nil { 56 v.Default = &InheritKeys{All: !out1} 57 v.Variables = &InheritKeys{All: !out1} 58 return nil 59 } 60 61 if err := unmarshal(&out2); err == nil { 62 v.Default = out2.Default 63 v.Variables = out2.Variables 64 return nil 65 } 66 67 return errors.New("failed to unmarshal inherit") 68 } 69 70 func (v *Inherit) MarshalYAML() (interface{}, error) { 71 m := make(map[string]interface{}) 72 73 if v.Default != nil { 74 if v.Default.All { 75 m["default"] = false 76 } else { 77 m["default"] = v.Default.Keys 78 } 79 } 80 81 if v.Variables != nil { 82 if v.Variables.All { 83 m["variables"] = false 84 } else { 85 m["variables"] = v.Variables.Keys 86 } 87 } 88 89 return m, nil 90 }