github.com/drone/go-convert@v0.0.0-20240307072510-6bd371c65e61/convert/circle/yaml/workflows.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 ( 22 Workflows struct { 23 Version string `yaml:"version,omitempty"` 24 Items map[string]*Workflow `yaml:",inline"` 25 } 26 27 Workflow struct { 28 Jobs []*WorkflowJob `yaml:"jobs,omitempty"` 29 Triggers []*Trigger `yaml:"triggers,omitempty"` 30 Unless *Logical `yaml:"when,omitempty"` 31 When *Logical `yaml:"unless,omitempty"` 32 } 33 34 WorkflowJob struct { 35 Name string 36 Context []string 37 Filters *Filters 38 Matrix *Matrix 39 Type string 40 Requires []string 41 Params map[string]interface{} // custom params 42 } 43 44 workflowJob struct { 45 Context Stringorslice `yaml:"context,omitempty"` 46 Filters *Filters `yaml:"filters,omitempty"` 47 Matrix *Matrix `yaml:"matrix,omitempty"` 48 Type string `yaml:"type,omitempty"` // approval 49 Requires []string `yaml:"requires,omitempty"` 50 Params map[string]interface{} `yaml:",inline"` // custom params 51 } 52 ) 53 54 // UnmarshalYAML implements the unmarshal interface. 55 func (v *WorkflowJob) UnmarshalYAML(unmarshal func(interface{}) error) error { 56 var out1 string 57 var out2 map[string]*workflowJob 58 59 if err := unmarshal(&out1); err == nil { 60 v.Name = out1 61 return nil 62 } 63 64 if err := unmarshal(&out2); err == nil { 65 if len(out2) == 0 { 66 return errors.New("failed to unmarshal job") 67 } 68 for key, val := range out2 { 69 v.Name = key 70 v.Context = val.Context 71 v.Filters = val.Filters 72 v.Matrix = val.Matrix 73 v.Type = val.Type 74 v.Requires = val.Requires 75 v.Params = val.Params 76 } 77 return nil 78 } 79 80 return errors.New("failed to unmarshal job") 81 } 82 83 // MarshalYAML implements the marshal interface. 84 func (v *WorkflowJob) MarshalYAML() (interface{}, error) { 85 // if the structure is empty, output the string only 86 if len(v.Context) == 0 && len(v.Params) == 0 && v.Filters == nil && v.Matrix == nil && v.Type == "" && len(v.Requires) == 0 { 87 return v.Name, nil 88 } 89 return map[string]*workflowJob{ 90 v.Name: { 91 Context: v.Context, 92 Filters: v.Filters, 93 Matrix: v.Matrix, 94 Type: v.Type, 95 Requires: v.Requires, 96 Params: v.Params, 97 }, 98 }, nil 99 }