-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathyaml2hcl.go
62 lines (56 loc) · 1.59 KB
/
yaml2hcl.go
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
58
59
60
61
62
// Copyright © 2020 Martin Whittington <[email protected]>.
//
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file
package yaml2hcl
import (
"fmt"
"github.com/hashicorp/hcl/v2/hclwrite"
"github.com/zclconf/go-cty/cty"
)
func getValue(value interface{}) cty.Value {
switch t := value.(type) {
case string:
return cty.StringVal(t)
case int:
return cty.NumberIntVal(int64(t))
case bool:
return cty.BoolVal(t)
case map[interface{}]interface{}:
m := make(map[string]cty.Value)
for k, v := range t {
m[fmt.Sprintf("%v", k)] = getValue(v)
}
return cty.ObjectVal(m)
case []interface{}:
if len(t) < 1 {
return cty.ListValEmpty(cty.String)
}
vals := []cty.Value{}
for _, n := range t {
val := getValue(n)
vals = append(vals, val)
}
return cty.ListVal(vals)
default:
// type not handled yet
fmt.Printf("** yaml2hcl ** type is %s", t)
return cty.NullVal(cty.String)
}
}
// Convert converts a map of interfaces (unmarshalled from Yaml) and returns the HCL body
func Convert(vars map[interface{}]interface{}) *hclwrite.Body {
f := hclwrite.NewEmptyFile()
for key, value := range vars {
f.Body().SetAttributeValue(fmt.Sprintf("%v", key), getValue(value))
}
return f.Body()
}
// ConvertToString converts a map of interfaces (unmarshalled from Yaml) and returns the HCL body as a string
func ConvertToString(vars map[interface{}]interface{}) string {
f := hclwrite.NewEmptyFile()
for key, value := range vars {
f.Body().SetAttributeValue(fmt.Sprintf("%v", key), getValue(value))
}
return string(f.Bytes())
}