/
command.go
299 lines (281 loc) · 9.13 KB
/
command.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
// 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"
"fmt"
"io"
"path"
"golang.org/x/tools/internal/event"
"golang.org/x/tools/internal/lsp/debug/tag"
"golang.org/x/tools/internal/lsp/protocol"
"golang.org/x/tools/internal/lsp/source"
"golang.org/x/tools/internal/span"
"golang.org/x/tools/internal/xcontext"
errors "golang.org/x/xerrors"
)
func (s *Server) executeCommand(ctx context.Context, params *protocol.ExecuteCommandParams) (interface{}, error) {
var command *source.Command
for _, c := range source.Commands {
if c.Name == params.Command {
command = c
break
}
}
if command == nil {
return nil, fmt.Errorf("no known command")
}
var match bool
for _, name := range s.session.Options().SupportedCommands {
if command.Name == name {
match = true
break
}
}
if !match {
return nil, fmt.Errorf("%s is not a supported command", command.Name)
}
// 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 {
switch params.Command {
case source.CommandTest.Name, source.CommandGenerate.Name, source.CommandToggleDetails.Name:
// TODO(PJW): for Toggle, not an error if it is being disabled
err := fmt.Errorf("cannot run command %s: unsaved files in the view", params.Command)
s.client.ShowMessage(ctx, &protocol.ShowMessageParams{
Type: protocol.Error,
Message: err.Error(),
})
return nil, err
}
}
// If the command has a suggested fix function available, use it and apply
// the edits to the workspace.
if command.IsSuggestedFix() {
var uri protocol.DocumentURI
var rng protocol.Range
if err := source.UnmarshalArgs(params.Arguments, &uri, &rng); err != nil {
return nil, err
}
snapshot, fh, ok, release, err := s.beginFileRequest(ctx, uri, source.Go)
defer release()
if !ok {
return nil, err
}
edits, err := command.SuggestedFix(ctx, snapshot, fh, rng)
if err != nil {
return nil, err
}
r, err := s.client.ApplyEdit(ctx, &protocol.ApplyWorkspaceEditParams{
Edit: protocol.WorkspaceEdit{
DocumentChanges: edits,
},
})
if err != nil {
return nil, err
}
if !r.Applied {
return nil, s.client.ShowMessage(ctx, &protocol.ShowMessageParams{
Type: protocol.Error,
Message: fmt.Sprintf("%s failed: %v", params.Command, r.FailureReason),
})
}
return nil, nil
}
// Default commands that don't have suggested fix functions.
switch command {
case source.CommandTest:
var uri protocol.DocumentURI
var tests, benchmarks []string
if err := source.UnmarshalArgs(params.Arguments, &uri, &tests, &benchmarks); err != nil {
return nil, err
}
snapshot, _, ok, release, err := s.beginFileRequest(ctx, uri, source.UnknownKind)
defer release()
if !ok {
return nil, err
}
go s.runTests(ctx, snapshot, uri, params.WorkDoneToken, tests, benchmarks)
case source.CommandGenerate:
var uri protocol.DocumentURI
var recursive bool
if err := source.UnmarshalArgs(params.Arguments, &uri, &recursive); err != nil {
return nil, err
}
snapshot, _, ok, release, err := s.beginFileRequest(ctx, uri, source.UnknownKind)
defer release()
if !ok {
return nil, err
}
go s.runGoGenerate(xcontext.Detach(ctx), snapshot, uri.SpanURI(), recursive, params.WorkDoneToken)
case source.CommandRegenerateCgo:
var uri protocol.DocumentURI
if err := source.UnmarshalArgs(params.Arguments, &uri); err != nil {
return nil, err
}
mod := source.FileModification{
URI: uri.SpanURI(),
Action: source.InvalidateMetadata,
}
err := s.didModifyFiles(ctx, []source.FileModification{mod}, FromRegenerateCgo)
return nil, err
case source.CommandTidy, source.CommandVendor:
var uri protocol.DocumentURI
if err := source.UnmarshalArgs(params.Arguments, &uri); err != nil {
return nil, err
}
// The flow for `go mod tidy` and `go mod vendor` is almost identical,
// so we combine them into one case for convenience.
a := "tidy"
if command == source.CommandVendor {
a = "vendor"
}
err := s.directGoModCommand(ctx, uri, "mod", []string{a}...)
return nil, err
case source.CommandUpgradeDependency:
var uri protocol.DocumentURI
var goCmdArgs []string
if err := source.UnmarshalArgs(params.Arguments, &uri, &goCmdArgs); err != nil {
return nil, err
}
err := s.directGoModCommand(ctx, uri, "get", goCmdArgs...)
return nil, err
case source.CommandToggleDetails:
var fileURI span.URI
if err := source.UnmarshalArgs(params.Arguments, &fileURI); err != nil {
return nil, err
}
pkgDir := span.URIFromPath(path.Dir(fileURI.Filename()))
s.gcOptimizationDetailsMu.Lock()
if _, ok := s.gcOptimizatonDetails[pkgDir]; ok {
delete(s.gcOptimizatonDetails, pkgDir)
} else {
s.gcOptimizatonDetails[pkgDir] = struct{}{}
}
s.gcOptimizationDetailsMu.Unlock()
event.Log(ctx, fmt.Sprintf("gc_details %s now %v %v", pkgDir, s.gcOptimizatonDetails[pkgDir],
s.gcOptimizatonDetails))
// need to recompute diagnostics.
// so find the snapshot
sv, err := s.session.ViewOf(fileURI)
if err != nil {
return nil, err
}
snapshot, release := sv.Snapshot(ctx)
defer release()
s.diagnoseSnapshot(snapshot)
return nil, nil
default:
return nil, fmt.Errorf("unknown command: %s", params.Command)
}
return nil, nil
}
func (s *Server) directGoModCommand(ctx context.Context, uri protocol.DocumentURI, verb string, args ...string) error {
view, err := s.session.ViewOf(uri.SpanURI())
if err != nil {
return err
}
snapshot, release := view.Snapshot(ctx)
defer release()
return snapshot.RunGoCommandDirect(ctx, verb, args)
}
func (s *Server) runTests(ctx context.Context, snapshot source.Snapshot, uri protocol.DocumentURI, token protocol.ProgressToken, tests, benchmarks []string) error {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
pkgs, err := snapshot.PackagesForFile(ctx, uri.SpanURI())
if err != nil {
return err
}
if len(pkgs) == 0 {
return fmt.Errorf("package could not be found for file: %s", uri.SpanURI().Filename())
}
pkgPath := pkgs[0].PkgPath()
// create output
ew := &eventWriter{ctx: ctx, operation: "test"}
var title string
if len(tests) > 0 && len(benchmarks) > 0 {
title = "tests and benchmarks"
} else if len(tests) > 0 {
title = "tests"
} else if len(benchmarks) > 0 {
title = "benchmarks"
} else {
return errors.New("No functions were provided")
}
msg := fmt.Sprintf("Running %s...", title)
wc := s.progress.newWriter(ctx, title, msg, msg, token, cancel)
defer wc.Close()
stderr := io.MultiWriter(ew, wc)
// run `go test -run Func` on each test
var failedTests int
for _, funcName := range tests {
args := []string{pkgPath, "-run", fmt.Sprintf("^%s$", funcName)}
if err := snapshot.RunGoCommandPiped(ctx, "test", args, ew, stderr); err != nil {
if errors.Is(err, context.Canceled) {
return err
}
failedTests++
}
}
// run `go test -run=^$ -bench Func` on each test
var failedBenchmarks int
for _, funcName := range tests {
args := []string{pkgPath, "-run=^$", "-bench", fmt.Sprintf("^%s$", funcName)}
if err := snapshot.RunGoCommandPiped(ctx, "test", args, ew, stderr); err != nil {
if errors.Is(err, context.Canceled) {
return err
}
failedBenchmarks++
}
}
messageType := protocol.Info
message := fmt.Sprintf("all %s passed", title)
if failedTests > 0 || failedBenchmarks > 0 {
messageType = protocol.Error
}
if failedTests > 0 && failedBenchmarks > 0 {
message = fmt.Sprintf("%d / %d tests failed and %d / %d benchmarks failed", failedTests, len(tests), failedBenchmarks, len(benchmarks))
} else if failedTests > 0 {
message = fmt.Sprintf("%d / %d tests failed", failedTests, len(tests))
} else if failedBenchmarks > 0 {
message = fmt.Sprintf("%d / %d benchmarks failed", failedBenchmarks, len(benchmarks))
}
return s.client.ShowMessage(ctx, &protocol.ShowMessageParams{
Type: messageType,
Message: message,
})
}
// GenerateWorkDoneTitle is the title used in progress reporting for go
// generate commands. It is exported for testing purposes.
const GenerateWorkDoneTitle = "generate"
func (s *Server) runGoGenerate(ctx context.Context, snapshot source.Snapshot, uri span.URI, recursive bool, token protocol.ProgressToken) error {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
er := &eventWriter{ctx: ctx, operation: "generate"}
wc := s.progress.newWriter(ctx, GenerateWorkDoneTitle, "running go generate", "started go generate, check logs for progress", token, cancel)
defer wc.Close()
args := []string{"-x"}
if recursive {
args = append(args, "./...")
}
stderr := io.MultiWriter(er, wc)
if err := snapshot.RunGoCommandPiped(ctx, "generate", args, er, stderr); err != nil {
if errors.Is(err, context.Canceled) {
return nil
}
event.Error(ctx, "generate: command error", err, tag.Directory.Of(uri.Filename()))
return s.client.ShowMessage(ctx, &protocol.ShowMessageParams{
Type: protocol.Error,
Message: "go generate exited with an error, check gopls logs",
})
}
return nil
}