github.com/opendevstack/tailor@v1.3.5-0.20220119161809-cab064e60a67/pkg/openshift/list.go (about) 1 package openshift 2 3 import ( 4 "errors" 5 6 "github.com/ghodss/yaml" 7 "github.com/opendevstack/tailor/pkg/cli" 8 "github.com/opendevstack/tailor/pkg/utils" 9 "github.com/xeipuuv/gojsonpointer" 10 ) 11 12 // ResourceList is a collection of resources that conform to a filter. 13 type ResourceList struct { 14 Filter *ResourceFilter 15 Items []*ResourceItem 16 } 17 18 // NewTemplateBasedResourceList assembles a ResourceList from an input that is 19 // treated as coming from a local template (desired state). 20 func NewTemplateBasedResourceList(filter *ResourceFilter, inputs ...[]byte) (*ResourceList, error) { 21 list := &ResourceList{Filter: filter} 22 err := list.appendItems("template", "/items", inputs...) 23 return list, err 24 } 25 26 // NewPlatformBasedResourceList assembles a ResourceList from an input that is 27 // treated as coming from an OpenShift cluster (current state). 28 func NewPlatformBasedResourceList(filter *ResourceFilter, inputs ...[]byte) (*ResourceList, error) { 29 list := &ResourceList{Filter: filter} 30 err := list.appendItems("platform", "/items", inputs...) 31 return list, err 32 } 33 34 // Length returns the number of items in the resource list 35 func (l *ResourceList) Length() int { 36 return len(l.Items) 37 } 38 39 func (l *ResourceList) getItem(kind string, name string) (*ResourceItem, error) { 40 for _, item := range l.Items { 41 if item.Kind == kind && item.Name == name { 42 return item, nil 43 } 44 } 45 return nil, errors.New("No such item") 46 } 47 48 func (l *ResourceList) appendItems(source, itemsField string, inputs ...[]byte) error { 49 for _, input := range inputs { 50 if len(input) == 0 { 51 cli.DebugMsg("Input config empty") 52 continue 53 } 54 55 var f interface{} 56 err := yaml.Unmarshal(input, &f) 57 if err != nil { 58 err = utils.DisplaySyntaxError(input, err) 59 return err 60 } 61 m := f.(map[string]interface{}) 62 63 p, _ := gojsonpointer.NewJsonPointer(itemsField) 64 items, _, err := p.Get(m) 65 if err != nil { 66 return err 67 } 68 if items == nil { 69 return errors.New("Cannot find items to append") 70 } 71 for _, v := range items.([]interface{}) { 72 item, err := NewResourceItem(v.(map[string]interface{}), source) 73 if err != nil { 74 return err 75 } 76 if item.Comparable && l.Filter.SatisfiedBy(item) { 77 l.Items = append(l.Items, item) 78 } 79 } 80 } 81 82 return nil 83 }