Debian Codegraph @

gopls/internal/cmd/links.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 "encoding/json"
10 "flag"
11 "fmt"
12 "os"
13
14 "golang.org/x/tools/gopls/internal/protocol"
15 "golang.org/x/tools/gopls/internal/tool"
16 )
17
18 // links implements the links verb for gopls.
19 type links struct {
20 JSON bool `flag:"json" help:"emit document links in JSON format"`
21
22 app *Application
23 }
24
25 func (l *links) Name() string { return "links" }
26 func (l *links) Parent() string { return l.app.Name() }
27 func (l *links) Usage() string { return "[links-flags] <filename>" }
28 func (l *links) ShortHelp() string { return "list links in a file" }
29 func (l *links) DetailedHelp(f *flag.FlagSet) {
30 fmt.Fprintf(f.Output(), `
31 Example: list links contained within a file:
32
33 $ gopls links internal/cmd/check.go
34
35 links-flags:
36 `)
37 printFlagDefaults(f)
38 }
39
40 // Run finds all the links within a document
41 // - if -json is specified, outputs location range and uri
42 // - otherwise, prints the a list of unique links
43 func (l *links) Run(ctx context.Context, args ...string) error {
44 if len(args) != 1 {
45 return tool.CommandLineErrorf("links expects 1 argument")
46 }
47 cli, _, err := l.app.connect(ctx)
48 if err != nil {
49 return err
50 }
51 defer cli.terminate(ctx)
52
53 from := parseSpan(args[0])
54 uri := from.URI()
55
56 if _, err := cli.openFile(ctx, uri); err != nil {
57 return err
58 }
59 results, err := cli.server.DocumentLink(ctx, &protocol.DocumentLinkParams{
60 TextDocument: protocol.TextDocumentIdentifier{
61 URI: uri,
62 },
63 })
64 if err != nil {
65 return fmt.Errorf("%v: %v", from, err)
66 }
67 if l.JSON {
68 enc := json.NewEncoder(os.Stdout)
69 enc.SetIndent("", "\t")
70 return enc.Encode(results)
71 }
72 for _, v := range results {
73 fmt.Println(*v.Target)
74 }
75 return nil
76 }