golang.org/x/tools/gopls@v0.15.3/internal/cmd/imports.go (about)

     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/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  	conn, err := t.app.connect(ctx, nil)
    47  	if err != nil {
    48  		return err
    49  	}
    50  	defer conn.terminate(ctx)
    51  
    52  	from := parseSpan(args[0])
    53  	uri := from.URI()
    54  	file, err := conn.openFile(ctx, uri)
    55  	if err != nil {
    56  		return err
    57  	}
    58  	actions, err := conn.CodeAction(ctx, &protocol.CodeActionParams{
    59  		TextDocument: protocol.TextDocumentIdentifier{
    60  			URI: uri,
    61  		},
    62  	})
    63  	if err != nil {
    64  		return fmt.Errorf("%v: %v", from, err)
    65  	}
    66  	var edits []protocol.TextEdit
    67  	for _, a := range actions {
    68  		if a.Title != "Organize Imports" {
    69  			continue
    70  		}
    71  		for _, c := range a.Edit.DocumentChanges {
    72  			if c.TextDocumentEdit != nil {
    73  				if c.TextDocumentEdit.TextDocument.URI == uri {
    74  					edits = append(edits, protocol.AsTextEdits(c.TextDocumentEdit.Edits)...)
    75  				}
    76  			}
    77  		}
    78  	}
    79  	return applyTextEdits(file.mapper, edits, t.app.editFlags)
    80  }