aboutsummaryrefslogtreecommitdiffhomepage
path: root/vendor/github.com/zclconf/go-cty-yaml/cty_funcs.go
blob: b91141ccaa9488c639c4d6f017ef652ff4462920 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package yaml

import (
	"github.com/zclconf/go-cty/cty"
	"github.com/zclconf/go-cty/cty/function"
)

// YAMLDecodeFunc is a cty function for decoding arbitrary YAML source code
// into a cty Value, using the ImpliedType and Unmarshal methods of the
// Standard pre-defined converter.
var YAMLDecodeFunc = function.New(&function.Spec{
	Params: []function.Parameter{
		{
			Name: "src",
			Type: cty.String,
		},
	},
	Type: func(args []cty.Value) (cty.Type, error) {
		if !args[0].IsKnown() {
			return cty.DynamicPseudoType, nil
		}
		if args[0].IsNull() {
			return cty.NilType, function.NewArgErrorf(0, "YAML source code cannot be null")
		}
		return Standard.ImpliedType([]byte(args[0].AsString()))
	},
	Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) {
		if retType == cty.DynamicPseudoType {
			return cty.DynamicVal, nil
		}
		return Standard.Unmarshal([]byte(args[0].AsString()), retType)
	},
})

// YAMLEncodeFunc is a cty function for encoding an arbitrary cty value
// into YAML.
var YAMLEncodeFunc = function.New(&function.Spec{
	Params: []function.Parameter{
		{
			Name:             "value",
			Type:             cty.DynamicPseudoType,
			AllowNull:        true,
			AllowDynamicType: true,
		},
	},
	Type: function.StaticReturnType(cty.String),
	Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) {
		if !args[0].IsWhollyKnown() {
			return cty.UnknownVal(retType), nil
		}
		raw, err := Standard.Marshal(args[0])
		if err != nil {
			return cty.NilVal, err
		}
		return cty.StringVal(string(raw)), nil
	},
})