summaryrefslogtreecommitdiff
path: root/hclwrite/ast_test.go
blob: 12bb05468f787ce60a75c7d1af3237e75a82e1d1 (plain)
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
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0

package hclwrite

import (
	"fmt"
	"strings"
)

type TestTreeNode struct {
	Type string
	Val  string

	Children []TestTreeNode
}

func makeTestTree(n *node) (root TestTreeNode) {
	const us = "hclwrite."
	const usPtr = "*hclwrite."
	root.Type = fmt.Sprintf("%T", n.content)
	if strings.HasPrefix(root.Type, us) {
		root.Type = root.Type[len(us):]
	} else if strings.HasPrefix(root.Type, usPtr) {
		root.Type = root.Type[len(usPtr):]
	}

	type WithVal interface {
		testValue() string
	}
	hasTestVal := false
	if withVal, ok := n.content.(WithVal); ok {
		root.Val = withVal.testValue()
		hasTestVal = true
	}

	n.content.walkChildNodes(func(n *node) {
		root.Children = append(root.Children, makeTestTree(n))
	})

	// If we didn't end up with any children then this is probably a leaf
	// node, so we'll set its content value to it raw bytes if we didn't
	// already set a test value.
	if !hasTestVal && len(root.Children) == 0 {
		toks := n.content.BuildTokens(nil)
		root.Val = toks.testValue()
	}

	return root
}