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.
13 "golang.org/x/tools/internal/lsp/diff"
14 "golang.org/x/tools/internal/lsp/protocol"
15 "golang.org/x/tools/internal/lsp/source"
16 "golang.org/x/tools/internal/span"
17 "golang.org/x/tools/internal/tool"
18 errors "golang.org/x/xerrors"
21 // imports implements the import verb for gopls.
23 Diff bool `flag:"d" help:"display diffs instead of rewriting files"`
24 Write bool `flag:"w" help:"write result to (source) file instead of stdout"`
29 func (t *imports) Name() string { return "imports" }
30 func (t *imports) Usage() string { return "<filename>" }
31 func (t *imports) ShortHelp() string { return "updates import statements" }
32 func (t *imports) DetailedHelp(f *flag.FlagSet) {
33 fmt.Fprintf(f.Output(), `
34 Example: update imports statements in a file:
36 $ gopls imports -w internal/lsp/cmd/check.go
38 gopls imports flags are:
43 // Run performs diagnostic checks on the file specified and either;
44 // - if -w is specified, updates the file in place;
45 // - if -d is specified, prints out unified diffs of the changes; or
46 // - otherwise, prints the new versions to stdout.
47 func (t *imports) Run(ctx context.Context, args ...string) error {
49 return tool.CommandLineErrorf("imports expects 1 argument")
51 conn, err := t.app.connect(ctx)
55 defer conn.terminate(ctx)
57 from := span.Parse(args[0])
59 file := conn.AddFile(ctx, uri)
63 actions, err := conn.CodeAction(ctx, &protocol.CodeActionParams{
64 TextDocument: protocol.TextDocumentIdentifier{
65 URI: protocol.URIFromSpanURI(uri),
69 return errors.Errorf("%v: %v", from, err)
71 var edits []protocol.TextEdit
72 for _, a := range actions {
73 if a.Title != "Organize Imports" {
76 for _, c := range a.Edit.DocumentChanges {
77 if fileURI(c.TextDocument.URI) == uri {
78 edits = append(edits, c.Edits...)
82 sedits, err := source.FromProtocolEdits(file.mapper, edits)
84 return errors.Errorf("%v: %v", edits, err)
86 newContent := diff.ApplyEdits(string(file.mapper.Content), sedits)
88 filename := file.uri.Filename()
92 ioutil.WriteFile(filename, []byte(newContent), 0644)
95 diffs := diff.ToUnified(filename+".orig", filename, string(file.mapper.Content), sedits)
98 fmt.Print(string(newContent))