1
0
mirror of https://github.com/golang/go synced 2024-11-18 19:44:46 -07:00
go/internal/lsp/source/code_lens.go
Marwan Sulaiman 63da46f303 x/tools/gopls: run go generate through CodeLens
This change adds support for recognizing a //go:generate directive
and offering a CodeLens that will then send a "generate" command to
the server to run "go generate" or "go generate ./...". Because
"go generate" can only be executed per package, there is no need to show
the CodeLens on top of every //go:generate comment. Therefore, only the
top directive will be considered.

The stdout/stderr of the go generate command will be piped to the logger
while stderr will also be sent to the editor as a window/showMessage

The user will only know when the process starts and when it ends so that they wouldn't
get bogged with a large number of message windows popping up. However, they can
check the logs for all the details.

If a user wants to cancel the "go generate" command, they will be able
to do so with a "Cancel" ActionItem that the server will offer to the client

Fixes golang/go#37680

Change-Id: I89a9617521eab20859cb2215db133f34fda856c7
Reviewed-on: https://go-review.googlesource.com/c/tools/+/222247
Run-TryBot: Rebecca Stambler <rstambler@golang.org>
TryBot-Result: Gobot Gobot <gobot@golang.org>
Reviewed-by: Rebecca Stambler <rstambler@golang.org>
2020-03-17 04:34:34 +00:00

56 lines
1.3 KiB
Go

// Copyright 2020 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package source
import (
"context"
"go/token"
"path/filepath"
"strings"
"golang.org/x/tools/internal/lsp/protocol"
)
func CodeLens(ctx context.Context, snapshot Snapshot, fh FileHandle) ([]protocol.CodeLens, error) {
f, _, m, _, err := snapshot.View().Session().Cache().ParseGoHandle(fh, ParseFull).Parse(ctx)
if err != nil {
return nil, err
}
const ggDirective = "//go:generate"
for _, c := range f.Comments {
for _, l := range c.List {
if !strings.HasPrefix(l.Text, ggDirective) {
continue
}
fset := snapshot.View().Session().Cache().FileSet()
rng, err := newMappedRange(fset, m, l.Pos(), l.Pos()+token.Pos(len(ggDirective))).Range()
if err != nil {
return nil, err
}
dir := filepath.Dir(fh.Identity().URI.Filename())
return []protocol.CodeLens{
{
Range: rng,
Command: protocol.Command{
Title: "run go generate",
Command: "generate",
Arguments: []interface{}{dir, false},
},
},
{
Range: rng,
Command: protocol.Command{
Title: "run go generate ./...",
Command: "generate",
Arguments: []interface{}{dir, true},
},
},
}, nil
}
}
return nil, nil
}