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