internal/lsp: change the way that we pass arguments to command

Our approach to commands and their arguments has been ad-hoc until this
point. This CL creates a standard way of defining and passing the
arguments to different commands. The arguments to a command are now
json.RawMessages, so that we don't have to double encode. This also
allows us to check the expected number of arguments without defining
a struct for every command.

Change-Id: Ic765c9b059e8ec3e1985046d13bf321be21f16ab
Reviewed-on: https://go-review.googlesource.com/c/tools/+/242697
Run-TryBot: Rebecca Stambler <rstambler@golang.org>
TryBot-Result: Gobot Gobot <gobot@golang.org>
Reviewed-by: Robert Findley <rfindley@google.com>
This commit is contained in:
Rebecca Stambler 2020-07-14 20:40:38 -04:00
parent b8e13e1a4d
commit 5ea363182e
10 changed files with 176 additions and 128 deletions

View File

@ -6,7 +6,6 @@ package lsp
import (
"context"
"encoding/json"
"fmt"
"sort"
"strings"
@ -330,10 +329,7 @@ func convenienceFixes(ctx context.Context, snapshot source.Snapshot, ph source.P
// The fix depends on the category of the analyzer.
switch d.Category {
case fillstruct.Analyzer.Name:
arg, err := json.Marshal(CommandRangeArgument{
URI: protocol.URIFromSpanURI(d.URI),
Range: d.Range,
})
jsonArgs, err := source.EncodeArgs(d.URI, d.Range)
if err != nil {
return nil, err
}
@ -341,11 +337,9 @@ func convenienceFixes(ctx context.Context, snapshot source.Snapshot, ph source.P
Title: d.Message,
Kind: protocol.RefactorRewrite,
Command: &protocol.Command{
Command: source.CommandFillStruct,
Title: d.Message,
Arguments: []interface{}{
string(arg),
},
Command: source.CommandFillStruct,
Title: d.Message,
Arguments: jsonArgs,
},
}
codeActions = append(codeActions, action)

28
internal/lsp/code_lens.go Normal file
View File

@ -0,0 +1,28 @@
// 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 lsp
import (
"context"
"golang.org/x/tools/internal/lsp/mod"
"golang.org/x/tools/internal/lsp/protocol"
"golang.org/x/tools/internal/lsp/source"
)
func (s *Server) codeLens(ctx context.Context, params *protocol.CodeLensParams) ([]protocol.CodeLens, error) {
snapshot, fh, ok, err := s.beginFileRequest(ctx, params.TextDocument.URI, source.UnknownKind)
if !ok {
return nil, err
}
switch fh.Kind() {
case source.Mod:
return mod.CodeLens(ctx, snapshot, fh.URI())
case source.Go:
return source.CodeLens(ctx, snapshot, fh)
}
// Unsupported file kind for a code action.
return nil, nil
}

View File

@ -6,10 +6,8 @@ package lsp
import (
"context"
"encoding/json"
"fmt"
"io"
"strings"
"golang.org/x/tools/internal/event"
"golang.org/x/tools/internal/lsp/debug/tag"
@ -20,11 +18,6 @@ import (
errors "golang.org/x/xerrors"
)
type CommandRangeArgument struct {
URI protocol.DocumentURI `json:"uri,omitempty"`
Range protocol.Range `json:"range,omitempty"`
}
func (s *Server) executeCommand(ctx context.Context, params *protocol.ExecuteCommandParams) (interface{}, error) {
var found bool
for _, command := range s.session.Options().SupportedCommands {
@ -36,82 +29,86 @@ func (s *Server) executeCommand(ctx context.Context, params *protocol.ExecuteCom
if !found {
return nil, fmt.Errorf("unsupported command detected: %s", params.Command)
}
switch params.Command {
case source.CommandTest:
unsaved := false
for _, overlay := range s.session.Overlays() {
if !overlay.Saved() {
unsaved = true
break
}
// Some commands require that all files are saved to disk. If we detect
// unsaved files, warn the user instead of running the commands.
unsaved := false
for _, overlay := range s.session.Overlays() {
if !overlay.Saved() {
unsaved = true
break
}
if unsaved {
}
if unsaved {
switch params.Command {
case source.CommandTest, source.CommandGenerate:
return nil, s.client.ShowMessage(ctx, &protocol.ShowMessageParams{
Type: protocol.Error,
Message: "could not run tests, there are unsaved files in the view",
Message: fmt.Sprintf("cannot run command %s: unsaved files in the view", params.Command),
})
}
funcName, uri, err := getRunTestArguments(params.Arguments)
if err != nil {
}
switch params.Command {
case source.CommandTest:
var uri protocol.DocumentURI
var funcName string
if err := source.DecodeArgs(params.Arguments, &uri, &funcName); err != nil {
return nil, err
}
view, err := s.session.ViewOf(uri)
if err != nil {
snapshot, _, ok, err := s.beginFileRequest(ctx, uri, source.UnknownKind)
if !ok {
return nil, err
}
go s.runTest(ctx, view.Snapshot(), funcName)
go s.runGoTest(ctx, snapshot, funcName)
case source.CommandGenerate:
dir, recursive, err := getGenerateRequest(params.Arguments)
if err != nil {
var uri protocol.DocumentURI
var recursive bool
if err := source.DecodeArgs(params.Arguments, &uri, &recursive); err != nil {
return nil, err
}
go s.runGoGenerate(xcontext.Detach(ctx), dir, recursive)
go s.runGoGenerate(xcontext.Detach(ctx), uri.SpanURI(), recursive)
case source.CommandRegenerateCgo:
var uri protocol.DocumentURI
if err := source.DecodeArgs(params.Arguments, &uri); err != nil {
return nil, err
}
mod := source.FileModification{
URI: protocol.DocumentURI(params.Arguments[0].(string)).SpanURI(),
URI: uri.SpanURI(),
Action: source.InvalidateMetadata,
}
_, err := s.didModifyFiles(ctx, []source.FileModification{mod}, FromRegenerateCgo)
return nil, err
case source.CommandTidy, source.CommandVendor:
if len(params.Arguments) == 0 || len(params.Arguments) > 1 {
return nil, errors.Errorf("expected 1 argument, got %v", params.Arguments)
var uri protocol.DocumentURI
if err := source.DecodeArgs(params.Arguments, &uri); err != nil {
return nil, err
}
uri := protocol.DocumentURI(params.Arguments[0].(string))
// The flow for `go mod tidy` and `go mod vendor` is almost identical,
// so we combine them into one case for convenience.
arg := "tidy"
a := "tidy"
if params.Command == source.CommandVendor {
arg = "vendor"
a = "vendor"
}
err := s.directGoModCommand(ctx, uri, "mod", []string{arg}...)
err := s.directGoModCommand(ctx, uri, "mod", []string{a}...)
return nil, err
case source.CommandUpgradeDependency:
if len(params.Arguments) < 2 {
return nil, errors.Errorf("expected 2 arguments, got %v", params.Arguments)
var uri protocol.DocumentURI
var deps []string
if err := source.DecodeArgs(params.Arguments, &uri, &deps); err != nil {
return nil, err
}
uri := protocol.DocumentURI(params.Arguments[0].(string))
deps := params.Arguments[1].(string)
err := s.directGoModCommand(ctx, uri, "get", strings.Split(deps, " ")...)
err := s.directGoModCommand(ctx, uri, "get", deps...)
return nil, err
case source.CommandFillStruct:
if len(params.Arguments) != 1 {
return nil, fmt.Errorf("expected 1 arguments, got %v: %v", len(params.Arguments), params.Arguments)
}
var arg CommandRangeArgument
str, ok := params.Arguments[0].(string)
if !ok {
return nil, fmt.Errorf("expected string, got %v (%T)", params.Arguments[0], params.Arguments[0])
}
if err := json.Unmarshal([]byte(str), &arg); err != nil {
var uri protocol.DocumentURI
var rng protocol.Range
if err := source.DecodeArgs(params.Arguments, &uri, &rng); err != nil {
return nil, err
}
snapshot, fh, ok, err := s.beginFileRequest(ctx, arg.URI, source.Go)
snapshot, fh, ok, err := s.beginFileRequest(ctx, uri, source.Go)
if !ok {
return nil, err
}
edits, err := source.FillStruct(ctx, snapshot, fh, arg.Range)
edits, err := source.FillStruct(ctx, snapshot, fh, rng)
if err != nil {
return nil, err
}
@ -129,6 +126,8 @@ func (s *Server) executeCommand(ctx context.Context, params *protocol.ExecuteCom
Message: fmt.Sprintf("fillstruct failed: %v", r.FailureReason),
})
}
default:
return nil, fmt.Errorf("unknown command: %s", params.Command)
}
return nil, nil
}
@ -141,7 +140,7 @@ func (s *Server) directGoModCommand(ctx context.Context, uri protocol.DocumentUR
return view.Snapshot().RunGoCommandDirect(ctx, verb, args)
}
func (s *Server) runTest(ctx context.Context, snapshot source.Snapshot, funcName string) error {
func (s *Server) runGoTest(ctx context.Context, snapshot source.Snapshot, funcName string) error {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
@ -171,7 +170,7 @@ func (s *Server) runTest(ctx context.Context, snapshot source.Snapshot, funcName
// generate commands. It is exported for testing purposes.
const GenerateWorkDoneTitle = "generate"
func (s *Server) runGoGenerate(ctx context.Context, dir string, recursive bool) error {
func (s *Server) runGoGenerate(ctx context.Context, uri span.URI, recursive bool) error {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
@ -184,7 +183,6 @@ func (s *Server) runGoGenerate(ctx context.Context, dir string, recursive bool)
}
stderr := io.MultiWriter(er, wc)
uri := span.URIFromPath(dir)
view, err := s.session.ViewOf(uri)
if err != nil {
return err
@ -202,33 +200,3 @@ func (s *Server) runGoGenerate(ctx context.Context, dir string, recursive bool)
}
return nil
}
func getRunTestArguments(args []interface{}) (string, span.URI, error) {
if len(args) != 2 {
return "", "", errors.Errorf("expected one test func name and one file path, got %v", args)
}
funcName, ok := args[0].(string)
if !ok {
return "", "", errors.Errorf("expected func name to be a string, got %T", args[0])
}
filename, ok := args[1].(string)
if !ok {
return "", "", errors.Errorf("expected file to be a string, got %T", args[1])
}
return funcName, span.URIFromPath(filename), nil
}
func getGenerateRequest(args []interface{}) (string, bool, error) {
if len(args) != 2 {
return "", false, errors.Errorf("expected exactly 2 arguments but got %d", len(args))
}
dir, ok := args[0].(string)
if !ok {
return "", false, errors.Errorf("expected dir to be a string value but got %T", args[0])
}
recursive, ok := args[1].(bool)
if !ok {
return "", false, errors.Errorf("expected recursive to be a boolean but got %T", args[1])
}
return dir, recursive, nil
}

View File

@ -16,6 +16,8 @@ import (
"golang.org/x/tools/internal/jsonrpc2"
"golang.org/x/tools/internal/lsp/protocol"
"golang.org/x/tools/internal/lsp/source"
"golang.org/x/tools/internal/span"
)
// Editor is a fake editor client. It keeps track of client state and can be
@ -714,9 +716,13 @@ func (e *Editor) RunGenerate(ctx context.Context, dir string) error {
return nil
}
absDir := e.sandbox.Workdir.filePath(dir)
jsonArgs, err := source.EncodeArgs(span.URIFromPath(absDir), false)
if err != nil {
return err
}
params := &protocol.ExecuteCommandParams{
Command: "generate",
Arguments: []interface{}{absDir, false},
Command: source.CommandGenerate,
Arguments: jsonArgs,
}
if _, err := e.Server.ExecuteCommand(ctx, params); err != nil {
return fmt.Errorf("running generate: %v", err)

View File

@ -3,7 +3,6 @@ package mod
import (
"context"
"fmt"
"strings"
"golang.org/x/mod/modfile"
"golang.org/x/tools/internal/event"
@ -60,12 +59,16 @@ func CodeLens(ctx context.Context, snapshot source.Snapshot, uri span.URI) ([]pr
if err != nil {
return nil, err
}
jsonArgs, err := source.EncodeArgs(uri, dep)
if err != nil {
return nil, err
}
codelens = append(codelens, protocol.CodeLens{
Range: rng,
Command: protocol.Command{
Title: fmt.Sprintf("Upgrade dependency to %s", latest),
Command: source.CommandUpgradeDependency,
Arguments: []interface{}{uri, dep},
Arguments: jsonArgs,
},
})
allUpgrades = append(allUpgrades, dep)
@ -77,12 +80,16 @@ func CodeLens(ctx context.Context, snapshot source.Snapshot, uri span.URI) ([]pr
if err != nil {
return nil, err
}
jsonArgs, err := source.EncodeArgs(uri, append([]string{"-u"}, allUpgrades...))
if err != nil {
return nil, err
}
codelens = append(codelens, protocol.CodeLens{
Range: rng,
Command: protocol.Command{
Title: "Upgrade all dependencies",
Command: source.CommandUpgradeDependency,
Arguments: []interface{}{uri, strings.Join(append([]string{"-u"}, allUpgrades...), " ")},
Arguments: jsonArgs,
},
})
}

View File

@ -149,14 +149,11 @@ func (s *Server) newProgressWriter(ctx context.Context, title, beginMsg, msg str
return mw
}
// messageWriter implements progressWriter
// and only tells the user that "go generate"
// has started through window/showMessage but does not
// report anything afterwards. This is because each
// log shows up as a separate window and therefore
// would be obnoxious to show every incoming line.
// Request cancellation happens synchronously through
// the ShowMessageRequest response.
// messageWriter implements progressWriter and only tells the user that
// a command has started through window/showMessage, but does not report
// anything afterwards. This is because each log shows up as a separate window
// and therefore would be obnoxious to show every incoming line. Request
// cancellation happens synchronously through the ShowMessageRequest response.
type messageWriter struct {
ctx context.Context
cancel func()

View File

@ -4,6 +4,8 @@
// last fetched Tue Jun 09 2020 11:22:02 GMT-0400 (Eastern Daylight Time)
package protocol
import "encoding/json"
// Code generated (see typescript/README.md) DO NOT EDIT.
/**
@ -523,7 +525,7 @@ type Command struct {
* Arguments that the command handler should be
* invoked with.
*/
Arguments []interface{} `json:"arguments,omitempty"`
Arguments []json.RawMessage `json:"arguments,omitempty"`
}
/**
@ -1661,7 +1663,7 @@ type ExecuteCommandParams struct {
/**
* Arguments that the command should be invoked with.
*/
Arguments []interface{} `json:"arguments,omitempty"`
Arguments []json.RawMessage `json:"arguments,omitempty"`
WorkDoneProgressParams
}

View File

@ -11,7 +11,6 @@ import (
"sync"
"golang.org/x/tools/internal/jsonrpc2"
"golang.org/x/tools/internal/lsp/mod"
"golang.org/x/tools/internal/lsp/protocol"
"golang.org/x/tools/internal/lsp/source"
"golang.org/x/tools/internal/span"
@ -93,21 +92,6 @@ type sentDiagnostics struct {
snapshotID uint64
}
func (s *Server) codeLens(ctx context.Context, params *protocol.CodeLensParams) ([]protocol.CodeLens, error) {
snapshot, fh, ok, err := s.beginFileRequest(ctx, params.TextDocument.URI, source.UnknownKind)
if !ok {
return nil, err
}
switch fh.Kind() {
case source.Mod:
return mod.CodeLens(ctx, snapshot, fh.URI())
case source.Go:
return source.CodeLens(ctx, snapshot, fh)
}
// Unsupported file kind for a code action.
return nil, nil
}
func (s *Server) nonstandardRequest(ctx context.Context, method string, params interface{}) (interface{}, error) {
paramMap := params.(map[string]interface{})
if method == "gopls/diagnoseFiles" {

View File

@ -14,6 +14,7 @@ import (
"strings"
"golang.org/x/tools/internal/lsp/protocol"
"golang.org/x/tools/internal/span"
)
type lensFunc func(context.Context, Snapshot, FileHandle) ([]protocol.CodeLens, error)
@ -67,12 +68,16 @@ func runTestCodeLens(ctx context.Context, snapshot Snapshot, fh FileHandle) ([]p
if err != nil {
return nil, err
}
jsonArgs, err := EncodeArgs(fh.URI(), fn.Name.Name)
if err != nil {
return nil, err
}
codeLens = append(codeLens, protocol.CodeLens{
Range: rng,
Command: protocol.Command{
Title: "run test",
Command: CommandTest,
Arguments: []interface{}{fn.Name.Name, fh.URI()},
Arguments: jsonArgs,
},
})
}
@ -141,14 +146,22 @@ func goGenerateCodeLens(ctx context.Context, snapshot Snapshot, fh FileHandle) (
if err != nil {
return nil, err
}
dir := filepath.Dir(fh.URI().Filename())
dir := span.URIFromPath(filepath.Dir(fh.URI().Filename()))
nonRecursiveArgs, err := EncodeArgs(dir, false)
if err != nil {
return nil, err
}
recursiveArgs, err := EncodeArgs(dir, true)
if err != nil {
return nil, err
}
return []protocol.CodeLens{
{
Range: rng,
Command: protocol.Command{
Title: "run go generate",
Command: CommandGenerate,
Arguments: []interface{}{dir, false},
Arguments: nonRecursiveArgs,
},
},
{
@ -156,7 +169,7 @@ func goGenerateCodeLens(ctx context.Context, snapshot Snapshot, fh FileHandle) (
Command: protocol.Command{
Title: "run go generate ./...",
Command: CommandGenerate,
Arguments: []interface{}{dir, true},
Arguments: recursiveArgs,
},
},
}, nil
@ -186,13 +199,17 @@ func regenerateCgoLens(ctx context.Context, snapshot Snapshot, fh FileHandle) ([
if err != nil {
return nil, err
}
jsonArgs, err := EncodeArgs(fh.URI())
if err != nil {
return nil, err
}
return []protocol.CodeLens{
{
Range: rng,
Command: protocol.Command{
Title: "regenerate cgo definitions",
Command: CommandRegenerateCgo,
Arguments: []interface{}{fh.URI()},
Arguments: jsonArgs,
},
},
}, nil

View File

@ -6,6 +6,7 @@ package source
import (
"context"
"encoding/json"
"fmt"
"go/ast"
"go/printer"
@ -626,3 +627,47 @@ func formatZeroValue(T types.Type, qf types.Qualifier) string {
return types.TypeString(T, qf) + "{}"
}
}
// EncodeArgs encodes the given arguments to json.RawMessages. This function
// is used to construct arguments to a protocol.Command.
//
// Example usage:
//
// jsonArgs, err := EncodeArgs(1, "hello", true, StructuredArg{42, 12.6})
//
func EncodeArgs(args ...interface{}) ([]json.RawMessage, error) {
var out []json.RawMessage
for _, arg := range args {
argJSON, err := json.Marshal(arg)
if err != nil {
return nil, err
}
out = append(out, argJSON)
}
return out, nil
}
// DecodeArgs decodes the given json.RawMessages to the variables provided by
// args. Each element of args should be a pointer.
//
// Example usage:
//
// var (
// num int
// str string
// bul bool
// structured StructuredArg
// )
// err := DecodeArgs(args, &num, &str, &bul, &structured)
//
func DecodeArgs(jsonArgs []json.RawMessage, args ...interface{}) error {
if len(args) != len(jsonArgs) {
return fmt.Errorf("DecodeArgs: expected %d input arguments, got %d JSON arguments", len(args), len(jsonArgs))
}
for i, arg := range args {
if err := json.Unmarshal(jsonArgs[i], arg); err != nil {
return err
}
}
return nil
}