Skip to content

Commit

Permalink
hcl: Introduce TokenAtPosition
Browse files Browse the repository at this point in the history
  • Loading branch information
radeksimko committed Jun 2, 2020
1 parent f7fc4bd commit 010655f
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 0 deletions.
8 changes: 8 additions & 0 deletions internal/hcl/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,3 +27,11 @@ func IsNoBlockFoundErr(err error) bool {
_, ok := err.(*NoBlockFoundErr)
return ok
}

type NoTokenFoundErr struct {
AtPos hcllib.Pos
}

func (e *NoTokenFoundErr) Error() string {
return fmt.Sprintf("no token found at %#v", e.AtPos)
}
13 changes: 13 additions & 0 deletions internal/hcl/hcl.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (

type File interface {
BlockTokensAtPosition(hcl.Pos) (hclsyntax.Tokens, error)
TokenAtPosition(hcl.Pos) (hclsyntax.Token, error)
}

type file struct {
Expand Down Expand Up @@ -87,6 +88,18 @@ func (f *file) BlockTokensAtPosition(pos hcllib.Pos) (hclsyntax.Tokens, error) {
return pf.Tokens, &NoBlockFoundErr{pos}
}

func (f *file) TokenAtPosition(pos hcllib.Pos) (hclsyntax.Token, error) {
pf, _ := f.parse()

for _, t := range pf.Tokens {
if rangeContainsOffset(t.Range, pos.Byte) {
return t, nil
}
}

return hclsyntax.Token{}, &NoTokenFoundErr{pos}
}

func tokensInRange(tokens hclsyntax.Tokens, rng hcllib.Range) hclsyntax.Tokens {
var ts hclsyntax.Tokens

Expand Down

0 comments on commit 010655f

Please sign in to comment.