This repository was archived by the owner on Sep 30, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Expand file tree
/
Copy pathsymbol.go
More file actions
293 lines (263 loc) · 8.22 KB
/
Copy pathsymbol.go
File metadata and controls
293 lines (263 loc) · 8.22 KB
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
package symbol
import (
"context"
"regexp/syntax" //nolint:depguard // zoekt requires this pkg
"sync"
"time"
"github.com/RoaringBitmap/roaring"
"github.com/grafana/regexp"
"github.com/sourcegraph/zoekt"
"github.com/sourcegraph/zoekt/query"
"github.com/sourcegraph/sourcegraph/internal/actor"
"github.com/sourcegraph/sourcegraph/internal/api"
"github.com/sourcegraph/sourcegraph/internal/authz"
"github.com/sourcegraph/sourcegraph/internal/search"
"github.com/sourcegraph/sourcegraph/internal/search/result"
"github.com/sourcegraph/sourcegraph/internal/search/zoektquery"
"github.com/sourcegraph/sourcegraph/internal/symbols"
"github.com/sourcegraph/sourcegraph/internal/types"
"github.com/sourcegraph/sourcegraph/lib/errors"
)
const DefaultSymbolLimit = 100
// NOTE: this lives inside a syncx.OnceValue because search.Indexed depends on
// conf.Get, and running conf.Get() at init time can cause a deadlock. So,
// we construct it lazily instead.
var DefaultZoektSymbolsClient = sync.OnceValue(func() *ZoektSymbolsClient {
return &ZoektSymbolsClient{
subRepoPermsChecker: authz.DefaultSubRepoPermsChecker,
zoektStreamer: search.Indexed(),
symbols: symbols.DefaultClient,
}
})
type ZoektSymbolsClient struct {
subRepoPermsChecker authz.SubRepoPermissionChecker
zoektStreamer zoekt.Streamer
symbols *symbols.Client
}
func (s *ZoektSymbolsClient) Compute(ctx context.Context, repoName types.MinimalRepo, commitID api.CommitID, inputRev *string, query *string, first *int32, includePatterns *[]string) (res []*result.SymbolMatch, err error) {
// TODO(keegancsmith) we should be able to use indexedSearchRequest here
// and remove indexedSymbolsBranch.
if branch := indexedSymbolsBranch(ctx, s.zoektStreamer, &repoName, string(commitID)); branch != "" {
results, err := searchZoekt(ctx, s.zoektStreamer, repoName, commitID, inputRev, branch, query, first, includePatterns)
if err != nil {
return nil, errors.Wrap(err, "zoekt symbol search")
}
results, err = filterZoektResults(ctx, s.subRepoPermsChecker, repoName.Name, results)
if err != nil {
return nil, errors.Wrap(err, "checking permissions")
}
return results, nil
}
serverTimeout := 5 * time.Second
clientTimeout := 2 * serverTimeout
ctx, done := context.WithTimeout(ctx, clientTimeout)
defer done()
defer func() {
if ctx.Err() != nil && len(res) == 0 {
err = errors.Newf("The symbols service appears unresponsive, check the logs for errors.")
}
}()
var includePatternsSlice []string
if includePatterns != nil {
includePatternsSlice = *includePatterns
}
searchArgs := search.SymbolsParameters{
CommitID: commitID,
First: limitOrDefault(first) + 1, // add 1 so we can determine PageInfo.hasNextPage
Repo: repoName.Name,
IncludePatterns: includePatternsSlice,
Timeout: serverTimeout,
}
if query != nil {
searchArgs.Query = *query
}
// We ignore LimitHit, which is consistent with how we treat stats coming
// from Zoekt in indexedSymbolsBranch.
symbols, _, err := s.symbols.Search(ctx, searchArgs)
if err != nil {
return nil, err
}
for i := range symbols {
symbols[i].Line += 1 // callers expect 1-indexed lines
}
fileWithPathAndLanguage := func(path, language string) *result.File {
return &result.File{
Path: path,
Repo: repoName,
InputRev: inputRev,
CommitID: commitID,
PreciseLanguage: language,
}
}
matches := make([]*result.SymbolMatch, 0, len(symbols))
for _, symbol := range symbols {
matches = append(matches, &result.SymbolMatch{
Symbol: symbol,
File: fileWithPathAndLanguage(symbol.Path, symbol.Language),
})
}
return matches, err
}
// GetMatchAtLineCharacter retrieves the shortest matching symbol (if exists) defined
// at a specific line number and character offset in the provided file.
func (s *ZoektSymbolsClient) GetMatchAtLineCharacter(ctx context.Context, repo types.MinimalRepo, commitID api.CommitID, filePath string, line int, character int) (*result.SymbolMatch, error) {
// Should be large enough to include all symbols from a single file
first := int32(999999)
emptyString := ""
includePatterns := []string{regexp.QuoteMeta(filePath)}
symbolMatches, err := s.Compute(ctx, repo, commitID, &emptyString, &emptyString, &first, &includePatterns)
if err != nil {
return nil, err
}
var match *result.SymbolMatch
for _, symbolMatch := range symbolMatches {
symbolRange := symbolMatch.Symbol.Range()
isWithinRange := line >= symbolRange.Start.Line && character >= symbolRange.Start.Character && line <= symbolRange.End.Line && character <= symbolRange.End.Character
if isWithinRange && (match == nil || len(symbolMatch.Symbol.Name) < len(match.Symbol.Name)) {
match = symbolMatch
}
}
return match, nil
}
// indexedSymbols checks to see if Zoekt has indexed symbols information for a
// repository at a specific commit. If it has it returns the branch name (for
// use when querying zoekt). Otherwise an empty string is returned.
func indexedSymbolsBranch(ctx context.Context, zs zoekt.Searcher, repo *types.MinimalRepo, commit string) string {
// We use ListAllIndexed since that is cached.
ctx, cancel := context.WithTimeout(ctx, time.Second)
defer cancel()
list, err := search.ListAllIndexed(ctx, zs)
if err != nil {
return ""
}
r, ok := list.ReposMap[uint32(repo.ID)]
if !ok || !r.HasSymbols {
return ""
}
for _, branch := range r.Branches {
if branch.Version == commit {
return branch.Name
}
}
return ""
}
func filterZoektResults(ctx context.Context, checker authz.SubRepoPermissionChecker, repo api.RepoName, results []*result.SymbolMatch) ([]*result.SymbolMatch, error) {
if !authz.SubRepoEnabled(checker) {
return results, nil
}
// Filter out results from files we don't have access to:
act := actor.FromContext(ctx)
filtered := results[:0]
for i, r := range results {
ok, err := authz.FilterActorPath(ctx, checker, act, repo, r.File.Path)
if err != nil {
return nil, errors.Wrap(err, "checking permissions")
}
if ok {
filtered = append(filtered, results[i])
}
}
return filtered, nil
}
func searchZoekt(
ctx context.Context,
z zoekt.Searcher,
repoName types.MinimalRepo,
commitID api.CommitID,
inputRev *string,
branch string,
queryString *string,
first *int32,
includePatterns *[]string,
) (res []*result.SymbolMatch, err error) {
var raw string
if queryString != nil {
raw = *queryString
}
if raw == "" {
raw = ".*"
}
expr, err := syntax.Parse(raw, syntax.ClassNL|syntax.PerlX|syntax.UnicodeGroups)
if err != nil {
return
}
var q query.Q
if expr.Op == syntax.OpLiteral {
q = &query.Substring{
Pattern: string(expr.Rune),
Content: true,
}
} else {
q = &query.Regexp{
Regexp: expr,
Content: true,
}
}
ands := []query.Q{
&query.BranchesRepos{List: []query.BranchRepos{
{Branch: branch, Repos: roaring.BitmapOf(uint32(repoName.ID))},
}},
&query.Symbol{Expr: q},
}
if includePatterns != nil {
for _, p := range *includePatterns {
q, err := zoektquery.FileRe(p, true)
if err != nil {
return nil, err
}
ands = append(ands, q)
}
}
final := query.Simplify(query.NewAnd(ands...))
match := limitOrDefault(first) + 1
resp, err := z.Search(ctx, final, &zoekt.SearchOptions{
MaxWallTime: 3 * time.Second,
ShardMaxMatchCount: match * 25,
TotalMaxMatchCount: match * 25,
MaxDocDisplayCount: match,
ChunkMatches: true,
NumContextLines: 0,
})
if err != nil {
return nil, err
}
for _, file := range resp.Files {
newFile := &result.File{
Repo: repoName,
CommitID: commitID,
InputRev: inputRev,
Path: file.FileName,
PreciseLanguage: file.Language,
}
for _, cm := range file.ChunkMatches {
if cm.FileName || len(cm.SymbolInfo) == 0 {
continue
}
for i, r := range cm.Ranges {
si := cm.SymbolInfo[i]
if si == nil {
continue
}
res = append(res, result.NewSymbolMatch(
newFile,
int(r.Start.LineNumber),
int(r.Start.Column),
si.Sym,
si.Kind,
si.Parent,
si.ParentKind,
file.Language,
"", // unused when column is set
false,
))
}
}
}
return
}
func limitOrDefault(first *int32) int {
if first == nil {
return DefaultSymbolLimit
}
return int(*first)
}