|
| 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/internal/lsp/protocol" |
| 13 | + "golang.org/x/tools/internal/span" |
| 14 | + "golang.org/x/tools/internal/tool" |
| 15 | +) |
| 16 | + |
| 17 | +// prepareRename implements the prepare_rename verb for gopls. |
| 18 | +type prepareRename struct { |
| 19 | + app *Application |
| 20 | +} |
| 21 | + |
| 22 | +func (r *prepareRename) Name() string { return "prepare_rename" } |
| 23 | +func (r *prepareRename) Usage() string { return "<position>" } |
| 24 | +func (r *prepareRename) ShortHelp() string { return "test validity of a rename operation at location" } |
| 25 | +func (r *prepareRename) DetailedHelp(f *flag.FlagSet) { |
| 26 | + fmt.Fprint(f.Output(), ` |
| 27 | +Example: |
| 28 | +
|
| 29 | + $ # 1-indexed location (:line:column or :#offset) of the target identifier |
| 30 | + $ gopls prepare_rename helper/helper.go:8:6 |
| 31 | + $ gopls prepare_rename helper/helper.go:#53 |
| 32 | +
|
| 33 | + gopls prepare_rename flags are: |
| 34 | +`) |
| 35 | + f.PrintDefaults() |
| 36 | +} |
| 37 | + |
| 38 | +func (r *prepareRename) Run(ctx context.Context, args ...string) error { |
| 39 | + if len(args) != 1 { |
| 40 | + return tool.CommandLineErrorf("prepare_rename expects 1 argument (file)") |
| 41 | + } |
| 42 | + |
| 43 | + conn, err := r.app.connect(ctx) |
| 44 | + if err != nil { |
| 45 | + return err |
| 46 | + } |
| 47 | + defer conn.terminate(ctx) |
| 48 | + |
| 49 | + from := span.Parse(args[0]) |
| 50 | + file := conn.AddFile(ctx, from.URI()) |
| 51 | + if file.err != nil { |
| 52 | + return file.err |
| 53 | + } |
| 54 | + loc, err := file.mapper.Location(from) |
| 55 | + if err != nil { |
| 56 | + return err |
| 57 | + } |
| 58 | + p := protocol.PrepareRenameParams{ |
| 59 | + TextDocumentPositionParams: protocol.TextDocumentPositionParams{ |
| 60 | + TextDocument: protocol.TextDocumentIdentifier{URI: loc.URI}, |
| 61 | + Position: loc.Range.Start, |
| 62 | + }, |
| 63 | + } |
| 64 | + result, err := conn.PrepareRename(ctx, &p) |
| 65 | + if err != nil { |
| 66 | + return fmt.Errorf("prepare_rename failed: %v", err) |
| 67 | + } |
| 68 | + if result == nil { |
| 69 | + return fmt.Errorf("request is not valid at the given position") |
| 70 | + } |
| 71 | + |
| 72 | + resRange, ok := result.(protocol.Range) |
| 73 | + if !ok { |
| 74 | + return fmt.Errorf("prepare_rename failed to convert result to range, got: %T", result) |
| 75 | + } |
| 76 | + |
| 77 | + l := protocol.Location{Range: resRange} |
| 78 | + s, err := file.mapper.Span(l) |
| 79 | + if err != nil { |
| 80 | + return err |
| 81 | + } |
| 82 | + |
| 83 | + fmt.Println(s) |
| 84 | + return nil |
| 85 | +} |
0 commit comments