Debian Codegraph @

gopls/internal/server/code_lens.go

raw symbols SCIP
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
5 package server
6
7 import (
8 "context"
9 "encoding/json"
10 "fmt"
11 "sort"
12
13 "golang.org/x/tools/gopls/internal/cache"
14 "golang.org/x/tools/gopls/internal/file"
15 "golang.org/x/tools/gopls/internal/golang"
16 "golang.org/x/tools/gopls/internal/label"
17 "golang.org/x/tools/gopls/internal/mod"
18 "golang.org/x/tools/gopls/internal/protocol"
19 "golang.org/x/tools/gopls/internal/settings"
20 "golang.org/x/tools/internal/event"
21 )
22
23 type codeLensMetadata struct {
24 Source string `json:"source"`
25 }
26
27 // CodeLens reports the set of available CodeLenses
28 // (range-associated commands) in the given file.
29 func (s *server) CodeLens(ctx context.Context, params *protocol.CodeLensParams) ([]protocol.CodeLens, error) {
30 ctx, done := event.Start(ctx, "server.CodeLens", label.URI.Of(params.TextDocument.URI))
31 defer done()
32
33 fh, snapshot, release, err := s.session.FileOf(ctx, params.TextDocument.URI)
34 if err != nil {
35 return nil, err
36 }
37 defer release()
38
39 var lensFuncs map[settings.CodeLensSource]cache.CodeLensSourceFunc
40 switch snapshot.FileKind(fh) {
41 case file.Mod:
42 lensFuncs = mod.CodeLensSources()
43 case file.Go:
44 lensFuncs = golang.CodeLensSources()
45 default:
46 // Unsupported file kind for a code lens.
47 return nil, nil
48 }
49 var lenses []protocol.CodeLens
50 for kind, lensFunc := range lensFuncs {
51 if !snapshot.Options().Codelenses[kind] {
52 continue
53 }
54 added, err := lensFunc(ctx, snapshot, fh)
55 // Code lens is called on every keystroke, so we should just operate in
56 // a best-effort mode, ignoring errors.
57 if err != nil {
58 event.Error(ctx, fmt.Sprintf("code lens %s failed", kind), err)
59 continue
60 }
61 lenses = append(lenses, added...)
62 }
63 for i := range lenses {
64 if lenses[i].Command == nil {
65 continue
66 }
67 meta := codeLensMetadata{Source: "codelens"}
68 metaBytes, err := json.Marshal(meta)
69 if err != nil {
70 event.Error(ctx, "failed to marshal codelens metadata", err)
71 continue
72 }
73 lenses[i].Command.Arguments = append(lenses[i].Command.Arguments, json.RawMessage(metaBytes))
74 }
75 sort.Slice(lenses, func(i, j int) bool {
76 a, b := lenses[i], lenses[j]
77 if cmp := protocol.CompareRange(a.Range, b.Range); cmp != 0 {
78 return cmp < 0
79 }
80 return a.Command.Command < b.Command.Command
81 })
82 return lenses, nil
83 }