Skip to content

Commit 9be3dab

Browse files
committed
filesystem: Avoid crash when file is not open
1 parent 78966e8 commit 9be3dab

File tree

2 files changed

+21
-4
lines changed

2 files changed

+21
-4
lines changed

internal/filesystem/filesystem.go

+20-4
Original file line numberDiff line numberDiff line change
@@ -2,15 +2,19 @@ package filesystem
22

33
import (
44
"fmt"
5+
"io/ioutil"
6+
"log"
57
"sync"
68

79
"github.com/hashicorp/hcl/v2"
810
lsp "github.com/sourcegraph/go-lsp"
911
)
1012

1113
type fsystem struct {
12-
mu sync.RWMutex
13-
dirs map[string]*dir
14+
mu sync.RWMutex
15+
16+
logger *log.Logger
17+
dirs map[string]*dir
1418
}
1519

1620
type Filesystem interface {
@@ -23,10 +27,15 @@ type Filesystem interface {
2327

2428
func NewFilesystem() *fsystem {
2529
return &fsystem{
26-
dirs: make(map[string]*dir),
30+
dirs: make(map[string]*dir),
31+
logger: log.New(ioutil.Discard, "", 0),
2732
}
2833
}
2934

35+
func (fs *fsystem) SetLogger(logger *log.Logger) {
36+
fs.logger = logger
37+
}
38+
3039
func (fs *fsystem) Open(doc lsp.TextDocumentItem) error {
3140
fs.mu.Lock()
3241
defer fs.mu.Unlock()
@@ -89,11 +98,18 @@ func (fs *fsystem) URI(uri lsp.DocumentURI) URI {
8998
}
9099

91100
func (fs *fsystem) HclBlockAtDocPosition(params lsp.TextDocumentPositionParams) (*hcl.Block, hcl.Pos, error) {
92-
u := URI(params.TextDocument.URI)
101+
u := fs.URI(params.TextDocument.URI)
93102
f := fs.file(u)
103+
if f == nil || !f.open {
104+
return nil, hcl.Pos{}, fmt.Errorf("file %q is not open", u)
105+
}
106+
107+
fs.logger.Printf("Converting LSP position %#v into HCL", params.Position)
94108

95109
hclPos := f.LspPosToHCLPos(params.Position)
96110

111+
fs.logger.Printf("Finding HCL block at position %#v", hclPos)
112+
97113
block, err := f.HclBlockAtPos(hclPos)
98114

99115
return block, hclPos, err

langserver/handler_map.go

+1
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ type handlerMap struct {
3030
// and passes related dependencies to methods via context
3131
func (hm *handlerMap) Map() rpch.Map {
3232
fs := filesystem.NewFilesystem()
33+
fs.SetLogger(hm.logger)
3334
lh := logHandler{hm.logger}
3435

3536
m := map[string]rpch.Func{

0 commit comments

Comments
 (0)