github.com/adevinta/lava@v0.7.2/internal/checktypes/checktypes.go (about) 1 // Copyright 2023 Adevinta 2 3 // Package checktypes provides utilities for working with checktypes 4 // and chektype catalogs. 5 package checktypes 6 7 import ( 8 "encoding/json" 9 "errors" 10 "fmt" 11 12 checkcatalog "github.com/adevinta/vulcan-check-catalog/pkg/model" 13 types "github.com/adevinta/vulcan-types" 14 15 "github.com/adevinta/lava/internal/urlutil" 16 ) 17 18 // ErrMalformedCatalog is returned by [NewCatalog] when the format of 19 // the retrieved catalog is not valid. 20 var ErrMalformedCatalog = errors.New("malformed catalog") 21 22 // Accepts reports whether the specified checktype accepts an asset 23 // type. 24 func Accepts(ct checkcatalog.Checktype, at types.AssetType) bool { 25 for _, accepted := range ct.Assets { 26 if accepted == string(at) { 27 return true 28 } 29 } 30 return false 31 } 32 33 // Catalog represents a collection of Vulcan checktypes. 34 type Catalog map[string]checkcatalog.Checktype 35 36 // NewCatalog retrieves the specified checktype catalogs and 37 // consolidates them in a single catalog with all the checktypes 38 // indexed by name. If a checktype is duplicated it is overridden with 39 // the last one. 40 func NewCatalog(urls []string) (Catalog, error) { 41 catalog := make(Catalog) 42 for _, url := range urls { 43 data, err := urlutil.Get(url) 44 if err != nil { 45 return nil, err 46 } 47 48 var decData struct { 49 Checktypes []checkcatalog.Checktype `json:"checktypes"` 50 } 51 err = json.Unmarshal(data, &decData) 52 if err != nil { 53 return nil, fmt.Errorf("%w: %w", ErrMalformedCatalog, err) 54 } 55 56 for _, checktype := range decData.Checktypes { 57 catalog[checktype.Name] = checktype 58 } 59 } 60 return catalog, nil 61 }