| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
package cmd |
| 6 |
|
| 7 |
import ( |
| 8 |
"context" |
| 9 |
"flag" |
| 10 |
"fmt" |
| 11 |
|
| 12 |
"golang.org/x/tools/gopls/internal/protocol" |
| 13 |
"golang.org/x/tools/gopls/internal/tool" |
| 14 |
) |
| 15 |
|
| 16 |
|
| 17 |
type imports struct { |
| 18 |
EditFlags |
| 19 |
app *Application |
| 20 |
} |
| 21 |
|
| 22 |
func (t *imports) Name() string { return "imports" } |
| 23 |
func (t *imports) Parent() string { return t.app.Name() } |
| 24 |
func (t *imports) Usage() string { return "[imports-flags] <filename>" } |
| 25 |
func (t *imports) ShortHelp() string { return "updates import statements" } |
| 26 |
func (t *imports) DetailedHelp(f *flag.FlagSet) { |
| 27 |
fmt.Fprintf(f.Output(), ` |
| 28 |
Example: update imports statements in a file: |
| 29 |
|
| 30 |
$ gopls imports -w internal/cmd/check.go |
| 31 |
|
| 32 |
imports-flags: |
| 33 |
`) |
| 34 |
printFlagDefaults(f) |
| 35 |
} |
| 36 |
|
| 37 |
|
| 38 |
|
| 39 |
|
| 40 |
|
| 41 |
func (t *imports) Run(ctx context.Context, args ...string) error { |
| 42 |
if len(args) != 1 { |
| 43 |
return tool.CommandLineErrorf("imports expects 1 argument") |
| 44 |
} |
| 45 |
t.app.editFlags = &t.EditFlags |
| 46 |
cli, _, err := t.app.connect(ctx) |
| 47 |
if err != nil { |
| 48 |
return err |
| 49 |
} |
| 50 |
defer cli.terminate(ctx) |
| 51 |
|
| 52 |
from := parseSpan(args[0]) |
| 53 |
uri := from.URI() |
| 54 |
file, err := cli.openFile(ctx, uri) |
| 55 |
if err != nil { |
| 56 |
return err |
| 57 |
} |
| 58 |
actions, err := cli.server.CodeAction(ctx, &protocol.CodeActionParams{ |
| 59 |
TextDocument: protocol.TextDocumentIdentifier{ |
| 60 |
URI: uri, |
| 61 |
}, |
| 62 |
Context: protocol.CodeActionContext{ |
| 63 |
Only: []protocol.CodeActionKind{protocol.SourceOrganizeImports}, |
| 64 |
}, |
| 65 |
}) |
| 66 |
if err != nil { |
| 67 |
return fmt.Errorf("%v: %v", from, err) |
| 68 |
} |
| 69 |
var edits []protocol.TextEdit |
| 70 |
for _, a := range actions { |
| 71 |
for _, c := range a.Edit.DocumentChanges { |
| 72 |
|
| 73 |
|
| 74 |
if c.TextDocumentEdit != nil && c.TextDocumentEdit.TextDocument.URI == uri { |
| 75 |
edits = append(edits, protocol.AsTextEdits(c.TextDocumentEdit.Edits)...) |
| 76 |
} |
| 77 |
} |
| 78 |
} |
| 79 |
return applyTextEdits(file.mapper, edits, t.app.editFlags) |
| 80 |
} |