github.com/eliastor/durgaform@v0.0.0-20220816172711-d0ab2d17673e/internal/command/jsonprovider/provider.go (about)

     1  package jsonprovider
     2  
     3  import (
     4  	"encoding/json"
     5  
     6  	"github.com/eliastor/durgaform/internal/durgaform"
     7  )
     8  
     9  // FormatVersion represents the version of the json format and will be
    10  // incremented for any change to this format that requires changes to a
    11  // consuming parser.
    12  const FormatVersion = "1.0"
    13  
    14  // providers is the top-level object returned when exporting provider schemas
    15  type providers struct {
    16  	FormatVersion string               `json:"format_version"`
    17  	Schemas       map[string]*Provider `json:"provider_schemas,omitempty"`
    18  }
    19  
    20  type Provider struct {
    21  	Provider          *schema            `json:"provider,omitempty"`
    22  	ResourceSchemas   map[string]*schema `json:"resource_schemas,omitempty"`
    23  	DataSourceSchemas map[string]*schema `json:"data_source_schemas,omitempty"`
    24  }
    25  
    26  func newProviders() *providers {
    27  	schemas := make(map[string]*Provider)
    28  	return &providers{
    29  		FormatVersion: FormatVersion,
    30  		Schemas:       schemas,
    31  	}
    32  }
    33  
    34  func Marshal(s *durgaform.Schemas) ([]byte, error) {
    35  	providers := newProviders()
    36  
    37  	for k, v := range s.Providers {
    38  		providers.Schemas[k.String()] = marshalProvider(v)
    39  	}
    40  
    41  	ret, err := json.Marshal(providers)
    42  	return ret, err
    43  }
    44  
    45  func marshalProvider(tps *durgaform.ProviderSchema) *Provider {
    46  	if tps == nil {
    47  		return &Provider{}
    48  	}
    49  
    50  	var ps *schema
    51  	var rs, ds map[string]*schema
    52  
    53  	if tps.Provider != nil {
    54  		ps = marshalSchema(tps.Provider)
    55  	}
    56  
    57  	if tps.ResourceTypes != nil {
    58  		rs = marshalSchemas(tps.ResourceTypes, tps.ResourceTypeSchemaVersions)
    59  	}
    60  
    61  	if tps.DataSources != nil {
    62  		ds = marshalSchemas(tps.DataSources, tps.ResourceTypeSchemaVersions)
    63  	}
    64  
    65  	return &Provider{
    66  		Provider:          ps,
    67  		ResourceSchemas:   rs,
    68  		DataSourceSchemas: ds,
    69  	}
    70  }