github.com/terramate-io/tf@v0.0.0-20230830114523-fce866b4dfcd/legacy/terraform/context_components.go (about)

     1  // Copyright (c) HashiCorp, Inc.
     2  // SPDX-License-Identifier: MPL-2.0
     3  
     4  package terraform
     5  
     6  import (
     7  	"fmt"
     8  
     9  	"github.com/terramate-io/tf/addrs"
    10  	"github.com/terramate-io/tf/providers"
    11  	"github.com/terramate-io/tf/provisioners"
    12  )
    13  
    14  // contextComponentFactory is the interface that Context uses
    15  // to initialize various components such as providers and provisioners.
    16  // This factory gets more information than the raw maps using to initialize
    17  // a Context. This information is used for debugging.
    18  type contextComponentFactory interface {
    19  	// ResourceProvider creates a new ResourceProvider with the given type.
    20  	ResourceProvider(typ addrs.Provider) (providers.Interface, error)
    21  	ResourceProviders() []string
    22  
    23  	// ResourceProvisioner creates a new ResourceProvisioner with the given
    24  	// type.
    25  	ResourceProvisioner(typ string) (provisioners.Interface, error)
    26  	ResourceProvisioners() []string
    27  }
    28  
    29  // basicComponentFactory just calls a factory from a map directly.
    30  type basicComponentFactory struct {
    31  	providers    map[addrs.Provider]providers.Factory
    32  	provisioners map[string]ProvisionerFactory
    33  }
    34  
    35  func (c *basicComponentFactory) ResourceProviders() []string {
    36  	var result []string
    37  	for k := range c.providers {
    38  		result = append(result, k.String())
    39  	}
    40  	return result
    41  }
    42  
    43  func (c *basicComponentFactory) ResourceProvisioners() []string {
    44  	var result []string
    45  	for k := range c.provisioners {
    46  		result = append(result, k)
    47  	}
    48  
    49  	return result
    50  }
    51  
    52  func (c *basicComponentFactory) ResourceProvider(typ addrs.Provider) (providers.Interface, error) {
    53  	f, ok := c.providers[typ]
    54  	if !ok {
    55  		return nil, fmt.Errorf("unknown provider %q", typ.String())
    56  	}
    57  
    58  	return f()
    59  }
    60  
    61  func (c *basicComponentFactory) ResourceProvisioner(typ string) (provisioners.Interface, error) {
    62  	f, ok := c.provisioners[typ]
    63  	if !ok {
    64  		return nil, fmt.Errorf("unknown provisioner %q", typ)
    65  	}
    66  
    67  	return f()
    68  }