fork of https://github.com/sourcegraph/zoekt
0

Configure Feed

Select the types of activity you want to include in your feed.

1// Copyright 2016 Google Inc. All rights reserved. 2// 3// Licensed under the Apache License, Version 2.0 (the "License"); 4// you may not use this file except in compliance with the License. 5// You may obtain a copy of the License at 6// 7// http://www.apache.org/licenses/LICENSE-2.0 8// 9// Unless required by applicable law or agreed to in writing, software 10// distributed under the License is distributed on an "AS IS" BASIS, 11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12// See the License for the specific language governing permissions and 13// limitations under the License. 14 15package zoekt 16 17import ( 18 "context" 19 "fmt" 20 "log" 21 "math" 22 "regexp/syntax" 23 "sort" 24 "strconv" 25 "strings" 26 "time" 27 28 enry_data "github.com/go-enry/go-enry/v2/data" 29 "github.com/grafana/regexp" 30 31 "github.com/sourcegraph/zoekt/query" 32) 33 34const maxUInt16 = 0xffff 35 36// addScore increments the score of the FileMatch by the computed score. If 37// debugScore is true, it also adds a debug string to the FileMatch. If raw is 38// -1, it is ignored. Otherwise, it is added to the debug string. 39func (m *FileMatch) addScore(what string, computed float64, raw float64, debugScore bool) { 40 if computed != 0 && debugScore { 41 var b strings.Builder 42 fmt.Fprintf(&b, "%s", what) 43 if raw != -1 { 44 fmt.Fprintf(&b, "(%s)", strconv.FormatFloat(raw, 'f', -1, 64)) 45 } 46 fmt.Fprintf(&b, ":%.2f, ", computed) 47 m.Debug += b.String() 48 } 49 m.Score += computed 50} 51 52func (m *FileMatch) addKeywordScore(score float64, sumTf float64, L float64, debugScore bool) { 53 if debugScore { 54 m.Debug += fmt.Sprintf("keyword-score:%.2f (sum-tf: %.2f, length-ratio: %.2f)", score, sumTf, L) 55 } 56 m.Score += score 57} 58 59// simplifyMultiRepo takes a query and a predicate. It returns Const(true) if all 60// repository names fulfill the predicate, Const(false) if none of them do, and q 61// otherwise. 62func (d *indexData) simplifyMultiRepo(q query.Q, predicate func(*Repository) bool) query.Q { 63 count := 0 64 alive := len(d.repoMetaData) 65 for i := range d.repoMetaData { 66 if d.repoMetaData[i].Tombstone { 67 alive-- 68 } else if predicate(&d.repoMetaData[i]) { 69 count++ 70 } 71 } 72 if count == alive { 73 return &query.Const{Value: true} 74 } 75 if count > 0 { 76 return q 77 } 78 return &query.Const{Value: false} 79} 80 81func (d *indexData) simplify(in query.Q) query.Q { 82 eval := query.Map(in, func(q query.Q) query.Q { 83 switch r := q.(type) { 84 case *query.Repo: 85 return d.simplifyMultiRepo(q, func(repo *Repository) bool { 86 return r.Regexp.MatchString(repo.Name) 87 }) 88 case *query.RepoRegexp: 89 return d.simplifyMultiRepo(q, func(repo *Repository) bool { 90 return r.Regexp.MatchString(repo.Name) 91 }) 92 case *query.BranchesRepos: 93 for i := range d.repoMetaData { 94 for _, br := range r.List { 95 if br.Repos.Contains(d.repoMetaData[i].ID) { 96 return q 97 } 98 } 99 } 100 return &query.Const{Value: false} 101 case *query.RepoSet: 102 return d.simplifyMultiRepo(q, func(repo *Repository) bool { 103 return r.Set[repo.Name] 104 }) 105 case *query.RepoIDs: 106 return d.simplifyMultiRepo(q, func(repo *Repository) bool { 107 return r.Repos.Contains(repo.ID) 108 }) 109 case *query.Language: 110 _, has := d.metaData.LanguageMap[r.Language] 111 if !has && d.metaData.IndexFeatureVersion < 12 { 112 // For index files that haven't been re-indexed by go-enry, 113 // fall back to file-based matching and continue even if this 114 // repo doesn't have the specific language present. 115 extsForLang := enry_data.ExtensionsByLanguage[r.Language] 116 if extsForLang != nil { 117 extFrags := make([]string, 0, len(extsForLang)) 118 for _, ext := range extsForLang { 119 extFrags = append(extFrags, regexp.QuoteMeta(ext)) 120 } 121 if len(extFrags) > 0 { 122 pattern := fmt.Sprintf("(?i)(%s)$", strings.Join(extFrags, "|")) 123 // inlined copy of query.regexpQuery 124 re, err := syntax.Parse(pattern, syntax.Perl) 125 if err != nil { 126 return &query.Const{Value: false} 127 } 128 if re.Op == syntax.OpLiteral { 129 return &query.Substring{ 130 Pattern: string(re.Rune), 131 FileName: true, 132 } 133 } 134 return &query.Regexp{ 135 Regexp: re, 136 FileName: true, 137 } 138 } 139 } 140 } 141 if !has { 142 return &query.Const{Value: false} 143 } 144 } 145 return q 146 }) 147 return query.Simplify(eval) 148} 149 150func (o *SearchOptions) SetDefaults() { 151 if o.ShardMaxMatchCount == 0 { 152 // We cap the total number of matches, so overly broad 153 // searches don't crash the machine. 154 o.ShardMaxMatchCount = 100000 155 } 156 if o.TotalMaxMatchCount == 0 { 157 o.TotalMaxMatchCount = 10 * o.ShardMaxMatchCount 158 } 159} 160 161func (d *indexData) Search(ctx context.Context, q query.Q, opts *SearchOptions) (sr *SearchResult, err error) { 162 timer := newTimer() 163 164 copyOpts := *opts 165 opts = &copyOpts 166 opts.SetDefaults() 167 168 var res SearchResult 169 if len(d.fileNameIndex) == 0 { 170 return &res, nil 171 } 172 173 select { 174 case <-ctx.Done(): 175 res.Stats.ShardsSkipped++ 176 return &res, nil 177 default: 178 } 179 180 q = d.simplify(q) 181 if c, ok := q.(*query.Const); ok && !c.Value { 182 return &res, nil 183 } 184 185 if opts.EstimateDocCount { 186 res.Stats.ShardFilesConsidered = len(d.fileBranchMasks) 187 return &res, nil 188 } 189 190 q = query.Map(q, query.ExpandFileContent) 191 192 mt, err := d.newMatchTree(q, matchTreeOpt{}) 193 if err != nil { 194 return nil, err 195 } 196 197 // Capture the costs of construction before pruning 198 updateMatchTreeStats(mt, &res.Stats) 199 200 mt, err = pruneMatchTree(mt) 201 if err != nil { 202 return nil, err 203 } 204 res.Stats.MatchTreeConstruction = timer.Elapsed() 205 if mt == nil { 206 res.Stats.ShardsSkippedFilter++ 207 return &res, nil 208 } 209 210 res.Stats.ShardsScanned++ 211 212 cp := &contentProvider{ 213 id: d, 214 stats: &res.Stats, 215 } 216 217 // Track the number of documents found in a repository for 218 // ShardRepoMaxMatchCount 219 var ( 220 lastRepoID uint16 221 repoMatchCount int 222 ) 223 224 docCount := uint32(len(d.fileBranchMasks)) 225 lastDoc := int(-1) 226 227nextFileMatch: 228 for { 229 canceled := false 230 select { 231 case <-ctx.Done(): 232 canceled = true 233 default: 234 } 235 236 nextDoc := mt.nextDoc() 237 if int(nextDoc) <= lastDoc { 238 nextDoc = uint32(lastDoc + 1) 239 } 240 241 for ; nextDoc < docCount; nextDoc++ { 242 repoID := d.repos[nextDoc] 243 repoMetadata := &d.repoMetaData[repoID] 244 245 // Skip tombstoned repositories 246 if repoMetadata.Tombstone { 247 continue 248 } 249 250 // Skip documents that are tombstoned 251 if len(repoMetadata.FileTombstones) > 0 { 252 if _, tombstoned := repoMetadata.FileTombstones[string(d.fileName(nextDoc))]; tombstoned { 253 continue 254 } 255 } 256 257 // Skip documents over ShardRepoMaxMatchCount if specified. 258 if opts.ShardRepoMaxMatchCount > 0 { 259 if repoMatchCount >= opts.ShardRepoMaxMatchCount && repoID == lastRepoID { 260 res.Stats.FilesSkipped++ 261 continue 262 } 263 } 264 265 break 266 } 267 268 if nextDoc >= docCount { 269 break 270 } 271 272 lastDoc = int(nextDoc) 273 274 // We track lastRepoID for ShardRepoMaxMatchCount 275 if lastRepoID != d.repos[nextDoc] { 276 lastRepoID = d.repos[nextDoc] 277 repoMatchCount = 0 278 } 279 280 if canceled || (res.Stats.MatchCount >= opts.ShardMaxMatchCount && opts.ShardMaxMatchCount > 0) { 281 res.Stats.FilesSkipped += int(docCount - nextDoc) 282 break 283 } 284 285 res.Stats.FilesConsidered++ 286 mt.prepare(nextDoc) 287 288 cp.setDocument(nextDoc) 289 290 known := make(map[matchTree]bool) 291 md := d.repoMetaData[d.repos[nextDoc]] 292 293 for cost := costMin; cost <= costMax; cost++ { 294 switch evalMatchTree(cp, cost, known, mt) { 295 case matchesRequiresHigherCost: 296 if cost == costMax { 297 log.Panicf("did not decide. Repo %s, doc %d, known %v", 298 md.Name, nextDoc, known) 299 } 300 case matchesFound: 301 // could short-circuit now, but we want to run higher costs to 302 // potentially find higher ranked matches. 303 case matchesNone: 304 continue nextFileMatch 305 } 306 } 307 308 fileMatch := FileMatch{ 309 Repository: md.Name, 310 RepositoryID: md.ID, 311 RepositoryPriority: md.priority, 312 FileName: string(d.fileName(nextDoc)), 313 Checksum: d.getChecksum(nextDoc), 314 Language: d.languageMap[d.getLanguage(nextDoc)], 315 } 316 317 if s := d.subRepos[nextDoc]; s > 0 { 318 if s >= uint32(len(d.subRepoPaths[d.repos[nextDoc]])) { 319 log.Panicf("corrupt index: subrepo %d beyond %v", s, d.subRepoPaths) 320 } 321 path := d.subRepoPaths[d.repos[nextDoc]][s] 322 fileMatch.SubRepositoryPath = path 323 sr := md.SubRepoMap[path] 324 fileMatch.SubRepositoryName = sr.Name 325 if idx := d.branchIndex(nextDoc); idx >= 0 { 326 fileMatch.Version = sr.Branches[idx].Version 327 } 328 } else { 329 idx := d.branchIndex(nextDoc) 330 if idx >= 0 { 331 fileMatch.Version = md.Branches[idx].Version 332 } 333 } 334 335 // Important invariant for performance: finalCands is sorted by offset and 336 // non-overlapping. gatherMatches respects this invariant and all later 337 // transformations respect this. 338 shouldMergeMatches := !opts.ChunkMatches 339 finalCands := gatherMatches(mt, known, shouldMergeMatches) 340 341 if len(finalCands) == 0 { 342 nm := d.fileName(nextDoc) 343 finalCands = append(finalCands, 344 &candidateMatch{ 345 caseSensitive: false, 346 fileName: true, 347 substrBytes: nm, 348 substrLowered: nm, 349 file: nextDoc, 350 runeOffset: 0, 351 byteOffset: 0, 352 byteMatchSz: uint32(len(nm)), 353 }) 354 } 355 356 if opts.ChunkMatches { 357 fileMatch.ChunkMatches = cp.fillChunkMatches(finalCands, opts.NumContextLines, fileMatch.Language, opts.DebugScore) 358 } else { 359 fileMatch.LineMatches = cp.fillMatches(finalCands, opts.NumContextLines, fileMatch.Language, opts.DebugScore) 360 } 361 362 if opts.UseKeywordScoring { 363 d.scoreFileUsingBM25(&fileMatch, nextDoc, finalCands, opts) 364 } else { 365 // Use the standard, non-experimental scoring method by default 366 d.scoreFile(&fileMatch, nextDoc, mt, known, opts) 367 } 368 369 fileMatch.Branches = d.gatherBranches(nextDoc, mt, known) 370 sortMatchesByScore(fileMatch.LineMatches) 371 sortChunkMatchesByScore(fileMatch.ChunkMatches) 372 if opts.Whole { 373 fileMatch.Content = cp.data(false) 374 } 375 376 matchedChunkRanges := 0 377 for _, cm := range fileMatch.ChunkMatches { 378 matchedChunkRanges += len(cm.Ranges) 379 } 380 381 repoMatchCount += len(fileMatch.LineMatches) 382 repoMatchCount += matchedChunkRanges 383 384 if opts.DebugScore { 385 fileMatch.Debug = fmt.Sprintf("score:%.2f <- %s", fileMatch.Score, fileMatch.Debug) 386 } 387 388 res.Files = append(res.Files, fileMatch) 389 res.Stats.MatchCount += len(fileMatch.LineMatches) 390 res.Stats.MatchCount += matchedChunkRanges 391 res.Stats.FileCount++ 392 } 393 394 // We do not sort Files here, instead we rely on the shards pkg to do file 395 // ranking. If we sorted now, we would break the assumption that results 396 // from the same repo in a shard appear next to each other. 397 398 for _, md := range d.repoMetaData { 399 r := md 400 addRepo(&res, &r) 401 for _, v := range r.SubRepoMap { 402 addRepo(&res, v) 403 } 404 } 405 406 // Update stats based on work done during document search. 407 updateMatchTreeStats(mt, &res.Stats) 408 409 // If document ranking is enabled, then we can rank and truncate the files to save memory. 410 if opts.UseDocumentRanks { 411 res.Files = SortAndTruncateFiles(res.Files, opts) 412 } 413 414 res.Stats.MatchTreeSearch = timer.Elapsed() 415 416 return &res, nil 417} 418 419// scoreFile computes a score for the file match using various scoring signals, like 420// whether there's an exact match on a symbol, the number of query clauses that matched, etc. 421func (d *indexData) scoreFile(fileMatch *FileMatch, doc uint32, mt matchTree, known map[matchTree]bool, opts *SearchOptions) { 422 atomMatchCount := 0 423 visitMatches(mt, known, func(mt matchTree) { 424 atomMatchCount++ 425 }) 426 427 addScore := func(what string, computed float64) { 428 fileMatch.addScore(what, computed, -1, opts.DebugScore) 429 } 430 431 // atom-count boosts files with matches from more than 1 atom. The 432 // maximum boost is scoreFactorAtomMatch. 433 if atomMatchCount > 0 { 434 fileMatch.addScore("atom", (1.0-1.0/float64(atomMatchCount))*scoreFactorAtomMatch, float64(atomMatchCount), opts.DebugScore) 435 } 436 437 maxFileScore := 0.0 438 for i := range fileMatch.LineMatches { 439 if maxFileScore < fileMatch.LineMatches[i].Score { 440 maxFileScore = fileMatch.LineMatches[i].Score 441 } 442 443 // Order by ordering in file. 444 fileMatch.LineMatches[i].Score += scoreLineOrderFactor * (1.0 - (float64(i) / float64(len(fileMatch.LineMatches)))) 445 } 446 447 for i := range fileMatch.ChunkMatches { 448 if maxFileScore < fileMatch.ChunkMatches[i].Score { 449 maxFileScore = fileMatch.ChunkMatches[i].Score 450 } 451 452 // Order by ordering in file. 453 fileMatch.ChunkMatches[i].Score += scoreLineOrderFactor * (1.0 - (float64(i) / float64(len(fileMatch.ChunkMatches)))) 454 } 455 456 // Maintain ordering of input files. This 457 // strictly dominates the in-file ordering of 458 // the matches. 459 addScore("fragment", maxFileScore) 460 461 if opts.UseDocumentRanks && len(d.ranks) > int(doc) { 462 weight := scoreFileRankFactor 463 if opts.DocumentRanksWeight > 0.0 { 464 weight = opts.DocumentRanksWeight 465 } 466 467 ranks := d.ranks[doc] 468 // The ranks slice always contains one entry representing the file rank (unless it's empty since the 469 // file doesn't have a rank). This is left over from when documents could have multiple rank signals, 470 // and we plan to clean this up. 471 if len(ranks) > 0 { 472 // The file rank represents a log (base 2) count. The log ranks should be bounded at 32, but we 473 // cap it just in case to ensure it falls in the range [0, 1]. 474 normalized := math.Min(1.0, ranks[0]/32.0) 475 addScore("file-rank", weight*normalized) 476 } 477 } 478 479 md := d.repoMetaData[d.repos[doc]] 480 addScore("doc-order", scoreFileOrderFactor*(1.0-float64(doc)/float64(len(d.boundaries)))) 481 addScore("repo-rank", scoreRepoRankFactor*float64(md.Rank)/maxUInt16) 482 483 if opts.DebugScore { 484 fileMatch.Debug = strings.TrimSuffix(fileMatch.Debug, ", ") 485 } 486} 487 488// scoreFileUsingBM25 computes a score for the file match using an approximation to BM25, the most common scoring 489// algorithm for keyword search: https://en.wikipedia.org/wiki/Okapi_BM25. It implements all parts of the formula 490// except inverse document frequency (idf), since we don't have access to global term frequency statistics. 491// 492// This scoring strategy ignores all other signals including document ranks. This keeps things simple for now, 493// since BM25 is not normalized and can be tricky to combine with other scoring signals. 494func (d *indexData) scoreFileUsingBM25(fileMatch *FileMatch, doc uint32, cands []*candidateMatch, opts *SearchOptions) { 495 // Treat each candidate match as a term and compute the frequencies. For now, ignore case 496 // sensitivity and treat filenames and symbols the same as content. 497 termFreqs := map[string]int{} 498 for _, cand := range cands { 499 term := string(cand.substrLowered) 500 termFreqs[term]++ 501 } 502 503 // Compute the file length ratio. Usually the calculation would be based on terms, but using 504 // bytes should work fine, as we're just computing a ratio. 505 fileLength := float64(d.boundaries[doc+1] - d.boundaries[doc]) 506 numFiles := len(d.boundaries) 507 averageFileLength := float64(d.boundaries[numFiles-1]) / float64(numFiles) 508 L := fileLength / averageFileLength 509 510 // Use standard parameter defaults (used in Lucene and academic papers) 511 k, b := 1.2, 0.75 512 sumTf := 0.0 // Just for debugging 513 score := 0.0 514 for _, freq := range termFreqs { 515 tf := float64(freq) 516 sumTf += tf 517 score += ((k + 1.0) * tf) / (k*(1.0-b+b*L) + tf) 518 } 519 520 fileMatch.addKeywordScore(score, sumTf, L, opts.DebugScore) 521} 522 523func addRepo(res *SearchResult, repo *Repository) { 524 if res.RepoURLs == nil { 525 res.RepoURLs = map[string]string{} 526 } 527 res.RepoURLs[repo.Name] = repo.FileURLTemplate 528 529 if res.LineFragments == nil { 530 res.LineFragments = map[string]string{} 531 } 532 res.LineFragments[repo.Name] = repo.LineFragmentTemplate 533} 534 535type sortByOffsetSlice []*candidateMatch 536 537func (m sortByOffsetSlice) Len() int { return len(m) } 538func (m sortByOffsetSlice) Swap(i, j int) { m[i], m[j] = m[j], m[i] } 539func (m sortByOffsetSlice) Less(i, j int) bool { 540 if m[i].byteOffset == m[j].byteOffset { // tie break if same offset 541 // Prefer longer candidates if starting at same position 542 return m[i].byteMatchSz > m[j].byteMatchSz 543 } 544 return m[i].byteOffset < m[j].byteOffset 545} 546 547// Gather matches from this document. This never returns a mixture of 548// filename/content matches: if there are content matches, all 549// filename matches are trimmed from the result. The matches are 550// returned in document order and are non-overlapping. 551// 552// If `merge` is set, overlapping and adjacent matches will be merged 553// into a single match. Otherwise, overlapping matches will be removed, 554// but adjacent matches will remain. 555func gatherMatches(mt matchTree, known map[matchTree]bool, merge bool) []*candidateMatch { 556 var cands []*candidateMatch 557 visitMatches(mt, known, func(mt matchTree) { 558 if smt, ok := mt.(*substrMatchTree); ok { 559 cands = append(cands, smt.current...) 560 } 561 if rmt, ok := mt.(*regexpMatchTree); ok { 562 cands = append(cands, rmt.found...) 563 } 564 if rmt, ok := mt.(*wordMatchTree); ok { 565 cands = append(cands, rmt.found...) 566 } 567 if smt, ok := mt.(*symbolRegexpMatchTree); ok { 568 cands = append(cands, smt.found...) 569 } 570 }) 571 572 foundContentMatch := false 573 for _, c := range cands { 574 if !c.fileName { 575 foundContentMatch = true 576 break 577 } 578 } 579 580 res := cands[:0] 581 for _, c := range cands { 582 if !foundContentMatch || !c.fileName { 583 res = append(res, c) 584 } 585 } 586 cands = res 587 588 if merge { 589 // Merge adjacent candidates. This guarantees that the matches 590 // are non-overlapping. 591 sort.Sort((sortByOffsetSlice)(cands)) 592 res = cands[:0] 593 for i, c := range cands { 594 if i == 0 { 595 res = append(res, c) 596 continue 597 } 598 last := res[len(res)-1] 599 lastEnd := last.byteOffset + last.byteMatchSz 600 end := c.byteOffset + c.byteMatchSz 601 if lastEnd >= c.byteOffset { 602 if end > lastEnd { 603 last.byteMatchSz = end - last.byteOffset 604 } 605 continue 606 } 607 608 res = append(res, c) 609 } 610 } else { 611 // Remove overlapping candidates. This guarantees that the matches 612 // are non-overlapping, but also preserves expected match counts. 613 sort.Sort((sortByOffsetSlice)(cands)) 614 res = cands[:0] 615 for i, c := range cands { 616 if i == 0 { 617 res = append(res, c) 618 continue 619 } 620 last := res[len(res)-1] 621 lastEnd := last.byteOffset + last.byteMatchSz 622 if lastEnd > c.byteOffset { 623 continue 624 } 625 626 res = append(res, c) 627 } 628 } 629 630 return res 631} 632 633func (d *indexData) branchIndex(docID uint32) int { 634 mask := d.fileBranchMasks[docID] 635 idx := 0 636 for mask != 0 { 637 if mask&0x1 != 0 { 638 return idx 639 } 640 idx++ 641 mask >>= 1 642 } 643 return -1 644} 645 646// gatherBranches returns a list of branch names taking into account any branch 647// filters in the query. If the query contains a branch filter, it returns all 648// branches containing the docID and matching the branch filter. Otherwise, it 649// returns all branches containing docID. 650func (d *indexData) gatherBranches(docID uint32, mt matchTree, known map[matchTree]bool) []string { 651 var mask uint64 652 visitMatches(mt, known, func(mt matchTree) { 653 bq, ok := mt.(*branchQueryMatchTree) 654 if !ok { 655 return 656 } 657 658 mask = mask | bq.branchMask() 659 }) 660 661 if mask == 0 { 662 mask = d.fileBranchMasks[docID] 663 } 664 665 var branches []string 666 id := uint32(1) 667 branchNames := d.branchNames[d.repos[docID]] 668 for mask != 0 { 669 if mask&0x1 != 0 { 670 branches = append(branches, branchNames[uint(id)]) 671 } 672 id <<= 1 673 mask >>= 1 674 } 675 676 return branches 677} 678 679func (d *indexData) List(ctx context.Context, q query.Q, opts *ListOptions) (rl *RepoList, err error) { 680 var include func(rle *RepoListEntry) bool 681 682 q = d.simplify(q) 683 if c, ok := q.(*query.Const); ok { 684 if !c.Value { 685 return &RepoList{}, nil 686 } 687 include = func(rle *RepoListEntry) bool { 688 return true 689 } 690 } else { 691 sr, err := d.Search(ctx, q, &SearchOptions{ 692 ShardRepoMaxMatchCount: 1, 693 }) 694 if err != nil { 695 return nil, err 696 } 697 698 foundRepos := make(map[string]struct{}, len(sr.Files)) 699 for _, file := range sr.Files { 700 foundRepos[file.Repository] = struct{}{} 701 } 702 703 include = func(rle *RepoListEntry) bool { 704 _, ok := foundRepos[rle.Repository.Name] 705 return ok 706 } 707 } 708 709 var l RepoList 710 711 field, err := opts.GetField() 712 if err != nil { 713 return nil, err 714 } 715 switch field { 716 case RepoListFieldRepos: 717 l.Repos = make([]*RepoListEntry, 0, len(d.repoListEntry)) 718 case RepoListFieldReposMap: 719 l.ReposMap = make(ReposMap, len(d.repoListEntry)) 720 } 721 722 for i := range d.repoListEntry { 723 if d.repoMetaData[i].Tombstone { 724 continue 725 } 726 rle := &d.repoListEntry[i] 727 if !include(rle) { 728 continue 729 } 730 731 l.Stats.Add(&rle.Stats) 732 733 // Backwards compat for when ID is missing 734 if rle.Repository.ID == 0 { 735 l.Repos = append(l.Repos, rle) 736 continue 737 } 738 739 switch field { 740 case RepoListFieldRepos: 741 l.Repos = append(l.Repos, rle) 742 case RepoListFieldReposMap: 743 l.ReposMap[rle.Repository.ID] = MinimalRepoListEntry{ 744 HasSymbols: rle.Repository.HasSymbols, 745 Branches: rle.Repository.Branches, 746 IndexTimeUnix: rle.IndexMetadata.IndexTime.Unix(), 747 } 748 } 749 750 } 751 752 // Only one of these fields is populated and in all cases the size of that 753 // field is the number of Repos in this shard. 754 l.Stats.Repos = len(l.Repos) + len(l.ReposMap) 755 756 return &l, nil 757} 758 759// regexpToMatchTreeRecursive converts a regular expression to a matchTree mt. If 760// mt is equivalent to the input r, isEqual = true and the matchTree can be used 761// in place of the regex r. If singleLine = true, then the matchTree and all 762// its children only match terms on the same line. singleLine is used during 763// recursion to decide whether to return an andLineMatchTree (singleLine = true) 764// or a andMatchTree (singleLine = false). 765func (d *indexData) regexpToMatchTreeRecursive(r *syntax.Regexp, minTextSize int, fileName bool, caseSensitive bool) (mt matchTree, isEqual bool, singleLine bool, err error) { 766 // TODO - we could perhaps transform Begin/EndText in '\n'? 767 // TODO - we could perhaps transform CharClass in (OrQuery ) 768 // if there are just a few runes, and part of a OpConcat? 769 switch r.Op { 770 case syntax.OpLiteral: 771 s := string(r.Rune) 772 if len(s) >= minTextSize { 773 mt, err := d.newSubstringMatchTree(&query.Substring{Pattern: s, FileName: fileName, CaseSensitive: caseSensitive}) 774 return mt, true, !strings.Contains(s, "\n"), err 775 } 776 case syntax.OpCapture: 777 return d.regexpToMatchTreeRecursive(r.Sub[0], minTextSize, fileName, caseSensitive) 778 779 case syntax.OpPlus: 780 return d.regexpToMatchTreeRecursive(r.Sub[0], minTextSize, fileName, caseSensitive) 781 782 case syntax.OpRepeat: 783 if r.Min == 1 { 784 return d.regexpToMatchTreeRecursive(r.Sub[0], minTextSize, fileName, caseSensitive) 785 } else if r.Min > 1 { 786 // (x){2,} can't be expressed precisely by the matchTree 787 mt, _, singleLine, err := d.regexpToMatchTreeRecursive(r.Sub[0], minTextSize, fileName, caseSensitive) 788 return mt, false, singleLine, err 789 } 790 case syntax.OpConcat, syntax.OpAlternate: 791 var qs []matchTree 792 isEq := true 793 singleLine = true 794 for _, sr := range r.Sub { 795 if sq, subIsEq, subSingleLine, err := d.regexpToMatchTreeRecursive(sr, minTextSize, fileName, caseSensitive); sq != nil { 796 if err != nil { 797 return nil, false, false, err 798 } 799 isEq = isEq && subIsEq 800 singleLine = singleLine && subSingleLine 801 qs = append(qs, sq) 802 } 803 } 804 if r.Op == syntax.OpConcat { 805 if len(qs) > 1 { 806 isEq = false 807 } 808 newQs := make([]matchTree, 0, len(qs)) 809 for _, q := range qs { 810 if _, ok := q.(*bruteForceMatchTree); ok { 811 continue 812 } 813 newQs = append(newQs, q) 814 } 815 if len(newQs) == 1 { 816 return newQs[0], isEq, singleLine, nil 817 } 818 if len(newQs) == 0 { 819 return &bruteForceMatchTree{}, isEq, singleLine, nil 820 } 821 if singleLine { 822 return &andLineMatchTree{andMatchTree{children: newQs}}, isEq, singleLine, nil 823 } 824 return &andMatchTree{newQs}, isEq, singleLine, nil 825 } 826 for _, q := range qs { 827 if _, ok := q.(*bruteForceMatchTree); ok { 828 return q, isEq, false, nil 829 } 830 } 831 if len(qs) == 0 { 832 return &noMatchTree{Why: "const"}, isEq, false, nil 833 } 834 return &orMatchTree{qs}, isEq, false, nil 835 case syntax.OpStar: 836 if r.Sub[0].Op == syntax.OpAnyCharNotNL { 837 return &bruteForceMatchTree{}, false, true, nil 838 } 839 } 840 return &bruteForceMatchTree{}, false, false, nil 841} 842 843type timer struct { 844 last time.Time 845} 846 847func newTimer() *timer { 848 return &timer{ 849 last: time.Now(), 850 } 851} 852 853func (t *timer) Elapsed() time.Duration { 854 now := time.Now() 855 d := now.Sub(t.last) 856 t.last = now 857 return d 858}