kubeform.dev/terraform-backend-sdk@v0.0.0-20220310143633-45f07fe731c5/configs/configschema/path.go (about)

     1  package configschema
     2  
     3  import (
     4  	"github.com/zclconf/go-cty/cty"
     5  )
     6  
     7  // AttributeByPath looks up the Attribute schema which corresponds to the given
     8  // cty.Path. A nil value is returned if the given path does not correspond to a
     9  // specific attribute.
    10  func (b *Block) AttributeByPath(path cty.Path) *Attribute {
    11  	block := b
    12  	for i, step := range path {
    13  		switch step := step.(type) {
    14  		case cty.GetAttrStep:
    15  			if attr := block.Attributes[step.Name]; attr != nil {
    16  				// If the Attribute is defined with a NestedType and there's
    17  				// more to the path, descend into the NestedType
    18  				if attr.NestedType != nil && i < len(path)-1 {
    19  					return attr.NestedType.AttributeByPath(path[i+1:])
    20  				} else if i < len(path)-1 { // There's more to the path, but not more to this Attribute.
    21  					return nil
    22  				}
    23  				return attr
    24  			}
    25  
    26  			if nestedBlock := block.BlockTypes[step.Name]; nestedBlock != nil {
    27  				block = &nestedBlock.Block
    28  				continue
    29  			}
    30  
    31  			return nil
    32  		}
    33  	}
    34  	return nil
    35  }
    36  
    37  // AttributeByPath recurses through a NestedType to look up the Attribute scheme
    38  // which corresponds to the given cty.Path. A nil value is returned if the given
    39  // path does not correspond to a specific attribute.
    40  func (o *Object) AttributeByPath(path cty.Path) *Attribute {
    41  	for i, step := range path {
    42  		switch step := step.(type) {
    43  		case cty.GetAttrStep:
    44  			if attr := o.Attributes[step.Name]; attr != nil {
    45  				if attr.NestedType != nil && i < len(path)-1 {
    46  					return attr.NestedType.AttributeByPath(path[i+1:])
    47  				} else if i < len(path)-1 { // There's more to the path, but not more to this Attribute.
    48  					return nil
    49  				}
    50  				return attr
    51  			}
    52  		}
    53  	}
    54  	return nil
    55  }