Debian Codegraph @

gopls/internal/test/integration/wrappers.go

raw symbols SCIP
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.
4
5 package integration
6
7 import (
8 "context"
9 "errors"
10 "os"
11 "path"
12
13 "golang.org/x/tools/gopls/internal/protocol"
14 "golang.org/x/tools/gopls/internal/protocol/command"
15 "golang.org/x/tools/gopls/internal/test/integration/fake"
16 )
17
18 // RemoveWorkspaceFile deletes a file on disk but does nothing in the
19 // editor. It calls t.Fatal on any error.
20 func (e *Env) RemoveWorkspaceFile(name string) {
21 e.TB.Helper()
22 if err := e.Sandbox.Workdir.RemoveFile(e.Ctx, name); err != nil {
23 e.TB.Fatal(err)
24 }
25 }
26
27 // ReadWorkspaceFile reads a file from the workspace, calling t.Fatal on any
28 // error.
29 func (e *Env) ReadWorkspaceFile(name string) string {
30 e.TB.Helper()
31 content, err := e.Sandbox.Workdir.ReadFile(name)
32 if err != nil {
33 e.TB.Fatal(err)
34 }
35 return string(content)
36 }
37
38 // WriteWorkspaceFile writes a file to disk but does nothing in the editor.
39 // It calls t.Fatal on any error.
40 func (e *Env) WriteWorkspaceFile(name, content string) {
41 e.TB.Helper()
42 if err := e.Sandbox.Workdir.WriteFile(e.Ctx, name, content); err != nil {
43 e.TB.Fatal(err)
44 }
45 }
46
47 // WriteWorkspaceFiles deletes a file on disk but does nothing in the
48 // editor. It calls t.Fatal on any error.
49 func (e *Env) WriteWorkspaceFiles(files map[string]string) {
50 e.TB.Helper()
51 if err := e.Sandbox.Workdir.WriteFiles(e.Ctx, files); err != nil {
52 e.TB.Fatal(err)
53 }
54 }
55
56 // ListFiles lists relative paths to files in the given directory.
57 // It calls t.Fatal on any error.
58 func (e *Env) ListFiles(dir string) []string {
59 e.TB.Helper()
60 paths, err := e.Sandbox.Workdir.ListFiles(dir)
61 if err != nil {
62 e.TB.Fatal(err)
63 }
64 return paths
65 }
66
67 // OpenFile opens a file in the editor, calling t.Fatal on any error.
68 func (e *Env) OpenFile(name string) {
69 e.TB.Helper()
70 if err := e.Editor.OpenFile(e.Ctx, name); err != nil {
71 e.TB.Fatal(err)
72 }
73 }
74
75 // CreateBuffer creates a buffer in the editor, calling t.Fatal on any error.
76 func (e *Env) CreateBuffer(name string, content string) {
77 e.TB.Helper()
78 if err := e.Editor.CreateBuffer(e.Ctx, name, content); err != nil {
79 e.TB.Fatal(err)
80 }
81 }
82
83 // BufferText returns the current buffer contents for the file with the given
84 // relative path, calling t.Fatal if the file is not open in a buffer.
85 func (e *Env) BufferText(name string) string {
86 e.TB.Helper()
87 text, ok := e.Editor.BufferText(name)
88 if !ok {
89 e.TB.Fatalf("buffer %q is not open", name)
90 }
91 return text
92 }
93
94 // CloseBuffer closes an editor buffer without saving, calling t.Fatal on any
95 // error.
96 func (e *Env) CloseBuffer(name string) {
97 e.TB.Helper()
98 if err := e.Editor.CloseBuffer(e.Ctx, name); err != nil {
99 e.TB.Fatal(err)
100 }
101 }
102
103 // EditBuffer applies edits to an editor buffer, calling t.Fatal on any error.
104 func (e *Env) EditBuffer(name string, edits ...protocol.TextEdit) {
105 e.TB.Helper()
106 if err := e.Editor.EditBuffer(e.Ctx, name, edits); err != nil {
107 e.TB.Fatal(err)
108 }
109 }
110
111 func (e *Env) SetBufferContent(name string, content string) {
112 e.TB.Helper()
113 if err := e.Editor.SetBufferContent(e.Ctx, name, content); err != nil {
114 e.TB.Fatal(err)
115 }
116 }
117
118 // FileContent returns the file content for name that applies to the current
119 // editing session: it returns the buffer content for an open file, the
120 // on-disk content for an unopened file, or "" for a non-existent file.
121 func (e *Env) FileContent(name string) string {
122 e.TB.Helper()
123 text, ok := e.Editor.BufferText(name)
124 if ok {
125 return text
126 }
127 content, err := e.Sandbox.Workdir.ReadFile(name)
128 if err != nil {
129 if errors.Is(err, os.ErrNotExist) {
130 return ""
131 } else {
132 e.TB.Fatal(err)
133 }
134 }
135 return string(content)
136 }
137
138 // FileContentAt returns the file content at the given location, using the
139 // file's mapper.
140 func (e *Env) FileContentAt(location protocol.Location) string {
141 e.TB.Helper()
142 mapper, err := e.Editor.Mapper(location.URI.Path())
143 if err != nil {
144 e.TB.Fatal(err)
145 }
146 start, end, err := mapper.RangeOffsets(location.Range)
147 if err != nil {
148 e.TB.Fatal(err)
149 }
150 return string(mapper.Content[start:end])
151 }
152
153 // RegexpSearch returns the starting position of the first match for re in the
154 // buffer specified by name, calling t.Fatal on any error. It first searches
155 // for the position in open buffers, then in workspace files.
156 func (e *Env) RegexpSearch(name, re string) protocol.Location {
157 e.TB.Helper()
158 loc, err := e.Editor.RegexpSearch(name, re)
159 if err == fake.ErrUnknownBuffer {
160 loc, err = e.Sandbox.Workdir.RegexpSearch(name, re)
161 }
162 if err != nil {
163 e.TB.Fatalf("RegexpSearch: %v, %v for %q", name, err, re)
164 }
165 return loc
166 }
167
168 // RegexpReplace replaces the first group in the first match of regexpStr with
169 // the replace text, calling t.Fatal on any error.
170 func (e *Env) RegexpReplace(name, regexpStr, replace string) {
171 e.TB.Helper()
172 if err := e.Editor.RegexpReplace(e.Ctx, name, regexpStr, replace); err != nil {
173 e.TB.Fatalf("RegexpReplace: %v", err)
174 }
175 }
176
177 // SaveBuffer saves an editor buffer, calling t.Fatal on any error.
178 func (e *Env) SaveBuffer(name string) {
179 e.TB.Helper()
180 if err := e.Editor.SaveBuffer(e.Ctx, name); err != nil {
181 e.TB.Fatal(err)
182 }
183 }
184
185 func (e *Env) SaveBufferWithoutActions(name string) {
186 e.TB.Helper()
187 if err := e.Editor.SaveBufferWithoutActions(e.Ctx, name); err != nil {
188 e.TB.Fatal(err)
189 }
190 }
191
192 // FirstDefinition returns the first definition of the symbol at the
193 // selected location, calling t.Fatal on error.
194 func (e *Env) FirstDefinition(loc protocol.Location) protocol.Location {
195 e.TB.Helper()
196 locs, err := e.Editor.Definitions(e.Ctx, loc)
197 if err != nil {
198 e.TB.Fatal(err)
199 }
200 if len(locs) == 0 {
201 e.TB.Fatalf("no definitions")
202 }
203 return locs[0]
204 }
205
206 // FirstTypeDefinition returns the first type definition of the symbol
207 // at the selected location, calling t.Fatal on error.
208 func (e *Env) FirstTypeDefinition(loc protocol.Location) protocol.Location {
209 e.TB.Helper()
210 locs, err := e.Editor.TypeDefinitions(e.Ctx, loc)
211 if err != nil {
212 e.TB.Fatal(err)
213 }
214 if len(locs) == 0 {
215 e.TB.Fatalf("no type definitions")
216 }
217 return locs[0]
218 }
219
220 // FormatBuffer formats the editor buffer, calling t.Fatal on any error.
221 func (e *Env) FormatBuffer(name string) {
222 e.TB.Helper()
223 if err := e.Editor.FormatBuffer(e.Ctx, name); err != nil {
224 e.TB.Fatal(err)
225 }
226 }
227
228 // OrganizeImports processes the source.organizeImports codeAction, calling
229 // t.Fatal on any error.
230 func (e *Env) OrganizeImports(name string) {
231 e.TB.Helper()
232 if err := e.Editor.OrganizeImports(e.Ctx, name); err != nil {
233 e.TB.Fatal(err)
234 }
235 }
236
237 // ApplyQuickFixes processes the quickfix codeAction, calling t.Fatal on any error.
238 func (e *Env) ApplyQuickFixes(path string, diagnostics []protocol.Diagnostic) {
239 e.TB.Helper()
240 loc := e.Sandbox.Workdir.EntireFile(path)
241 if err := e.Editor.ApplyQuickFixes(e.Ctx, loc, diagnostics); err != nil {
242 e.TB.Fatal(err)
243 }
244 }
245
246 // ApplyCodeAction applies the given code action, calling t.Fatal on any error.
247 func (e *Env) ApplyCodeAction(action protocol.CodeAction) {
248 e.TB.Helper()
249 if err := e.Editor.ApplyCodeAction(e.Ctx, action); err != nil {
250 e.TB.Fatal(err)
251 }
252 }
253
254 // Diagnostics returns diagnostics for the given file, calling t.Fatal on any
255 // error.
256 func (e *Env) Diagnostics(name string) []protocol.Diagnostic {
257 e.TB.Helper()
258 diags, err := e.Editor.Diagnostics(e.Ctx, name)
259 if err != nil {
260 e.TB.Fatal(err)
261 }
262 return diags
263 }
264
265 // GetQuickFixes returns the available quick fix code actions, calling t.Fatal
266 // on any error.
267 func (e *Env) GetQuickFixes(path string, diagnostics []protocol.Diagnostic) []protocol.CodeAction {
268 e.TB.Helper()
269 loc := e.Sandbox.Workdir.EntireFile(path)
270 actions, err := e.Editor.GetQuickFixes(e.Ctx, loc, diagnostics)
271 if err != nil {
272 e.TB.Fatal(err)
273 }
274 return actions
275 }
276
277 // Hover in the editor, calling t.Fatal on any error.
278 // It may return (nil, zero) even on success.
279 func (e *Env) Hover(loc protocol.Location) (*protocol.MarkupContent, protocol.Location) {
280 e.TB.Helper()
281 c, loc, err := e.Editor.Hover(e.Ctx, loc)
282 if err != nil {
283 e.TB.Fatal(err)
284 }
285 return c, loc
286 }
287
288 func (e *Env) DocumentLink(name string) []protocol.DocumentLink {
289 e.TB.Helper()
290 links, err := e.Editor.DocumentLink(e.Ctx, name)
291 if err != nil {
292 e.TB.Fatal(err)
293 }
294 return links
295 }
296
297 func (e *Env) DocumentHighlight(loc protocol.Location) []protocol.DocumentHighlight {
298 e.TB.Helper()
299 highlights, err := e.Editor.DocumentHighlight(e.Ctx, loc)
300 if err != nil {
301 e.TB.Fatal(err)
302 }
303 return highlights
304 }
305
306 // RunGenerate runs "go generate" in the given dir, calling t.Fatal on any error.
307 // It waits for the generate command to complete and checks for file changes
308 // before returning.
309 func (e *Env) RunGenerate(dir string) {
310 e.TB.Helper()
311 if err := e.Editor.RunGenerate(e.Ctx, dir); err != nil {
312 e.TB.Fatal(err)
313 }
314 e.Await(NoOutstandingWork(IgnoreTelemetryPromptWork))
315 // Ideally the editor.Workspace would handle all synthetic file watching, but
316 // we help it out here as we need to wait for the generate command to
317 // complete before checking the filesystem.
318 e.CheckForFileChanges()
319 }
320
321 // RunGoCommand runs the given command in the sandbox's default working
322 // directory.
323 func (e *Env) RunGoCommand(verb string, args ...string) []byte {
324 e.TB.Helper()
325 out, err := e.Sandbox.RunGoCommand(e.Ctx, "", verb, args, nil, true)
326 if err != nil {
327 e.TB.Fatal(err)
328 }
329 return out
330 }
331
332 // RunGoCommandInDir is like RunGoCommand, but executes in the given
333 // relative directory of the sandbox.
334 func (e *Env) RunGoCommandInDir(dir, verb string, args ...string) {
335 e.TB.Helper()
336 if _, err := e.Sandbox.RunGoCommand(e.Ctx, dir, verb, args, nil, true); err != nil {
337 e.TB.Fatal(err)
338 }
339 }
340
341 // RunGoCommandInDirWithEnv is like RunGoCommand, but executes in the given
342 // relative directory of the sandbox with the given additional environment variables.
343 func (e *Env) RunGoCommandInDirWithEnv(dir string, env []string, verb string, args ...string) {
344 e.TB.Helper()
345 if _, err := e.Sandbox.RunGoCommand(e.Ctx, dir, verb, args, env, true); err != nil {
346 e.TB.Fatal(err)
347 }
348 }
349
350 // GoVersion checks the version of the go command.
351 // It returns the X in Go 1.X.
352 func (e *Env) GoVersion() int {
353 e.TB.Helper()
354 v, err := e.Sandbox.GoVersion(e.Ctx)
355 if err != nil {
356 e.TB.Fatal(err)
357 }
358 return v
359 }
360
361 // DumpGoSum prints the correct go.sum contents for dir in txtar format,
362 // for use in creating integration tests.
363 func (e *Env) DumpGoSum(dir string) {
364 e.TB.Helper()
365
366 if _, err := e.Sandbox.RunGoCommand(e.Ctx, dir, "list", []string{"-mod=mod", "./..."}, nil, true); err != nil {
367 e.TB.Fatal(err)
368 }
369 sumFile := path.Join(dir, "go.sum")
370 e.TB.Log("\n\n-- " + sumFile + " --\n" + e.ReadWorkspaceFile(sumFile))
371 e.TB.Fatal("see contents above")
372 }
373
374 // CheckForFileChanges triggers a manual poll of the workspace for any file
375 // changes since creation, or since last polling. It is a workaround for the
376 // lack of true file watching support in the fake workspace.
377 func (e *Env) CheckForFileChanges() {
378 e.TB.Helper()
379 if err := e.Sandbox.Workdir.CheckForFileChanges(e.Ctx); err != nil {
380 e.TB.Fatal(err)
381 }
382 }
383
384 // CodeLens calls textDocument/codeLens for the given path, calling t.Fatal on
385 // any error.
386 func (e *Env) CodeLens(path string) []protocol.CodeLens {
387 e.TB.Helper()
388 lens, err := e.Editor.CodeLens(e.Ctx, path)
389 if err != nil {
390 e.TB.Fatal(err)
391 }
392 return lens
393 }
394
395 // ExecuteCodeLensCommand executes the command for the code lens matching the
396 // given command name.
397 //
398 // result is a pointer to a variable to be populated by json.Unmarshal.
399 func (e *Env) ExecuteCodeLensCommand(path string, cmd command.Command, result any) {
400 e.TB.Helper()
401 if err := e.Editor.ExecuteCodeLensCommand(e.Ctx, path, cmd, result); err != nil {
402 e.TB.Fatal(err)
403 }
404 }
405
406 // ExecuteCommand executes the requested command in the editor, calling t.Fatal
407 // on any error.
408 //
409 // result is a pointer to a variable to be populated by json.Unmarshal.
410 func (e *Env) ExecuteCommand(params *protocol.ExecuteCommandParams, result any) {
411 e.TB.Helper()
412 if err := e.Editor.ExecuteCommand(e.Ctx, params, result); err != nil {
413 e.TB.Fatal(err)
414 }
415 }
416
417 // Views returns the server's views.
418 func (e *Env) Views() []command.View {
419 var summaries []command.View
420 cmd := command.NewViewsCommand("")
421 e.ExecuteCommand(&protocol.ExecuteCommandParams{
422 Command: cmd.Command,
423 Arguments: cmd.Arguments,
424 }, &summaries)
425 return summaries
426 }
427
428 // StartProfile starts a CPU profile with the given name, using the
429 // gopls.start_profile custom command. It calls t.Fatal on any error.
430 //
431 // The resulting stop function must be called to stop profiling (using the
432 // gopls.stop_profile custom command).
433 func (e *Env) StartProfile() (stop func() string) {
434 // TODO(golang/go#61217): revisit the ergonomics of these command APIs.
435 //
436 // This would be a lot simpler if we generated params constructors.
437 args, err := command.MarshalArgs(command.StartProfileArgs{})
438 if err != nil {
439 e.TB.Fatal(err)
440 }
441 params := &protocol.ExecuteCommandParams{
442 Command: command.StartProfile.String(),
443 Arguments: args,
444 }
445 var result command.StartProfileResult
446 e.ExecuteCommand(params, &result)
447
448 return func() string {
449 stopArgs, err := command.MarshalArgs(command.StopProfileArgs{})
450 if err != nil {
451 e.TB.Fatal(err)
452 }
453 stopParams := &protocol.ExecuteCommandParams{
454 Command: command.StopProfile.String(),
455 Arguments: stopArgs,
456 }
457 var result command.StopProfileResult
458 e.ExecuteCommand(stopParams, &result)
459 return result.File
460 }
461 }
462
463 // InlayHints calls textDocument/inlayHints for the given path, calling t.Fatal on
464 // any error.
465 func (e *Env) InlayHints(path string) []protocol.InlayHint {
466 e.TB.Helper()
467 hints, err := e.Editor.InlayHint(e.Ctx, path)
468 if err != nil {
469 e.TB.Fatal(err)
470 }
471 return hints
472 }
473
474 // Symbol calls workspace/symbol
475 func (e *Env) Symbol(query string) []protocol.SymbolInformation {
476 e.TB.Helper()
477 ans, err := e.Editor.Symbols(e.Ctx, query)
478 if err != nil {
479 e.TB.Fatal(err)
480 }
481 return ans
482 }
483
484 // References wraps Editor.References, calling t.Fatal on any error.
485 func (e *Env) References(loc protocol.Location) []protocol.Location {
486 e.TB.Helper()
487 locations, err := e.Editor.References(e.Ctx, loc)
488 if err != nil {
489 e.TB.Fatal(err)
490 }
491 return locations
492 }
493
494 // Rename wraps Editor.Rename, calling t.Fatal on any error.
495 func (e *Env) Rename(loc protocol.Location, newName string) {
496 e.TB.Helper()
497 if err := e.Editor.Rename(e.Ctx, loc, newName); err != nil {
498 e.TB.Fatal(err)
499 }
500 }
501
502 // Implementations wraps Editor.Implementations, calling t.Fatal on any error.
503 func (e *Env) Implementations(loc protocol.Location) []protocol.Location {
504 e.TB.Helper()
505 locations, err := e.Editor.Implementations(e.Ctx, loc)
506 if err != nil {
507 e.TB.Fatal(err)
508 }
509 return locations
510 }
511
512 // RenameFile wraps Editor.RenameFile, calling t.Fatal on any error.
513 func (e *Env) RenameFile(oldPath, newPath string) {
514 e.TB.Helper()
515 if err := e.Editor.RenameFile(e.Ctx, oldPath, newPath); err != nil {
516 e.TB.Fatal(err)
517 }
518 }
519
520 // SignatureHelp wraps Editor.SignatureHelp, calling t.Fatal on error
521 func (e *Env) SignatureHelp(loc protocol.Location) *protocol.SignatureHelp {
522 e.TB.Helper()
523 sighelp, err := e.Editor.SignatureHelp(e.Ctx, loc)
524 if err != nil {
525 e.TB.Fatal(err)
526 }
527 return sighelp
528 }
529
530 // Completion executes a completion request on the server.
531 func (e *Env) Completion(loc protocol.Location) *protocol.CompletionList {
532 e.TB.Helper()
533 completions, err := e.Editor.Completion(e.Ctx, loc)
534 if err != nil {
535 e.TB.Fatal(err)
536 }
537 return completions
538 }
539
540 func (e *Env) DidCreateFiles(files ...protocol.DocumentURI) {
541 e.TB.Helper()
542 err := e.Editor.DidCreateFiles(e.Ctx, files...)
543 if err != nil {
544 e.TB.Fatal(err)
545 }
546 }
547
548 func (e *Env) SetSuggestionInsertReplaceMode(useReplaceMode bool) {
549 e.TB.Helper()
550 e.Editor.SetSuggestionInsertReplaceMode(e.Ctx, useReplaceMode)
551 }
552
553 // AcceptCompletion accepts a completion for the given item at the given
554 // position.
555 func (e *Env) AcceptCompletion(loc protocol.Location, item protocol.CompletionItem) {
556 e.TB.Helper()
557 if err := e.Editor.AcceptCompletion(e.Ctx, loc, item); err != nil {
558 e.TB.Fatal(err)
559 }
560 }
561
562 // CodeActionForFile calls textDocument/codeAction for the entire
563 // file, and calls t.Fatal if there were errors.
564 func (e *Env) CodeActionForFile(path string, diagnostics []protocol.Diagnostic) []protocol.CodeAction {
565 return e.CodeAction(e.Sandbox.Workdir.EntireFile(path), diagnostics, protocol.CodeActionUnknownTrigger)
566 }
567
568 // CodeAction calls textDocument/codeAction for a selection,
569 // and calls t.Fatal if there were errors.
570 func (e *Env) CodeAction(loc protocol.Location, diagnostics []protocol.Diagnostic, trigger protocol.CodeActionTriggerKind) []protocol.CodeAction {
571 e.TB.Helper()
572 actions, err := e.Editor.CodeAction(e.Ctx, loc, diagnostics, trigger)
573 if err != nil {
574 e.TB.Fatal(err)
575 }
576 return actions
577 }
578
579 // ChangeConfiguration updates the editor config, calling t.Fatal on any error.
580 func (e *Env) ChangeConfiguration(newConfig fake.EditorConfig) {
581 e.TB.Helper()
582 if err := e.Editor.ChangeConfiguration(e.Ctx, newConfig); err != nil {
583 e.TB.Fatal(err)
584 }
585 }
586
587 // ChangeWorkspaceFolders updates the editor workspace folders, calling t.Fatal
588 // on any error.
589 func (e *Env) ChangeWorkspaceFolders(newFolders ...string) {
590 e.TB.Helper()
591 if err := e.Editor.ChangeWorkspaceFolders(e.Ctx, newFolders); err != nil {
592 e.TB.Fatal(err)
593 }
594 }
595
596 // SemanticTokensFull invokes textDocument/semanticTokens/full, calling t.Fatal
597 // on any error.
598 func (e *Env) SemanticTokensFull(path string) []fake.SemanticToken {
599 e.TB.Helper()
600 toks, err := e.Editor.SemanticTokensFull(e.Ctx, path)
601 if err != nil {
602 e.TB.Fatal(err)
603 }
604 return toks
605 }
606
607 // SemanticTokensRange invokes textDocument/semanticTokens/range, calling t.Fatal
608 // on any error.
609 func (e *Env) SemanticTokensRange(loc protocol.Location) []fake.SemanticToken {
610 e.TB.Helper()
611 toks, err := e.Editor.SemanticTokensRange(e.Ctx, loc)
612 if err != nil {
613 e.TB.Fatal(err)
614 }
615 return toks
616 }
617
618 // Close shuts down resources associated with the environment, calling t.Error
619 // on any error.
620 func (e *Env) Close() {
621 ctx := context.WithoutCancel(e.Ctx)
622 if e.MCPSession != nil {
623 if err := e.MCPSession.Close(); err != nil {
624 e.TB.Errorf("closing MCP session: %v", err)
625 }
626 }
627 if e.MCPServer != nil {
628 e.MCPServer.Close()
629 }
630 if err := e.Editor.Close(ctx); err != nil {
631 e.TB.Errorf("closing editor: %v", err)
632 }
633 if err := e.Sandbox.Close(); err != nil {
634 e.TB.Errorf("cleaning up sandbox: %v", err)
635 }
636 }