github.com/hashicorp/hcl/v2@v2.20.0/hclwrite/examples_test.go (about) 1 // Copyright (c) HashiCorp, Inc. 2 // SPDX-License-Identifier: MPL-2.0 3 4 package hclwrite_test 5 6 import ( 7 "fmt" 8 9 "github.com/hashicorp/hcl/v2" 10 "github.com/hashicorp/hcl/v2/hclwrite" 11 "github.com/zclconf/go-cty/cty" 12 ) 13 14 func Example_generateFromScratch() { 15 f := hclwrite.NewEmptyFile() 16 rootBody := f.Body() 17 rootBody.SetAttributeValue("string", cty.StringVal("bar")) // this is overwritten later 18 rootBody.AppendNewline() 19 rootBody.SetAttributeValue("object", cty.ObjectVal(map[string]cty.Value{ 20 "foo": cty.StringVal("foo"), 21 "bar": cty.NumberIntVal(5), 22 "baz": cty.True, 23 })) 24 rootBody.SetAttributeValue("string", cty.StringVal("foo")) 25 rootBody.SetAttributeValue("bool", cty.False) 26 rootBody.SetAttributeTraversal("path", hcl.Traversal{ 27 hcl.TraverseRoot{ 28 Name: "env", 29 }, 30 hcl.TraverseAttr{ 31 Name: "PATH", 32 }, 33 }) 34 rootBody.AppendNewline() 35 fooBlock := rootBody.AppendNewBlock("foo", nil) 36 fooBody := fooBlock.Body() 37 rootBody.AppendNewBlock("empty", nil) 38 rootBody.AppendNewline() 39 barBlock := rootBody.AppendNewBlock("bar", []string{"a", "b"}) 40 barBody := barBlock.Body() 41 42 fooBody.SetAttributeValue("hello", cty.StringVal("world")) 43 44 bazBlock := barBody.AppendNewBlock("baz", nil) 45 bazBody := bazBlock.Body() 46 bazBody.SetAttributeValue("foo", cty.NumberIntVal(10)) 47 bazBody.SetAttributeValue("beep", cty.StringVal("boop")) 48 bazBody.SetAttributeValue("baz", cty.ListValEmpty(cty.String)) 49 50 fmt.Printf("%s", f.Bytes()) 51 // Output: 52 // string = "foo" 53 // 54 // object = { 55 // bar = 5 56 // baz = true 57 // foo = "foo" 58 // } 59 // bool = false 60 // path = env.PATH 61 // 62 // foo { 63 // hello = "world" 64 // } 65 // empty { 66 // } 67 // 68 // bar "a" "b" { 69 // baz { 70 // foo = 10 71 // beep = "boop" 72 // baz = [] 73 // } 74 // } 75 } 76 77 func ExampleExpression_RenameVariablePrefix() { 78 src := []byte( 79 "foo = a.x + a.y * b.c\n" + 80 "bar = max(a.z, b.c)\n", 81 ) 82 f, diags := hclwrite.ParseConfig(src, "", hcl.Pos{Line: 1, Column: 1}) 83 if diags.HasErrors() { 84 fmt.Printf("errors: %s", diags) 85 return 86 } 87 88 // Rename references of variable "a" to "z" 89 for _, attr := range f.Body().Attributes() { 90 attr.Expr().RenameVariablePrefix( 91 []string{"a"}, 92 []string{"z"}, 93 ) 94 } 95 96 fmt.Printf("%s", f.Bytes()) 97 // Output: 98 // foo = z.x + z.y * b.c 99 // bar = max(z.z, b.c) 100 }