github.com/hashicorp/hcl/v2@v2.20.0/hcldec/variables.go (about)

     1  // Copyright (c) HashiCorp, Inc.
     2  // SPDX-License-Identifier: MPL-2.0
     3  
     4  package hcldec
     5  
     6  import (
     7  	"github.com/hashicorp/hcl/v2"
     8  )
     9  
    10  // Variables processes the given body with the given spec and returns a
    11  // list of the variable traversals that would be required to decode
    12  // the same pairing of body and spec.
    13  //
    14  // This can be used to conditionally populate the variables in the EvalContext
    15  // passed to Decode, for applications where a static scope is insufficient.
    16  //
    17  // If the given body is not compliant with the given schema, the result may
    18  // be incomplete, but that's assumed to be okay because the eventual call
    19  // to Decode will produce error diagnostics anyway.
    20  func Variables(body hcl.Body, spec Spec) []hcl.Traversal {
    21  	var vars []hcl.Traversal
    22  	schema := ImpliedSchema(spec)
    23  	content, _, _ := body.PartialContent(schema)
    24  
    25  	if vs, ok := spec.(specNeedingVariables); ok {
    26  		vars = append(vars, vs.variablesNeeded(content)...)
    27  	}
    28  
    29  	var visitFn visitFunc
    30  	visitFn = func(s Spec) {
    31  		if vs, ok := s.(specNeedingVariables); ok {
    32  			vars = append(vars, vs.variablesNeeded(content)...)
    33  		}
    34  		s.visitSameBodyChildren(visitFn)
    35  	}
    36  	spec.visitSameBodyChildren(visitFn)
    37  
    38  	return vars
    39  }