1 // Copyright 2020 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
16 "golang.org/x/tools/internal/event"
17 "golang.org/x/tools/internal/lsp/protocol"
18 "golang.org/x/tools/internal/lsp/source"
19 "golang.org/x/tools/internal/span"
20 "golang.org/x/tools/internal/xcontext"
21 errors "golang.org/x/xerrors"
24 func (s *Server) executeCommand(ctx context.Context, params *protocol.ExecuteCommandParams) (interface{}, error) {
25 var command *source.Command
26 for _, c := range source.Commands {
27 if c.ID() == params.Command {
33 return nil, fmt.Errorf("no known command")
36 for _, name := range s.session.Options().SupportedCommands {
37 if command.ID() == name {
43 return nil, fmt.Errorf("%s is not a supported command", command.ID())
45 title := command.Title
49 // Some commands require that all files are saved to disk. If we detect
50 // unsaved files, warn the user instead of running the commands.
52 for _, overlay := range s.session.Overlays() {
59 switch params.Command {
60 case source.CommandTest.ID(), source.CommandGenerate.ID(), source.CommandToggleDetails.ID():
61 // TODO(PJW): for Toggle, not an error if it is being disabled
62 err := errors.New("unsaved files in the view")
63 s.showCommandError(ctx, title, err)
67 // If the command has a suggested fix function available, use it and apply
68 // the edits to the workspace.
69 if command.IsSuggestedFix() {
70 err := s.runSuggestedFixCommand(ctx, command, params.Arguments)
72 s.showCommandError(ctx, title, err)
76 ctx, cancel := context.WithCancel(xcontext.Detach(ctx))
77 // Start progress prior to spinning off a goroutine specifically so that
78 // clients are aware of the work item before the command completes. This
79 // matters for regtests, where having a continuous thread of work is
80 // convenient for assertions.
81 work := s.progress.start(ctx, title, "Running...", params.WorkDoneToken, cancel)
82 if command.Synchronous {
83 return nil, s.runCommand(ctx, work, command, params.Arguments)
87 err := s.runCommand(ctx, work, command, params.Arguments)
89 case errors.Is(err, context.Canceled):
90 work.end(title + ": canceled")
92 event.Error(ctx, fmt.Sprintf("%s: command error", title), err)
93 work.end(title + ": failed")
94 // Show a message when work completes with error, because the progress end
95 // message is typically dismissed immediately by LSP clients.
96 s.showCommandError(ctx, title, err)
98 work.end(command.ID() + ": completed")
104 func (s *Server) runSuggestedFixCommand(ctx context.Context, command *source.Command, args []json.RawMessage) error {
105 var uri protocol.DocumentURI
106 var rng protocol.Range
107 if err := source.UnmarshalArgs(args, &uri, &rng); err != nil {
110 snapshot, fh, ok, release, err := s.beginFileRequest(ctx, uri, source.Go)
115 edits, err := command.SuggestedFix(ctx, snapshot, fh, rng)
119 r, err := s.client.ApplyEdit(ctx, &protocol.ApplyWorkspaceEditParams{
120 Edit: protocol.WorkspaceEdit{
121 DocumentChanges: edits,
128 return errors.New(r.FailureReason)
133 func (s *Server) showCommandError(ctx context.Context, title string, err error) {
134 // Command error messages should not be cancelable.
135 ctx = xcontext.Detach(ctx)
136 if err := s.client.ShowMessage(ctx, &protocol.ShowMessageParams{
137 Type: protocol.Error,
138 Message: fmt.Sprintf("%s failed: %v", title, err),
140 event.Error(ctx, title+": failed to show message", err)
144 func (s *Server) runCommand(ctx context.Context, work *workDone, command *source.Command, args []json.RawMessage) error {
146 case source.CommandTest:
147 var uri protocol.DocumentURI
148 var tests, benchmarks []string
149 if err := source.UnmarshalArgs(args, &uri, &tests, &benchmarks); err != nil {
152 snapshot, _, ok, release, err := s.beginFileRequest(ctx, uri, source.UnknownKind)
157 return s.runTests(ctx, snapshot, uri, work, tests, benchmarks)
158 case source.CommandGenerate:
159 var uri protocol.DocumentURI
161 if err := source.UnmarshalArgs(args, &uri, &recursive); err != nil {
164 snapshot, _, ok, release, err := s.beginFileRequest(ctx, uri, source.UnknownKind)
169 return s.runGoGenerate(ctx, snapshot, uri.SpanURI(), recursive, work)
170 case source.CommandRegenerateCgo:
171 var uri protocol.DocumentURI
172 if err := source.UnmarshalArgs(args, &uri); err != nil {
175 mod := source.FileModification{
177 Action: source.InvalidateMetadata,
179 return s.didModifyFiles(ctx, []source.FileModification{mod}, FromRegenerateCgo)
180 case source.CommandTidy, source.CommandVendor:
181 var uri protocol.DocumentURI
182 if err := source.UnmarshalArgs(args, &uri); err != nil {
185 // The flow for `go mod tidy` and `go mod vendor` is almost identical,
186 // so we combine them into one case for convenience.
188 if command == source.CommandVendor {
191 return s.directGoModCommand(ctx, uri, "mod", []string{a}...)
192 case source.CommandUpgradeDependency:
193 var uri protocol.DocumentURI
194 var goCmdArgs []string
195 if err := source.UnmarshalArgs(args, &uri, &goCmdArgs); err != nil {
198 return s.directGoModCommand(ctx, uri, "get", goCmdArgs...)
199 case source.CommandToggleDetails:
201 if err := source.UnmarshalArgs(args, &fileURI); err != nil {
204 pkgDir := span.URIFromPath(filepath.Dir(fileURI.Filename()))
205 s.gcOptimizationDetailsMu.Lock()
206 if _, ok := s.gcOptimizatonDetails[pkgDir]; ok {
207 delete(s.gcOptimizatonDetails, pkgDir)
209 s.gcOptimizatonDetails[pkgDir] = struct{}{}
211 s.gcOptimizationDetailsMu.Unlock()
212 // need to recompute diagnostics.
213 // so find the snapshot
214 sv, err := s.session.ViewOf(fileURI)
218 snapshot, release := sv.Snapshot(ctx)
220 s.diagnoseSnapshot(snapshot, nil)
221 case source.CommandGenerateGoplsMod:
224 views := s.session.Views()
226 return fmt.Errorf("cannot resolve view: have %d views", len(views))
230 var uri protocol.DocumentURI
231 if err := source.UnmarshalArgs(args, &uri); err != nil {
235 v, err = s.session.ViewOf(uri.SpanURI())
240 snapshot, release := v.Snapshot(ctx)
242 modFile, err := snapshot.BuildWorkspaceModFile(ctx)
244 return errors.Errorf("getting workspace mod file: %w", err)
246 content, err := modFile.Format()
248 return errors.Errorf("formatting mod file: %w", err)
250 filename := filepath.Join(v.Folder().Filename(), "gopls.mod")
251 if err := ioutil.WriteFile(filename, content, 0644); err != nil {
252 return errors.Errorf("writing mod file: %w", err)
255 return fmt.Errorf("unsupported command: %s", command.ID())
260 func (s *Server) directGoModCommand(ctx context.Context, uri protocol.DocumentURI, verb string, args ...string) error {
261 view, err := s.session.ViewOf(uri.SpanURI())
265 wdir := filepath.Dir(uri.SpanURI().Filename())
266 snapshot, release := view.Snapshot(ctx)
268 return snapshot.RunGoCommandDirect(ctx, wdir, verb, args)
271 func (s *Server) runTests(ctx context.Context, snapshot source.Snapshot, uri protocol.DocumentURI, work *workDone, tests, benchmarks []string) error {
272 pkgs, err := snapshot.PackagesForFile(ctx, uri.SpanURI(), source.TypecheckWorkspace)
277 return fmt.Errorf("package could not be found for file: %s", uri.SpanURI().Filename())
279 pkgPath := pkgs[0].PkgPath()
282 buf := &bytes.Buffer{}
283 ew := &eventWriter{ctx: ctx, operation: "test"}
284 out := io.MultiWriter(ew, workDoneWriter{work}, buf)
286 wdir := filepath.Dir(uri.SpanURI().Filename())
288 // Run `go test -run Func` on each test.
290 for _, funcName := range tests {
291 args := []string{pkgPath, "-v", "-count=1", "-run", fmt.Sprintf("^%s$", funcName)}
292 if err := snapshot.RunGoCommandPiped(ctx, wdir, "test", args, out, out); err != nil {
293 if errors.Is(err, context.Canceled) {
300 // Run `go test -run=^$ -bench Func` on each test.
301 var failedBenchmarks int
302 for _, funcName := range benchmarks {
303 args := []string{pkgPath, "-v", "-run=^$", "-bench", fmt.Sprintf("^%s$", funcName)}
304 if err := snapshot.RunGoCommandPiped(ctx, wdir, "test", args, out, out); err != nil {
305 if errors.Is(err, context.Canceled) {
313 if len(tests) > 0 && len(benchmarks) > 0 {
314 title = "tests and benchmarks"
315 } else if len(tests) > 0 {
317 } else if len(benchmarks) > 0 {
320 return errors.New("No functions were provided")
322 message := fmt.Sprintf("all %s passed", title)
323 if failedTests > 0 && failedBenchmarks > 0 {
324 message = fmt.Sprintf("%d / %d tests failed and %d / %d benchmarks failed", failedTests, len(tests), failedBenchmarks, len(benchmarks))
325 } else if failedTests > 0 {
326 message = fmt.Sprintf("%d / %d tests failed", failedTests, len(tests))
327 } else if failedBenchmarks > 0 {
328 message = fmt.Sprintf("%d / %d benchmarks failed", failedBenchmarks, len(benchmarks))
330 messageType := protocol.Info
331 if failedTests > 0 || failedBenchmarks > 0 {
332 messageType = protocol.Error
333 message += "\n" + buf.String()
336 return s.client.ShowMessage(ctx, &protocol.ShowMessageParams{
342 func (s *Server) runGoGenerate(ctx context.Context, snapshot source.Snapshot, dir span.URI, recursive bool, work *workDone) error {
343 ctx, cancel := context.WithCancel(ctx)
346 er := &eventWriter{ctx: ctx, operation: "generate"}
347 args := []string{"-x"}
352 args = append(args, pattern)
354 stderr := io.MultiWriter(er, workDoneWriter{work})
356 if err := snapshot.RunGoCommandPiped(ctx, dir.Filename(), "generate", args, er, stderr); err != nil {