github.com/drone/go-convert@v0.0.0-20240307072510-6bd371c65e61/convert/gitlab/yaml/needs.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 Needs struct { 20 Items []*Need 21 } 22 23 // UnmarshalYAML implements the unmarshal interface. 24 func (v *Needs) UnmarshalYAML(unmarshal func(interface{}) error) error { 25 var out1 *Need 26 var out2 []*Need 27 if err := unmarshal(&out1); err == nil { 28 v.Items = append(v.Items, out1) 29 return nil 30 } 31 if err := unmarshal(&out2); err == nil { 32 v.Items = append(v.Items, out2...) 33 return nil 34 } 35 return errors.New("failed to unmarshal needs list") 36 } 37 38 func (v *Needs) MarshalYAML() (interface{}, error) { 39 if v.Items == nil || len(v.Items) == 0 { 40 return []*Need{}, nil 41 } 42 return v.Items, nil 43 } 44 45 type Need struct { 46 Job string `yaml:"job,omitempty"` 47 Ref string `yaml:"ref,omitempty"` 48 Project string `yaml:"project,omitempty"` 49 Pipeline string `yaml:"pipeline,omitempty"` 50 Artifacts bool `yaml:"artifacts,omitempty"` 51 Optional bool `yaml:"optional,omitempty"` 52 } 53 54 // UnmarshalYAML implements the unmarshal interface. 55 func (v *Need) UnmarshalYAML(unmarshal func(interface{}) error) error { 56 var out1 string 57 var out2 = struct { 58 Job string `yaml:"job,omitempty"` 59 Ref string `yaml:"ref,omitempty"` 60 Project string `yaml:"project,omitempty"` 61 Pipeline string `yaml:"pipeline,omitempty"` 62 Artifacts bool `yaml:"artifacts,omitempty"` 63 Optional bool `yaml:"optional,omitempty"` 64 }{} 65 66 if err := unmarshal(&out1); err == nil { 67 v.Job = out1 68 return nil 69 } 70 71 if err := unmarshal(&out2); err == nil { 72 v.Job = out2.Job 73 v.Ref = out2.Ref 74 v.Project = out2.Project 75 v.Pipeline = out2.Pipeline 76 v.Artifacts = out2.Artifacts 77 v.Optional = out2.Optional 78 return nil 79 } 80 81 return errors.New("failed to unmarshal needs") 82 }