github.com/eliastor/durgaform@v0.0.0-20220816172711-d0ab2d17673e/internal/lang/blocktoattr/variables.go (about)

     1  package blocktoattr
     2  
     3  import (
     4  	"github.com/hashicorp/hcl/v2"
     5  	"github.com/hashicorp/hcl/v2/ext/dynblock"
     6  	"github.com/hashicorp/hcl/v2/hcldec"
     7  	"github.com/eliastor/durgaform/internal/configs/configschema"
     8  )
     9  
    10  // ExpandedVariables finds all of the global variables referenced in the
    11  // given body with the given schema while taking into account the possibilities
    12  // both of "dynamic" blocks being expanded and the possibility of certain
    13  // attributes being written instead as nested blocks as allowed by the
    14  // FixUpBlockAttrs function.
    15  //
    16  // This function exists to allow variables to be analyzed prior to dynamic
    17  // block expansion while also dealing with the fact that dynamic block expansion
    18  // might in turn produce nested blocks that are subject to FixUpBlockAttrs.
    19  //
    20  // This is intended as a drop-in replacement for dynblock.VariablesHCLDec,
    21  // which is itself a drop-in replacement for hcldec.Variables.
    22  func ExpandedVariables(body hcl.Body, schema *configschema.Block) []hcl.Traversal {
    23  	rootNode := dynblock.WalkVariables(body)
    24  	return walkVariables(rootNode, body, schema)
    25  }
    26  
    27  func walkVariables(node dynblock.WalkVariablesNode, body hcl.Body, schema *configschema.Block) []hcl.Traversal {
    28  	givenRawSchema := hcldec.ImpliedSchema(schema.DecoderSpec())
    29  	ambiguousNames := ambiguousNames(schema)
    30  	effectiveRawSchema := effectiveSchema(givenRawSchema, body, ambiguousNames, false)
    31  	vars, children := node.Visit(effectiveRawSchema)
    32  
    33  	for _, child := range children {
    34  		if blockS, exists := schema.BlockTypes[child.BlockTypeName]; exists {
    35  			vars = append(vars, walkVariables(child.Node, child.Body(), &blockS.Block)...)
    36  		} else if attrS, exists := schema.Attributes[child.BlockTypeName]; exists && attrS.Type.IsCollectionType() && attrS.Type.ElementType().IsObjectType() {
    37  			// ☝️Check for collection type before element type, because if this is a mis-placed reference,
    38  			// a panic here will prevent other useful diags from being elevated to show the user what to fix
    39  			synthSchema := SchemaForCtyElementType(attrS.Type.ElementType())
    40  			vars = append(vars, walkVariables(child.Node, child.Body(), synthSchema)...)
    41  		}
    42  	}
    43  
    44  	return vars
    45  }