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