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