aboutsummaryrefslogtreecommitdiffhomepage
path: root/vendor/github.com/hashicorp/hcl2/hcl/json/navigation.go
blob: bc8a97f749dfa8760e50df249a679ad028e16396 (plain) (blame)
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
package json

import (
	"fmt"
	"strings"
)

type navigation struct {
	root node
}

// Implementation of hcled.ContextString
func (n navigation) ContextString(offset int) string {
	steps := navigationStepsRev(n.root, offset)
	if steps == nil {
		return ""
	}

	// We built our slice backwards, so we'll reverse it in-place now.
	half := len(steps) / 2 // integer division
	for i := 0; i < half; i++ {
		steps[i], steps[len(steps)-1-i] = steps[len(steps)-1-i], steps[i]
	}

	ret := strings.Join(steps, "")
	if len(ret) > 0 && ret[0] == '.' {
		ret = ret[1:]
	}
	return ret
}

func navigationStepsRev(v node, offset int) []string {
	switch tv := v.(type) {
	case *objectVal:
		// Do any of our properties have an object that contains the target
		// offset?
		for _, attr := range tv.Attrs {
			k := attr.Name
			av := attr.Value

			switch av.(type) {
			case *objectVal, *arrayVal:
				// okay
			default:
				continue
			}

			if av.Range().ContainsOffset(offset) {
				return append(navigationStepsRev(av, offset), "."+k)
			}
		}
	case *arrayVal:
		// Do any of our elements contain the target offset?
		for i, elem := range tv.Values {

			switch elem.(type) {
			case *objectVal, *arrayVal:
				// okay
			default:
				continue
			}

			if elem.Range().ContainsOffset(offset) {
				return append(navigationStepsRev(elem, offset), fmt.Sprintf("[%d]", i))
			}
		}
	}

	return nil
}