get.porter.sh/porter@v1.3.0/pkg/cnab/dependencies_v1.go (about) 1 package cnab 2 3 import ( 4 "encoding/json" 5 "errors" 6 "fmt" 7 8 depsv1ext "get.porter.sh/porter/pkg/cnab/extensions/dependencies/v1" 9 ) 10 11 const ( 12 // DependenciesV1ExtensionShortHand is the short suffix of the DependenciesV1ExtensionKey 13 DependenciesV1ExtensionShortHand = "dependencies" 14 15 // DependenciesV1ExtensionKey represents the full key for the DependenciesV1Extension. 16 DependenciesV1ExtensionKey = OfficialExtensionsPrefix + DependenciesV1ExtensionShortHand 17 18 // DependenciesV1Schema represents the schema for the Dependencies Extension 19 DependenciesV1Schema = "https://cnab.io/v1/dependencies.schema.json" 20 ) 21 22 // DependenciesV1Extension represents the required extension to enable dependencies 23 var DependenciesV1Extension = RequiredExtension{ 24 Shorthand: DependenciesV1ExtensionShortHand, 25 Key: DependenciesV1ExtensionKey, 26 Schema: DependenciesV1Schema, 27 Reader: func(b ExtendedBundle) (interface{}, error) { 28 return b.DependencyV1Reader() 29 }, 30 } 31 32 // ReadDependenciesV1 is a convenience method for returning a bonafide 33 // Dependencies reference after reading from the applicable section from 34 // the provided bundle 35 func (b ExtendedBundle) ReadDependenciesV1() (depsv1ext.Dependencies, error) { 36 raw, err := b.DependencyV1Reader() 37 if err != nil { 38 return depsv1ext.Dependencies{}, err 39 } 40 41 deps, ok := raw.(depsv1ext.Dependencies) 42 if !ok { 43 return depsv1ext.Dependencies{}, errors.New("unable to read dependencies extension data") 44 } 45 46 // Return the dependencies 47 return deps, nil 48 } 49 50 // DependencyV1Reader is a Reader for the DependenciesV1Extension, which reads 51 // from the applicable section in the provided bundle and returns the raw 52 // data in the form of an interface 53 func (b ExtendedBundle) DependencyV1Reader() (interface{}, error) { 54 data, ok := b.Custom[DependenciesV1ExtensionKey] 55 if !ok { 56 return nil, fmt.Errorf("attempted to read dependencies from bundle but none are defined") 57 } 58 59 dataB, err := json.Marshal(data) 60 if err != nil { 61 return nil, fmt.Errorf("could not marshal the untyped dependencies extension data %q: %w", string(dataB), err) 62 } 63 64 deps := depsv1ext.Dependencies{} 65 err = json.Unmarshal(dataB, &deps) 66 if err != nil { 67 return nil, fmt.Errorf("could not unmarshal the dependencies extension %q: %w", string(dataB), err) 68 } 69 70 return deps, nil 71 } 72 73 // SupportsDependenciesV1 checks if the bundle supports dependencies 74 func (b ExtendedBundle) SupportsDependenciesV1() bool { 75 return b.SupportsExtension(DependenciesV1ExtensionKey) 76 } 77 78 // HasDependenciesV1 returns whether the bundle has parameter sources defined. 79 func (b ExtendedBundle) HasDependenciesV1() bool { 80 _, ok := b.Custom[DependenciesV1ExtensionKey] 81 return ok 82 }