github.com/hashicorp/hcl/v2@v2.20.0/hclwrite/ast_test.go (about)

     1  // Copyright (c) HashiCorp, Inc.
     2  // SPDX-License-Identifier: MPL-2.0
     3  
     4  package hclwrite
     5  
     6  import (
     7  	"fmt"
     8  	"strings"
     9  )
    10  
    11  type TestTreeNode struct {
    12  	Type string
    13  	Val  string
    14  
    15  	Children []TestTreeNode
    16  }
    17  
    18  func makeTestTree(n *node) (root TestTreeNode) {
    19  	const us = "hclwrite."
    20  	const usPtr = "*hclwrite."
    21  	root.Type = fmt.Sprintf("%T", n.content)
    22  	if strings.HasPrefix(root.Type, us) {
    23  		root.Type = root.Type[len(us):]
    24  	} else if strings.HasPrefix(root.Type, usPtr) {
    25  		root.Type = root.Type[len(usPtr):]
    26  	}
    27  
    28  	type WithVal interface {
    29  		testValue() string
    30  	}
    31  	hasTestVal := false
    32  	if withVal, ok := n.content.(WithVal); ok {
    33  		root.Val = withVal.testValue()
    34  		hasTestVal = true
    35  	}
    36  
    37  	n.content.walkChildNodes(func(n *node) {
    38  		root.Children = append(root.Children, makeTestTree(n))
    39  	})
    40  
    41  	// If we didn't end up with any children then this is probably a leaf
    42  	// node, so we'll set its content value to it raw bytes if we didn't
    43  	// already set a test value.
    44  	if !hasTestVal && len(root.Children) == 0 {
    45  		toks := n.content.BuildTokens(nil)
    46  		root.Val = toks.testValue()
    47  	}
    48  
    49  	return root
    50  }