github.com/opentofu/opentofu@v1.7.1/internal/addrs/provider_function.go (about)

     1  package addrs
     2  
     3  import (
     4  	"fmt"
     5  	"strings"
     6  )
     7  
     8  // ProviderFunction is the address of a provider defined function.
     9  type ProviderFunction struct {
    10  	referenceable
    11  	ProviderName  string
    12  	ProviderAlias string
    13  	Function      string
    14  }
    15  
    16  func (v ProviderFunction) String() string {
    17  	if v.ProviderAlias != "" {
    18  		return fmt.Sprintf("provider::%s::%s::%s", v.ProviderName, v.ProviderAlias, v.Function)
    19  	}
    20  	return fmt.Sprintf("provider::%s::%s", v.ProviderName, v.Function)
    21  }
    22  
    23  func (v ProviderFunction) UniqueKey() UniqueKey {
    24  	return v // A ProviderFunction is its own UniqueKey
    25  }
    26  
    27  func (v ProviderFunction) uniqueKeySigil() {}
    28  
    29  type Function struct {
    30  	Namespaces []string
    31  	Name       string
    32  }
    33  
    34  const (
    35  	FunctionNamespaceProvider = "provider"
    36  	FunctionNamespaceCore     = "core"
    37  )
    38  
    39  var FunctionNamespaces = []string{
    40  	FunctionNamespaceProvider,
    41  	FunctionNamespaceCore,
    42  }
    43  
    44  func ParseFunction(input string) Function {
    45  	parts := strings.Split(input, "::")
    46  	return Function{
    47  		Name:       parts[len(parts)-1],
    48  		Namespaces: parts[:len(parts)-1],
    49  	}
    50  }
    51  
    52  func (f Function) String() string {
    53  	return strings.Join(append(f.Namespaces, f.Name), "::")
    54  }
    55  
    56  func (f Function) IsNamespace(namespace string) bool {
    57  	return len(f.Namespaces) > 0 && f.Namespaces[0] == namespace
    58  }
    59  
    60  func (f Function) AsProviderFunction() (pf ProviderFunction, err error) {
    61  	if !f.IsNamespace(FunctionNamespaceProvider) {
    62  		// Should always be checked ahead of time!
    63  		panic("BUG: non-provider function " + f.String())
    64  	}
    65  
    66  	if len(f.Namespaces) == 2 {
    67  		// provider::<name>::<function>
    68  		pf.ProviderName = f.Namespaces[1]
    69  	} else if len(f.Namespaces) == 3 {
    70  		// provider::<name>::<alias>::<function>
    71  		pf.ProviderName = f.Namespaces[1]
    72  		pf.ProviderAlias = f.Namespaces[2]
    73  	} else {
    74  		return pf, fmt.Errorf("invalid provider function %q: expected provider::<name>::<function> or provider::<name>::<alias>::<function>", f)
    75  	}
    76  	pf.Function = f.Name
    77  	return pf, nil
    78  }