github.com/terraform-linters/tflint-plugin-sdk@v0.22.0/hclext/decode_example_test.go (about)

     1  package hclext
     2  
     3  import (
     4  	"fmt"
     5  
     6  	"github.com/hashicorp/hcl/v2"
     7  	"github.com/hashicorp/hcl/v2/hclsyntax"
     8  )
     9  
    10  func ExampleDecodeBody() {
    11  	src := `
    12  noodle "foo" "bar" {
    13  	type = "rice"
    14  
    15  	bread "baz" {
    16  		type  = "focaccia"
    17  		baked = true
    18  	}
    19  	bread "quz" {
    20  		type = "rye"
    21  	}
    22  }`
    23  	file, diags := hclsyntax.ParseConfig([]byte(src), "test.tf", hcl.InitialPos)
    24  	if diags.HasErrors() {
    25  		panic(diags)
    26  	}
    27  
    28  	type Bread struct {
    29  		// The `*,label` tag matches "bread" block labels.
    30  		// The count of tags should be matched to count of block labels.
    31  		Name string `hclext:"name,label"`
    32  		// The `type` tag matches a "type" attribute inside of "bread" block.
    33  		Type string `hclext:"type"`
    34  		// The `baked,optional` tag matches a "baked" attribute, but it is optional.
    35  		Baked bool `hclext:"baked,optional"`
    36  	}
    37  	type Noodle struct {
    38  		Name    string `hclext:"name,label"`
    39  		SubName string `hclext:"subname,label"`
    40  		Type    string `hclext:"type"`
    41  		// The `bread,block` tag matches "bread" blocks.
    42  		// Multiple blocks are allowed because the field type is slice.
    43  		Breads []Bread `hclext:"bread,block"`
    44  	}
    45  	type Config struct {
    46  		// Only 1 block must be needed because the field type is not slice, not a pointer.
    47  		Noodle Noodle `hclext:"noodle,block"`
    48  	}
    49  
    50  	target := &Config{}
    51  
    52  	schema := ImpliedBodySchema(target)
    53  	body, diags := Content(file.Body, schema)
    54  	if diags.HasErrors() {
    55  		panic(diags)
    56  	}
    57  
    58  	diags = DecodeBody(body, nil, target)
    59  	if diags.HasErrors() {
    60  		panic(diags)
    61  	}
    62  
    63  	fmt.Printf("- noodle: name=%s, subname=%s type=%s\n", target.Noodle.Name, target.Noodle.SubName, target.Noodle.Type)
    64  	for i, bread := range target.Noodle.Breads {
    65  		fmt.Printf("  - bread[%d]: name=%s, type=%s baked=%t\n", i, bread.Name, bread.Type, bread.Baked)
    66  	}
    67  	// Output:
    68  	// - noodle: name=foo, subname=bar type=rice
    69  	//   - bread[0]: name=baz, type=focaccia baked=true
    70  	//   - bread[1]: name=quz, type=rye baked=false
    71  }