github.com/hashicorp/hcl/v2@v2.20.0/hclsyntax/navigation.go (about)

     1  // Copyright (c) HashiCorp, Inc.
     2  // SPDX-License-Identifier: MPL-2.0
     3  
     4  package hclsyntax
     5  
     6  import (
     7  	"bytes"
     8  	"fmt"
     9  
    10  	"github.com/hashicorp/hcl/v2"
    11  )
    12  
    13  type navigation struct {
    14  	root *Body
    15  }
    16  
    17  // Implementation of hcled.ContextString
    18  func (n navigation) ContextString(offset int) string {
    19  	// We will walk our top-level blocks until we find one that contains
    20  	// the given offset, and then construct a representation of the header
    21  	// of the block.
    22  
    23  	var block *Block
    24  	for _, candidate := range n.root.Blocks {
    25  		if candidate.Range().ContainsOffset(offset) {
    26  			block = candidate
    27  			break
    28  		}
    29  	}
    30  
    31  	if block == nil {
    32  		return ""
    33  	}
    34  
    35  	if len(block.Labels) == 0 {
    36  		// Easy case!
    37  		return block.Type
    38  	}
    39  
    40  	buf := &bytes.Buffer{}
    41  	buf.WriteString(block.Type)
    42  	for _, label := range block.Labels {
    43  		fmt.Fprintf(buf, " %q", label)
    44  	}
    45  	return buf.String()
    46  }
    47  
    48  func (n navigation) ContextDefRange(offset int) hcl.Range {
    49  	var block *Block
    50  	for _, candidate := range n.root.Blocks {
    51  		if candidate.Range().ContainsOffset(offset) {
    52  			block = candidate
    53  			break
    54  		}
    55  	}
    56  
    57  	if block == nil {
    58  		return hcl.Range{}
    59  	}
    60  
    61  	return block.DefRange()
    62  }