Debian Codegraph @

gopls/internal/test/marker/codeaction_test.go

raw symbols SCIP
1 // Copyright 2026 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 marker
6
7 import (
8 "bytes"
9 "context"
10 "encoding/json"
11 "errors"
12 "fmt"
13 "path/filepath"
14 "regexp"
15
16 "golang.org/x/tools/gopls/internal/protocol"
17 "golang.org/x/tools/gopls/internal/protocol/command"
18 "golang.org/x/tools/gopls/internal/test/integration"
19 "golang.org/x/tools/internal/expect"
20 )
21
22 func codeActionMarker(mark marker, loc protocol.Location, kind string) {
23 if !exactlyOneNamedArg(mark, "action", "edit", "result", "err") {
24 return
25 }
26
27 if end := namedArgFunc(mark, "end", convertNamedArgLocation, protocol.Location{}); end.URI != "" {
28 if end.URI != loc.URI {
29 mark.errorf("end marker is in a different file (%s)", filepath.Base(loc.URI.Path()))
30 return
31 }
32 loc.Range.End = end.Range.End
33 }
34
35 var (
36 edit = namedArg(mark, "edit", expect.Identifier(""))
37 result = namedArg(mark, "result", expect.Identifier(""))
38 wantAction = namedArg(mark, "action", expect.Identifier(""))
39 wantErr = namedArgFunc(mark, "err", convertStringMatcher, stringMatcher{})
40 )
41
42 var diag *protocol.Diagnostic
43 if re := namedArg(mark, "diag", (*regexp.Regexp)(nil)); re != nil {
44 d, ok := removeDiagnostic(mark, loc, false, re)
45 if !ok {
46 mark.errorf("no diagnostic at %v matches %q", loc, re)
47 return
48 }
49 diag = &d
50 }
51
52 action, err := resolveCodeAction(mark.run.env, loc.URI, loc.Range, protocol.CodeActionKind(kind), diag)
53 if err != nil {
54 if !wantErr.empty() {
55 wantErr.checkErr(mark, err)
56 } else {
57 mark.errorf("resolveCodeAction failed: %v", err)
58 }
59 return
60 }
61
62 // When 'action' is set, we simply compare the action, and don't apply it.
63 if wantAction != "" {
64 g := mark.getGolden(wantAction)
65 if action == nil {
66 mark.errorf("no matching codeAction")
67 return
68 }
69 data, err := json.MarshalIndent(action, "", "\t")
70 if err != nil {
71 mark.errorf("failed to marshal codeaction: %v", err)
72 return
73 }
74 data = bytes.ReplaceAll(data, []byte(mark.run.env.Sandbox.Workdir.RootURI()), []byte("$WORKDIR"))
75 compareGolden(mark, data, g)
76 return
77 }
78
79 changes, err := applyCodeAction(mark, action)
80 if err != nil {
81 if !wantErr.empty() {
82 wantErr.checkErr(mark, err)
83 } else {
84 mark.errorf("codeAction failed: %v", err)
85 }
86 return
87 }
88
89 changed, err := changedFiles(mark.run.env, changes)
90 if err != nil {
91 mark.errorf("changedFiles failed: %v", err)
92 return
93 }
94
95 switch {
96 case edit != "":
97 g := mark.getGolden(edit)
98 checkDiffs(mark, changed, g)
99 case result != "":
100 g := mark.getGolden(result)
101 // Check the file state.
102 checkChangedFiles(mark, changed, g)
103 case !wantErr.empty():
104 wantErr.checkErr(mark, err)
105 default:
106 panic("unreachable")
107 }
108 }
109
110 func exactlyOneNamedArg(mark marker, names ...string) bool {
111 var found []string
112 for _, name := range names {
113 if _, ok := mark.note.NamedArgs[name]; ok {
114 found = append(found, name)
115 }
116 }
117 if len(found) != 1 {
118 mark.errorf("need exactly one of %v to be set, got %v", names, found)
119 return false
120 }
121 return true
122 }
123
124 // not used for @codeaction, but codeactions
125
126 // codeAction executes a textDocument/codeAction request for the specified
127 // location and kind. If diag is non-nil, it is used as the code action
128 // context.
129 //
130 // The resulting map contains resulting file contents after the code action is
131 // applied. Currently, this function does not support code actions that return
132 // edits directly; it only supports code action commands.
133 func codeAction(mark marker, uri protocol.DocumentURI, rng protocol.Range, kind protocol.CodeActionKind, diag *protocol.Diagnostic) (map[string][]byte, error) {
134 action, err := resolveCodeAction(mark.run.env, uri, rng, kind, diag)
135 if err != nil {
136 return nil, err
137 }
138 changes, err := applyCodeAction(mark, action)
139 if err != nil {
140 return nil, err
141 }
142 return changedFiles(mark.run.env, changes)
143 }
144
145 // resolveCodeAction resolves the code action specified by the given location,
146 // kind, and diagnostic.
147 func resolveCodeAction(env *integration.Env, uri protocol.DocumentURI, rng protocol.Range, kind protocol.CodeActionKind, diag *protocol.Diagnostic) (*protocol.CodeAction, error) {
148 // Request all code actions that apply to the diagnostic.
149 // A production client would set Only=[kind],
150 // but we can give a better error if we don't filter.
151 params := &protocol.CodeActionParams{
152 TextDocument: protocol.TextDocumentIdentifier{URI: uri},
153 Range: rng,
154 Context: protocol.CodeActionContext{
155 Only: []protocol.CodeActionKind{protocol.Empty}, // => all
156 // TriggerKind: protocol.CodeActionTriggerKind(1 /*Invoked*/),
157 },
158 }
159 if diag != nil {
160 params.Context.Diagnostics = []protocol.Diagnostic{*diag}
161 }
162
163 actions, err := env.Editor.Server.CodeAction(env.Ctx, params)
164 if err != nil {
165 return nil, err
166 }
167
168 // Find the sole candidate CodeAction of exactly the specified kind
169 // (e.g. refactor.inline.call).
170 var candidates []protocol.CodeAction
171 for _, act := range actions {
172 if act.Kind == kind {
173 candidates = append(candidates, act)
174 }
175 }
176 if len(candidates) != 1 {
177 var msg bytes.Buffer
178 fmt.Fprintf(&msg, "found %d CodeActions of kind %s for this diagnostic, want 1", len(candidates), kind)
179 for _, act := range actions {
180 fmt.Fprintf(&msg, "\n\tfound %q (%s)", act.Title, act.Kind)
181 }
182 return nil, errors.New(msg.String())
183 }
184 action := candidates[0]
185
186 // Resolve code action edits first if the client has resolve support
187 // and the code action has no edits.
188 if action.Edit == nil {
189 editSupport, err := env.Editor.EditResolveSupport()
190 if err != nil {
191 return nil, err
192 }
193 if editSupport {
194 resolved, err := env.Editor.Server.ResolveCodeAction(env.Ctx, &action)
195 if err != nil {
196 return nil, err
197 }
198 action = *resolved
199 }
200 }
201
202 return &action, nil
203 }
204
205 // applyCodeAction applies the given code action, and captures the resulting
206 // document changes. This is not called for forms.
207 func applyCodeAction(mark marker, action *protocol.CodeAction) ([]protocol.DocumentChange, error) {
208 if action.Edit == nil && action.Command == nil {
209 return nil, fmt.Errorf("bad action: the server returned a CodeAction %q with no Edit and no Command", action.Title)
210 }
211
212 // Collect any server-initiated changes created by workspace/applyEdit.
213 //
214 // We set up this handler immediately, not right before executing the code
215 // action command, so we can assert that neither the codeAction request nor
216 // codeAction resolve request cause edits as a side effect (golang/go#71405).
217 var changes []protocol.DocumentChange
218 restore := mark.run.env.Editor.Client().SetApplyEditHandler(func(ctx context.Context, wsedit *protocol.WorkspaceEdit) error {
219 changes = append(changes, wsedit.DocumentChanges...)
220 return nil
221 })
222 defer restore()
223
224 // Apply the codeAction.
225 //
226 // Spec:
227 // "If a code action provides an edit and a command, first the edit is
228 // executed and then the command."
229 // An action may specify an edit and/or a command, to be
230 // applied in that order. But since applyDocumentChanges(env,
231 // action.Edit.DocumentChanges) doesn't compose, for now we
232 // assert that actions return one or the other.
233 if action.Edit != nil {
234 if len(action.Edit.Changes) > 0 {
235 mark.run.env.TB.Errorf("internal error: discarding unexpected CodeAction{Kind=%s, Title=%q}.Edit.Changes", action.Kind, action.Title)
236 }
237 if action.Edit.DocumentChanges != nil {
238 if action.Command != nil {
239 mark.run.env.TB.Errorf("internal error: discarding unexpected CodeAction{Kind=%s, Title=%q}.Command", action.Kind, action.Title)
240 }
241 return action.Edit.DocumentChanges, nil
242 }
243 }
244
245 if action.Command != nil {
246 // This is a typical CodeAction command:
247 //
248 // Title: "Implement error"
249 // Command: gopls.apply_fix
250 // Arguments: [{"Fix":"stub_methods","URI":".../a.go","Range":...}}]
251 //
252 // The client makes an ExecuteCommand RPC to the server,
253 // which dispatches it to the ApplyFix handler.
254 // ApplyFix dispatches to the "stub_methods" fixer (the meat).
255 // The server then makes an ApplyEdit RPC to the client,
256 // whose WorkspaceEditFunc hook temporarily gathers the edits
257 // instead of applying them.
258
259 // resolveCommand simulates how a client (like vscode-go) resolves interactive
260 // commands using a tunneling mechanism.
261 //
262 // Because some clients cannot send custom JSON-RPC methods directly, they tunnel
263 // a "command/resolve" request via the standard "workspace/executeCommand"
264 // method (specifically using the "gopls.lsp" command). This function replicates
265 // that JSON tunneling rather than calling [protocol.Server.ResolveCommand]
266 // directly, ensuring the actual over-the-wire pipeline is tested.
267 resolveCommand := func(unresolved *protocol.ExecuteCommandParams) (resolved *protocol.ExecuteCommandParams, err error) {
268 unresolvedJSON, err := json.Marshal(unresolved)
269 if err != nil {
270 return nil, fmt.Errorf("failed to marshal unresolved command: %v", err)
271 }
272
273 lspArgJSON, err := json.Marshal(command.LSPArgs{
274 Method: "command/resolve",
275 Param: unresolvedJSON,
276 })
277 if err != nil {
278 return nil, fmt.Errorf("failed to marshal LSPArgs wrapper: %v", err)
279 }
280
281 lspCmd := &protocol.ExecuteCommandParams{
282 Command: "gopls.lsp",
283 Arguments: []json.RawMessage{lspArgJSON},
284 }
285
286 rawResponse, err := mark.run.env.Editor.Server.ExecuteCommand(mark.run.env.Ctx, lspCmd)
287 if err != nil {
288 return nil, fmt.Errorf("server.ExecuteCommand failed: %v", err)
289 }
290
291 responseJSON, err := json.Marshal(rawResponse)
292 if err != nil {
293 return nil, fmt.Errorf("failed to marshal server response: %v", err)
294 }
295
296 if err := json.Unmarshal(responseJSON, &resolved); err != nil {
297 return nil, fmt.Errorf("failed to unmarshal resolved command: %v", err)
298 }
299
300 return resolved, nil
301 }
302
303 cmd, err := resolveCommand(&protocol.ExecuteCommandParams{
304 Command: action.Command.Command,
305 Arguments: action.Command.Arguments,
306 })
307 if err != nil {
308 return nil, err
309 }
310
311 // Check if the command interactivity is required.
312 if len(cmd.FormFields) > 0 {
313 // Fill in "formAnswers" field from named arg "answers".
314 if rawArgs, ok := mark.note.NamedArgs["answers"]; ok {
315 args := make(map[string]any)
316 if err := json.Unmarshal([]byte(rawArgs.(string)), &args); err != nil {
317 mark.errorf("fail to unmarshal arguments to map[string]any: %v", err)
318 }
319 for k, v := range args {
320 cmd.FormAnswers = append(cmd.FormAnswers, protocol.FormAnswer{
321 ID: k,
322 Value: v,
323 })
324 }
325 }
326
327 // Re-resolve command with the "formAnswers" field filled.
328 cmd, err = resolveCommand(cmd)
329 if err != nil {
330 return nil, err
331 }
332
333 if len(cmd.FormFields) > 0 {
334 return nil, fmt.Errorf("got %v question after providing answers, expect 0", len(cmd.FormFields))
335 }
336 }
337
338 if _, err := mark.run.env.Editor.Server.ExecuteCommand(mark.run.env.Ctx, cmd); err != nil {
339 return nil, err
340 }
341 return changes, nil // populated as a side effect of ExecuteCommand
342 }
343
344 return nil, nil
345 }