github.com/beauknowssoftware/makehcl@v0.0.0-20200322000747-1b9bb1e1c008/internal/functions/exists.go (about)

     1  package functions
     2  
     3  import (
     4  	"fmt"
     5  
     6  	"github.com/zclconf/go-cty/cty"
     7  	"github.com/zclconf/go-cty/cty/function"
     8  )
     9  
    10  func Exists(args []cty.Value, _ cty.Type) (cty.Value, error) {
    11  	key := args[1].AsString()
    12  
    13  	t := args[0].Type()
    14  
    15  	switch {
    16  	case t.IsObjectType():
    17  		res := t.HasAttribute(key)
    18  		return cty.BoolVal(res), nil
    19  	case t.IsMapType():
    20  		m := args[0].AsValueMap()
    21  		_, res := m[key]
    22  
    23  		return cty.BoolVal(res), nil
    24  	default:
    25  		return cty.False, fmt.Errorf("expected map or object got %v", t.FriendlyName())
    26  	}
    27  }
    28  
    29  var ExistsSpec = function.Spec{
    30  	Params: []function.Parameter{
    31  		{Type: cty.DynamicPseudoType},
    32  		{Type: cty.String},
    33  	},
    34  	Type: function.StaticReturnType(cty.Bool),
    35  	Impl: Exists,
    36  }