github.com/terramate-io/tf@v0.0.0-20230830114523-fce866b4dfcd/configs/configschema/path.go (about)

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