github.com/jd-ly/tools@v0.5.7/internal/lsp/code_lens.go (about) 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 lsp 6 7 import ( 8 "context" 9 "fmt" 10 "sort" 11 12 "github.com/jd-ly/tools/internal/event" 13 "github.com/jd-ly/tools/internal/lsp/mod" 14 "github.com/jd-ly/tools/internal/lsp/protocol" 15 "github.com/jd-ly/tools/internal/lsp/source" 16 ) 17 18 func (s *Server) codeLens(ctx context.Context, params *protocol.CodeLensParams) ([]protocol.CodeLens, error) { 19 snapshot, fh, ok, release, err := s.beginFileRequest(ctx, params.TextDocument.URI, source.UnknownKind) 20 defer release() 21 if !ok { 22 return nil, err 23 } 24 var lensFuncs map[string]source.LensFunc 25 switch fh.Kind() { 26 case source.Mod: 27 lensFuncs = mod.LensFuncs() 28 case source.Go: 29 lensFuncs = source.LensFuncs() 30 default: 31 // Unsupported file kind for a code lens. 32 return nil, nil 33 } 34 var result []protocol.CodeLens 35 for lens, lf := range lensFuncs { 36 if !snapshot.View().Options().Codelenses[lens] { 37 continue 38 } 39 added, err := lf(ctx, snapshot, fh) 40 // Code lens is called on every keystroke, so we should just operate in 41 // a best-effort mode, ignoring errors. 42 if err != nil { 43 event.Error(ctx, fmt.Sprintf("code lens %s failed", lens), err) 44 continue 45 } 46 result = append(result, added...) 47 } 48 sort.Slice(result, func(i, j int) bool { 49 a, b := result[i], result[j] 50 if protocol.CompareRange(a.Range, b.Range) == 0 { 51 return a.Command.Command < b.Command.Command 52 } 53 return protocol.CompareRange(a.Range, b.Range) < 0 54 }) 55 return result, nil 56 }