Debian Codegraph @

gopls/internal/cmd/prepare_rename.go

raw symbols SCIP
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 "errors"
10 "flag"
11 "fmt"
12
13 "golang.org/x/tools/gopls/internal/protocol"
14 "golang.org/x/tools/gopls/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) Parent() string { return r.app.Name() }
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 printFlagDefaults(f)
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 cli, _, err := r.app.connect(ctx)
47 if err != nil {
48 return err
49 }
50 defer cli.terminate(ctx)
51
52 from := parseSpan(args[0])
53 file, err := cli.openFile(ctx, from.URI())
54 if err != nil {
55 return err
56 }
57 loc, err := file.spanLocation(from)
58 if err != nil {
59 return err
60 }
61 p := protocol.PrepareRenameParams{
62 TextDocumentPositionParams: protocol.LocationTextDocumentPositionParams(loc),
63 }
64 result, err := cli.server.PrepareRename(ctx, &p)
65 if err != nil {
66 return fmt.Errorf("prepare_rename failed: %w", err)
67 }
68 if result == nil {
69 return ErrInvalidRenamePosition
70 }
71
72 s, err := file.rangeSpan(result.Range)
73 if err != nil {
74 return err
75 }
76
77 fmt.Println(s)
78 return nil
79 }