golang.org/x/tools/gopls@v0.15.3/internal/cmd/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 "golang.org/x/tools/gopls/internal/protocol" 13 "golang.org/x/tools/internal/tool" 14 ) 15 16 // rename implements the rename verb for gopls. 17 type rename struct { 18 EditFlags 19 app *Application 20 } 21 22 func (r *rename) Name() string { return "rename" } 23 func (r *rename) Parent() string { return r.app.Name() } 24 func (r *rename) Usage() string { return "[rename-flags] <position> <name>" } 25 func (r *rename) ShortHelp() string { return "rename selected identifier" } 26 func (r *rename) DetailedHelp(f *flag.FlagSet) { 27 fmt.Fprint(f.Output(), ` 28 Example: 29 30 $ # 1-based location (:line:column or :#position) of the thing to change 31 $ gopls rename helper/helper.go:8:6 Foo 32 $ gopls rename helper/helper.go:#53 Foo 33 34 rename-flags: 35 `) 36 printFlagDefaults(f) 37 } 38 39 // Run renames the specified identifier and either; 40 // - if -w is specified, updates the file(s) in place; 41 // - if -d is specified, prints out unified diffs of the changes; or 42 // - otherwise, prints the new versions to stdout. 43 func (r *rename) Run(ctx context.Context, args ...string) error { 44 if len(args) != 2 { 45 return tool.CommandLineErrorf("rename expects 2 arguments (position, new name)") 46 } 47 r.app.editFlags = &r.EditFlags 48 conn, err := r.app.connect(ctx, nil) 49 if err != nil { 50 return err 51 } 52 defer conn.terminate(ctx) 53 54 from := parseSpan(args[0]) 55 file, err := conn.openFile(ctx, from.URI()) 56 if err != nil { 57 return err 58 } 59 loc, err := file.spanLocation(from) 60 if err != nil { 61 return err 62 } 63 p := protocol.RenameParams{ 64 TextDocument: protocol.TextDocumentIdentifier{URI: loc.URI}, 65 Position: loc.Range.Start, 66 NewName: args[1], 67 } 68 edit, err := conn.Rename(ctx, &p) 69 if err != nil { 70 return err 71 } 72 return conn.client.applyWorkspaceEdit(edit) 73 }