Debian Codegraph @

gopls/internal/cmd/codeaction.go

raw symbols SCIP
1 // Copyright 2024 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 cmd
6
7 import (
8 "context"
9 "flag"
10 "fmt"
11 "regexp"
12 "slices"
13 "strings"
14
15 "golang.org/x/tools/gopls/internal/protocol"
16 "golang.org/x/tools/internal/tool"
17 )
18
19 // codeaction implements the codeaction verb for gopls.
20 type codeaction struct {
21 EditFlags
22 Kind string `flag:"kind" help:"comma-separated list of code action kinds to filter"`
23 Title string `flag:"title" help:"regular expression to match title"`
24 Exec bool `flag:"exec" help:"execute the first matching code action"`
25
26 app *Application
27 }
28
29 func (cmd *codeaction) Name() string { return "codeaction" }
30 func (cmd *codeaction) Parent() string { return cmd.app.Name() }
31 func (cmd *codeaction) Usage() string { return "[codeaction-flags] filename[:line[:col]]" }
32 func (cmd *codeaction) ShortHelp() string { return "list or execute code actions" }
33 func (cmd *codeaction) DetailedHelp(f *flag.FlagSet) {
34 fmt.Fprintf(f.Output(), `
35
36 The codeaction command lists or executes code actions for the
37 specified file or range of a file. Each code action contains
38 either an edit to be directly applied to the file, or a command
39 to be executed by the server, which may have an effect such as:
40 - requesting that the client apply an edit;
41 - changing the state of the server; or
42 - requesting that the client open a document.
43
44 The -kind and and -title flags filter the list of actions.
45
46 The -kind flag specifies a comma-separated list of LSP CodeAction kinds.
47 Only actions of these kinds will be requested from the server.
48 Valid kinds include:
49
50 gopls.doc.features
51 quickfix
52 refactor
53 refactor.extract
54 refactor.extract.constant
55 refactor.extract.function
56 refactor.extract.method
57 refactor.extract.toNewFile
58 refactor.extract.variable
59 refactor.inline
60 refactor.inline.call
61 refactor.rewrite
62 refactor.rewrite.changeQuote
63 refactor.rewrite.fillStruct
64 refactor.rewrite.fillSwitch
65 refactor.rewrite.invertIf
66 refactor.rewrite.joinLines
67 refactor.rewrite.removeUnusedParam
68 refactor.rewrite.splitLines
69 source
70 source.assembly
71 source.doc
72 source.fixAll
73 source.freesymbols
74 source.organizeImports
75 source.test
76
77 Kinds are hierarchical, so "refactor" includes "refactor.inline".
78 (Note: actions of kind "source.test" are not returned unless explicitly
79 requested.)
80
81 The -title flag specifies a regular expression that must match the
82 action's title. (Ideally kinds would be specific enough that this
83 isn't necessary; we really need to subdivide refactor.rewrite; see
84 gopls/internal/settings/codeactionkind.go.)
85
86 The -exec flag causes the first matching code action to be executed.
87 Without the flag, the matching actions are merely listed.
88
89 It is not currently possible to execute more than one action,
90 as that requires a way to detect and resolve conflicts.
91 TODO(adonovan): support it when golang/go#67049 is resolved.
92
93 If executing an action causes the server to send a patch to the
94 client, the usual -write, -preserve, -diff, and -list flags govern how
95 the client deals with the patch.
96
97 Example: execute the first "quick fix" in the specified file and show the diff:
98
99 $ gopls codeaction -kind=quickfix -exec -diff ./gopls/main.go
100
101 codeaction-flags:
102 `)
103 printFlagDefaults(f)
104 }
105
106 func (cmd *codeaction) Run(ctx context.Context, args ...string) error {
107 if len(args) < 1 {
108 return tool.CommandLineErrorf("codeaction expects at least 1 argument")
109 }
110 cmd.app.editFlags = &cmd.EditFlags
111 cli, _, err := cmd.app.connect(ctx)
112 if err != nil {
113 return err
114 }
115 defer cli.terminate(ctx)
116
117 from := parseSpan(args[0])
118 uri := from.URI()
119 file, err := cli.openFile(ctx, uri)
120 if err != nil {
121 return err
122 }
123 rng, err := file.spanRange(from)
124 if err != nil {
125 return err
126 }
127
128 titleRE, err := regexp.Compile(cmd.Title)
129 if err != nil {
130 return err
131 }
132
133 // Get diagnostics, as they may encode various lazy code actions.
134 if err := diagnoseFiles(ctx, cli.server, []protocol.DocumentURI{uri}); err != nil {
135 return err
136 }
137 file.diagnosticsMu.Lock()
138 diagnostics := slices.Clone(file.diagnostics)
139 file.diagnosticsMu.Unlock()
140
141 // Request code actions of the desired kinds.
142 var kinds []protocol.CodeActionKind
143 if cmd.Kind != "" {
144 for kind := range strings.SplitSeq(cmd.Kind, ",") {
145 kinds = append(kinds, protocol.CodeActionKind(kind))
146 }
147 } else {
148 kinds = append(kinds, protocol.Empty) // => all
149 }
150 actions, err := cli.server.CodeAction(ctx, &protocol.CodeActionParams{
151 TextDocument: protocol.TextDocumentIdentifier{URI: uri},
152 Range: rng,
153 Context: protocol.CodeActionContext{
154 Only: kinds,
155 Diagnostics: diagnostics,
156 },
157 })
158 if err != nil {
159 return fmt.Errorf("%v: %v", from, err)
160 }
161
162 // Gather edits from matching code actions.
163 var edits []protocol.TextEdit
164 for _, act := range actions {
165 if act.Disabled != nil {
166 continue
167 }
168 if !titleRE.MatchString(act.Title) {
169 continue
170 }
171
172 // If the provided span has a position (not just offsets),
173 // and the action has diagnostics, the action must have a
174 // diagnostic with the same range as it.
175 if from.HasPosition() && len(act.Diagnostics) > 0 &&
176 !slices.ContainsFunc(act.Diagnostics, func(diag protocol.Diagnostic) bool {
177 return diag.Range.Start == rng.Start
178 }) {
179 continue
180 }
181
182 if cmd.Exec {
183 // -exec: run the first matching code action.
184 if act.Command != nil {
185 // This may cause the server to make
186 // an ApplyEdit downcall to the client.
187 if _, err := executeCommand(ctx, cli.server, act.Command); err != nil {
188 return err
189 }
190 // The specification says that commands should
191 // be executed _after_ edits are applied, not
192 // instead of them, but we don't want to
193 // duplicate edits.
194 } else {
195 // Partially apply CodeAction.Edit, a WorkspaceEdit.
196 // (See also cli.applyWorkspaceEdit(a.Edit)).
197 for _, c := range act.Edit.DocumentChanges {
198 tde := c.TextDocumentEdit
199 if tde != nil && tde.TextDocument.URI == uri {
200 // TODO(adonovan): this logic will butcher an edit that spans files.
201 // It will also ignore create/delete/rename operations.
202 // Fix or document. Need a three-way merge.
203 edits = append(edits, protocol.AsTextEdits(tde.Edits)...)
204 }
205 }
206 return applyTextEdits(file.mapper, edits, cmd.app.editFlags)
207 }
208 return nil
209 } else {
210 // No -exec: list matching code actions.
211 action := "edit"
212 if act.Command != nil {
213 action = "command"
214 }
215 fmt.Printf("%s\t%q [%s]\n",
216 action,
217 act.Title,
218 act.Kind)
219 }
220 }
221
222 if cmd.Exec {
223 return fmt.Errorf("no matching code action at %s", from)
224 }
225 return nil
226 }