Debian Codegraph @

gopls/internal/cmd/imports.go

raw symbols SCIP
1 // Copyright 2019 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
12 "golang.org/x/tools/gopls/internal/protocol"
13 "golang.org/x/tools/gopls/internal/tool"
14 )
15
16 // imports implements the import verb for gopls.
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 // Run performs diagnostic checks on the file specified and either;
38 // - if -w is specified, updates the file in place;
39 // - if -d is specified, prints out unified diffs of the changes; or
40 // - otherwise, prints the new versions to stdout.
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 // This code action should affect only the specified file;
73 // it is safe to ignore others.
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 }