Skip to content

Commit

Permalink
feat(lsp): also probe common directories to look for gopls, see #127
Browse files Browse the repository at this point in the history
  • Loading branch information
a-h committed Nov 14, 2023
1 parent 6e36230 commit 8d2651a
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 8 deletions.
2 changes: 1 addition & 1 deletion .version
Original file line number Diff line number Diff line change
@@ -1 +1 @@
0.2.473
0.2.474
40 changes: 33 additions & 7 deletions cmd/templ/lspcmd/pls/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"io"
"os"
"os/exec"
"path"

"go.uber.org/zap"
)
Expand All @@ -29,17 +30,42 @@ func (opts Options) AsArguments() []string {
return args
}

// NewGopls starts gopls and opens up a jsonrpc2 connection to it.
func NewGopls(ctx context.Context, log *zap.Logger, opts Options) (rwc io.ReadWriteCloser, err error) {
func findGopls() (location string, err error) {
_, err = exec.LookPath("gopls")
if errors.Is(err, exec.ErrNotFound) {
err = fmt.Errorf("cannot find gopls on the path (%q), you can install it with `go install golang.org/x/tools/gopls@latest`", os.Getenv("PATH"))
return
if err == nil {
// Found on the path.
return "gopls", nil
}

// Unexpected error.
if !errors.Is(err, exec.ErrNotFound) {
return "", fmt.Errorf("unexpected error looking for gopls: %w", err)
}

// Probe standard locations.
locations := []string{
path.Join(os.Getenv("HOME"), "go", "bin", "gopls"),
path.Join(os.Getenv("HOME"), ".local", "bin", "gopls"),
}
for _, location := range locations {
_, err = os.Stat(location)
if err != nil {
continue
}
// Found in a standard location.
return location, nil
}

return "", fmt.Errorf("cannot find gopls on the path (%q), in $HOME/go/bin or $HOME/.local/bin/gopls. You can install gopls with `go install golang.org/x/tools/gopls@latest`", os.Getenv("PATH"))
}

// NewGopls starts gopls and opens up a jsonrpc2 connection to it.
func NewGopls(ctx context.Context, log *zap.Logger, opts Options) (rwc io.ReadWriteCloser, err error) {
location, err := findGopls()
if err != nil {
return
return nil, err
}
cmd := exec.Command("gopls", opts.AsArguments()...)
cmd := exec.Command(location, opts.AsArguments()...)
return newProcessReadWriteCloser(log, cmd)
}

Expand Down

0 comments on commit 8d2651a

Please sign in to comment.