summaryrefslogtreecommitdiff
path: root/hclsyntax/navigation.go
blob: 83e1d4efb5d5133062457251c9f1618d6509f67a (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
51
52
53
54
55
56
57
58
59
60
61
62
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0

package hclsyntax

import (
	"bytes"
	"fmt"

	"github.com/hashicorp/hcl/v2"
)

type navigation struct {
	root *Body
}

// Implementation of hcled.ContextString
func (n navigation) ContextString(offset int) string {
	// We will walk our top-level blocks until we find one that contains
	// the given offset, and then construct a representation of the header
	// of the block.

	var block *Block
	for _, candidate := range n.root.Blocks {
		if candidate.Range().ContainsOffset(offset) {
			block = candidate
			break
		}
	}

	if block == nil {
		return ""
	}

	if len(block.Labels) == 0 {
		// Easy case!
		return block.Type
	}

	buf := &bytes.Buffer{}
	buf.WriteString(block.Type)
	for _, label := range block.Labels {
		fmt.Fprintf(buf, " %q", label)
	}
	return buf.String()
}

func (n navigation) ContextDefRange(offset int) hcl.Range {
	var block *Block
	for _, candidate := range n.root.Blocks {
		if candidate.Range().ContainsOffset(offset) {
			block = candidate
			break
		}
	}

	if block == nil {
		return hcl.Range{}
	}

	return block.DefRange()
}