1// Copyright 2020 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 "flag" 10 "fmt" 11 12 "golang.org/x/tools/internal/lsp/protocol" 13 "golang.org/x/tools/internal/lsp/source" 14 "golang.org/x/tools/internal/tool" 15) 16 17// workspaceSymbol implements the workspace_symbol verb for gopls. 18type workspaceSymbol struct { 19 Matcher string `flag:"matcher" help:"specifies the type of matcher: fuzzy, caseSensitive, or caseInsensitive.\nThe default is caseInsensitive."` 20 21 app *Application 22} 23 24func (r *workspaceSymbol) Name() string { return "workspace_symbol" } 25func (r *workspaceSymbol) Usage() string { return "<query>" } 26func (r *workspaceSymbol) ShortHelp() string { return "search symbols in workspace" } 27func (r *workspaceSymbol) DetailedHelp(f *flag.FlagSet) { 28 fmt.Fprint(f.Output(), ` 29Example: 30 31 $ gopls workspace_symbol -matcher fuzzy 'wsymbols' 32 33gopls workspace_symbol flags are: 34`) 35 f.PrintDefaults() 36} 37 38func (r *workspaceSymbol) Run(ctx context.Context, args ...string) error { 39 if len(args) != 1 { 40 return tool.CommandLineErrorf("workspace_symbol expects 1 argument") 41 } 42 43 opts := r.app.options 44 r.app.options = func(o *source.Options) { 45 if opts != nil { 46 opts(o) 47 } 48 switch r.Matcher { 49 case "fuzzy": 50 o.SymbolMatcher = source.SymbolFuzzy 51 case "caseSensitive": 52 o.SymbolMatcher = source.SymbolCaseSensitive 53 default: 54 o.SymbolMatcher = source.SymbolCaseInsensitive 55 } 56 } 57 58 conn, err := r.app.connect(ctx) 59 if err != nil { 60 return err 61 } 62 defer conn.terminate(ctx) 63 64 p := protocol.WorkspaceSymbolParams{ 65 Query: args[0], 66 } 67 68 symbols, err := conn.Symbol(ctx, &p) 69 if err != nil { 70 return err 71 } 72 for _, s := range symbols { 73 f := conn.AddFile(ctx, fileURI(s.Location.URI)) 74 span, err := f.mapper.Span(s.Location) 75 if err != nil { 76 return err 77 } 78 fmt.Printf("%s %s %s\n", span, s.Name, s.Kind) 79 } 80 81 return nil 82} 83