forked from hashicorp/hcl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexamples_test.go
97 lines (88 loc) · 2.16 KB
/
examples_test.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package hclwrite_test
import (
"fmt"
"github.com/hashicorp/hcl/v2"
"github.com/hashicorp/hcl/v2/hclwrite"
"github.com/zclconf/go-cty/cty"
)
func Example_generateFromScratch() {
f := hclwrite.NewEmptyFile()
rootBody := f.Body()
rootBody.SetAttributeValue("string", cty.StringVal("bar")) // this is overwritten later
rootBody.AppendNewline()
rootBody.SetAttributeValue("object", cty.ObjectVal(map[string]cty.Value{
"foo": cty.StringVal("foo"),
"bar": cty.NumberIntVal(5),
"baz": cty.True,
}))
rootBody.SetAttributeValue("string", cty.StringVal("foo"))
rootBody.SetAttributeValue("bool", cty.False)
rootBody.SetAttributeTraversal("path", hcl.Traversal{
hcl.TraverseRoot{
Name: "env",
},
hcl.TraverseAttr{
Name: "PATH",
},
})
rootBody.AppendNewline()
fooBlock := rootBody.AppendNewBlock("foo", nil)
fooBody := fooBlock.Body()
rootBody.AppendNewBlock("empty", nil)
rootBody.AppendNewline()
barBlock := rootBody.AppendNewBlock("bar", []string{"a", "b"})
barBody := barBlock.Body()
fooBody.SetAttributeValue("hello", cty.StringVal("world"))
bazBlock := barBody.AppendNewBlock("baz", nil)
bazBody := bazBlock.Body()
bazBody.SetAttributeValue("foo", cty.NumberIntVal(10))
bazBody.SetAttributeValue("beep", cty.StringVal("boop"))
bazBody.SetAttributeValue("baz", cty.ListValEmpty(cty.String))
fmt.Printf("%s", f.Bytes())
// Output:
// string = "foo"
//
// object = {
// bar = 5
// baz = true
// foo = "foo"
// }
// bool = false
// path = env.PATH
//
// foo {
// hello = "world"
// }
// empty {
// }
//
// bar "a" "b" {
// baz {
// foo = 10
// beep = "boop"
// baz = []
// }
// }
}
func ExampleExpression_RenameVariablePrefix() {
src := []byte(
"foo = a.x + a.y * b.c\n" +
"bar = max(a.z, b.c)\n",
)
f, diags := hclwrite.ParseConfig(src, "", hcl.Pos{Line: 1, Column: 1})
if diags.HasErrors() {
fmt.Printf("errors: %s", diags)
return
}
// Rename references of variable "a" to "z"
for _, attr := range f.Body().Attributes() {
attr.Expr().RenameVariablePrefix(
[]string{"a"},
[]string{"z"},
)
}
fmt.Printf("%s", f.Bytes())
// Output:
// foo = z.x + z.y * b.c
// bar = max(z.z, b.c)
}