aboutsummaryrefslogtreecommitdiff
path: root/gopls/internal/lsp/cmd/workspace_symbol.go
blob: 0c7160af39976c0afc0597d1bcc481db350f0408 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
// Copyright 2020 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package cmd

import (
	"context"
	"flag"
	"fmt"

	"golang.org/x/tools/gopls/internal/lsp/protocol"
	"golang.org/x/tools/gopls/internal/lsp/source"
	"golang.org/x/tools/internal/tool"
)

// workspaceSymbol implements the workspace_symbol verb for gopls.
type workspaceSymbol struct {
	Matcher string `flag:"matcher" help:"specifies the type of matcher: fuzzy, caseSensitive, or caseInsensitive.\nThe default is caseInsensitive."`

	app *Application
}

func (r *workspaceSymbol) Name() string      { return "workspace_symbol" }
func (r *workspaceSymbol) Parent() string    { return r.app.Name() }
func (r *workspaceSymbol) Usage() string     { return "[workspace_symbol-flags] <query>" }
func (r *workspaceSymbol) ShortHelp() string { return "search symbols in workspace" }
func (r *workspaceSymbol) DetailedHelp(f *flag.FlagSet) {
	fmt.Fprint(f.Output(), `
Example:

	$ gopls workspace_symbol -matcher fuzzy 'wsymbols'

workspace_symbol-flags:
`)
	printFlagDefaults(f)
}

func (r *workspaceSymbol) Run(ctx context.Context, args ...string) error {
	if len(args) != 1 {
		return tool.CommandLineErrorf("workspace_symbol expects 1 argument")
	}

	opts := r.app.options
	r.app.options = func(o *source.Options) {
		if opts != nil {
			opts(o)
		}
		switch r.Matcher {
		case "fuzzy":
			o.SymbolMatcher = source.SymbolFuzzy
		case "caseSensitive":
			o.SymbolMatcher = source.SymbolCaseSensitive
		case "fastfuzzy":
			o.SymbolMatcher = source.SymbolFastFuzzy
		default:
			o.SymbolMatcher = source.SymbolCaseInsensitive
		}
	}

	conn, err := r.app.connect(ctx)
	if err != nil {
		return err
	}
	defer conn.terminate(ctx)

	p := protocol.WorkspaceSymbolParams{
		Query: args[0],
	}

	symbols, err := conn.Symbol(ctx, &p)
	if err != nil {
		return err
	}
	for _, s := range symbols {
		f := conn.openFile(ctx, fileURI(s.Location.URI))
		span, err := f.mapper.LocationSpan(s.Location)
		if err != nil {
			return err
		}
		fmt.Printf("%s %s %s\n", span, s.Name, s.Kind)
	}

	return nil
}