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

     1  package funcs
     2  
     3  import (
     4  	"github.com/eliastor/durgaform/internal/lang/marks"
     5  	"github.com/zclconf/go-cty/cty"
     6  	"github.com/zclconf/go-cty/cty/function"
     7  )
     8  
     9  // SensitiveFunc returns a value identical to its argument except that
    10  // Durgaform will consider it to be sensitive.
    11  var SensitiveFunc = function.New(&function.Spec{
    12  	Params: []function.Parameter{
    13  		{
    14  			Name:             "value",
    15  			Type:             cty.DynamicPseudoType,
    16  			AllowUnknown:     true,
    17  			AllowNull:        true,
    18  			AllowMarked:      true,
    19  			AllowDynamicType: true,
    20  		},
    21  	},
    22  	Type: func(args []cty.Value) (cty.Type, error) {
    23  		// This function only affects the value's marks, so the result
    24  		// type is always the same as the argument type.
    25  		return args[0].Type(), nil
    26  	},
    27  	Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) {
    28  		val, _ := args[0].Unmark()
    29  		return val.Mark(marks.Sensitive), nil
    30  	},
    31  })
    32  
    33  // NonsensitiveFunc takes a sensitive value and returns the same value without
    34  // the sensitive marking, effectively exposing the value.
    35  var NonsensitiveFunc = function.New(&function.Spec{
    36  	Params: []function.Parameter{
    37  		{
    38  			Name:             "value",
    39  			Type:             cty.DynamicPseudoType,
    40  			AllowUnknown:     true,
    41  			AllowNull:        true,
    42  			AllowMarked:      true,
    43  			AllowDynamicType: true,
    44  		},
    45  	},
    46  	Type: func(args []cty.Value) (cty.Type, error) {
    47  		// This function only affects the value's marks, so the result
    48  		// type is always the same as the argument type.
    49  		return args[0].Type(), nil
    50  	},
    51  	Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) {
    52  		if args[0].IsKnown() && !args[0].HasMark(marks.Sensitive) {
    53  			return cty.DynamicVal, function.NewArgErrorf(0, "the given value is not sensitive, so this call is redundant")
    54  		}
    55  		v, m := args[0].Unmark()
    56  		delete(m, marks.Sensitive) // remove the sensitive marking
    57  		return v.WithMarks(m), nil
    58  	},
    59  })
    60  
    61  func Sensitive(v cty.Value) (cty.Value, error) {
    62  	return SensitiveFunc.Call([]cty.Value{v})
    63  }
    64  
    65  func Nonsensitive(v cty.Value) (cty.Value, error) {
    66  	return NonsensitiveFunc.Call([]cty.Value{v})
    67  }