You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

repo.go 6.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  1. // Copyright 2017 The Gitea Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package indexer
  5. import (
  6. "strings"
  7. "code.gitea.io/gitea/modules/log"
  8. "code.gitea.io/gitea/modules/setting"
  9. "github.com/blevesearch/bleve"
  10. "github.com/blevesearch/bleve/analysis/analyzer/custom"
  11. "github.com/blevesearch/bleve/analysis/token/lowercase"
  12. "github.com/blevesearch/bleve/analysis/token/unique"
  13. "github.com/blevesearch/bleve/analysis/tokenizer/unicode"
  14. "github.com/blevesearch/bleve/search/query"
  15. "github.com/ethantkoenig/rupture"
  16. )
  17. const (
  18. repoIndexerAnalyzer = "repoIndexerAnalyzer"
  19. repoIndexerDocType = "repoIndexerDocType"
  20. repoIndexerLatestVersion = 3
  21. )
  22. // repoIndexer (thread-safe) index for repository contents
  23. var repoIndexer bleve.Index
  24. // RepoIndexerOp type of operation to perform on repo indexer
  25. type RepoIndexerOp int
  26. const (
  27. // RepoIndexerOpUpdate add/update a file's contents
  28. RepoIndexerOpUpdate = iota
  29. // RepoIndexerOpDelete delete a file
  30. RepoIndexerOpDelete
  31. )
  32. // RepoIndexerData data stored in the repo indexer
  33. type RepoIndexerData struct {
  34. RepoID int64
  35. Content string
  36. }
  37. // Type returns the document type, for bleve's mapping.Classifier interface.
  38. func (d *RepoIndexerData) Type() string {
  39. return repoIndexerDocType
  40. }
  41. // RepoIndexerUpdate an update to the repo indexer
  42. type RepoIndexerUpdate struct {
  43. Filepath string
  44. Op RepoIndexerOp
  45. Data *RepoIndexerData
  46. }
  47. // AddToFlushingBatch adds the update to the given flushing batch.
  48. func (update RepoIndexerUpdate) AddToFlushingBatch(batch rupture.FlushingBatch) error {
  49. id := filenameIndexerID(update.Data.RepoID, update.Filepath)
  50. switch update.Op {
  51. case RepoIndexerOpUpdate:
  52. return batch.Index(id, update.Data)
  53. case RepoIndexerOpDelete:
  54. return batch.Delete(id)
  55. default:
  56. log.Error("Unrecognized repo indexer op: %d", update.Op)
  57. }
  58. return nil
  59. }
  60. // InitRepoIndexer initialize repo indexer
  61. func InitRepoIndexer(populateIndexer func() error) {
  62. var err error
  63. repoIndexer, err = openIndexer(setting.Indexer.RepoPath, repoIndexerLatestVersion)
  64. if err != nil {
  65. log.Fatal("InitRepoIndexer: %v", err)
  66. }
  67. if repoIndexer != nil {
  68. return
  69. }
  70. if err = createRepoIndexer(setting.Indexer.RepoPath, repoIndexerLatestVersion); err != nil {
  71. log.Fatal("CreateRepoIndexer: %v", err)
  72. }
  73. if err = populateIndexer(); err != nil {
  74. log.Fatal("PopulateRepoIndex: %v", err)
  75. }
  76. }
  77. // createRepoIndexer create a repo indexer if one does not already exist
  78. func createRepoIndexer(path string, latestVersion int) error {
  79. var err error
  80. docMapping := bleve.NewDocumentMapping()
  81. numericFieldMapping := bleve.NewNumericFieldMapping()
  82. numericFieldMapping.IncludeInAll = false
  83. docMapping.AddFieldMappingsAt("RepoID", numericFieldMapping)
  84. textFieldMapping := bleve.NewTextFieldMapping()
  85. textFieldMapping.IncludeInAll = false
  86. docMapping.AddFieldMappingsAt("Content", textFieldMapping)
  87. mapping := bleve.NewIndexMapping()
  88. if err = addUnicodeNormalizeTokenFilter(mapping); err != nil {
  89. return err
  90. } else if err = mapping.AddCustomAnalyzer(repoIndexerAnalyzer, map[string]interface{}{
  91. "type": custom.Name,
  92. "char_filters": []string{},
  93. "tokenizer": unicode.Name,
  94. "token_filters": []string{unicodeNormalizeName, lowercase.Name, unique.Name},
  95. }); err != nil {
  96. return err
  97. }
  98. mapping.DefaultAnalyzer = repoIndexerAnalyzer
  99. mapping.AddDocumentMapping(repoIndexerDocType, docMapping)
  100. mapping.AddDocumentMapping("_all", bleve.NewDocumentDisabledMapping())
  101. repoIndexer, err = bleve.New(path, mapping)
  102. if err != nil {
  103. return err
  104. }
  105. return rupture.WriteIndexMetadata(path, &rupture.IndexMetadata{
  106. Version: latestVersion,
  107. })
  108. }
  109. func filenameIndexerID(repoID int64, filename string) string {
  110. return indexerID(repoID) + "_" + filename
  111. }
  112. func filenameOfIndexerID(indexerID string) string {
  113. index := strings.IndexByte(indexerID, '_')
  114. if index == -1 {
  115. log.Error("Unexpected ID in repo indexer: %s", indexerID)
  116. }
  117. return indexerID[index+1:]
  118. }
  119. // RepoIndexerBatch batch to add updates to
  120. func RepoIndexerBatch() rupture.FlushingBatch {
  121. return rupture.NewFlushingBatch(repoIndexer, maxBatchSize)
  122. }
  123. // DeleteRepoFromIndexer delete all of a repo's files from indexer
  124. func DeleteRepoFromIndexer(repoID int64) error {
  125. query := numericEqualityQuery(repoID, "RepoID")
  126. searchRequest := bleve.NewSearchRequestOptions(query, 2147483647, 0, false)
  127. result, err := repoIndexer.Search(searchRequest)
  128. if err != nil {
  129. return err
  130. }
  131. batch := RepoIndexerBatch()
  132. for _, hit := range result.Hits {
  133. if err = batch.Delete(hit.ID); err != nil {
  134. return err
  135. }
  136. }
  137. return batch.Flush()
  138. }
  139. // RepoSearchResult result of performing a search in a repo
  140. type RepoSearchResult struct {
  141. RepoID int64
  142. StartIndex int
  143. EndIndex int
  144. Filename string
  145. Content string
  146. }
  147. // SearchRepoByKeyword searches for files in the specified repo.
  148. // Returns the matching file-paths
  149. func SearchRepoByKeyword(repoIDs []int64, keyword string, page, pageSize int) (int64, []*RepoSearchResult, error) {
  150. phraseQuery := bleve.NewMatchPhraseQuery(keyword)
  151. phraseQuery.FieldVal = "Content"
  152. phraseQuery.Analyzer = repoIndexerAnalyzer
  153. var indexerQuery query.Query
  154. if len(repoIDs) > 0 {
  155. var repoQueries = make([]query.Query, 0, len(repoIDs))
  156. for _, repoID := range repoIDs {
  157. repoQueries = append(repoQueries, numericEqualityQuery(repoID, "RepoID"))
  158. }
  159. indexerQuery = bleve.NewConjunctionQuery(
  160. bleve.NewDisjunctionQuery(repoQueries...),
  161. phraseQuery,
  162. )
  163. } else {
  164. indexerQuery = phraseQuery
  165. }
  166. from := (page - 1) * pageSize
  167. searchRequest := bleve.NewSearchRequestOptions(indexerQuery, pageSize, from, false)
  168. searchRequest.Fields = []string{"Content", "RepoID"}
  169. searchRequest.IncludeLocations = true
  170. result, err := repoIndexer.Search(searchRequest)
  171. if err != nil {
  172. return 0, nil, err
  173. }
  174. searchResults := make([]*RepoSearchResult, len(result.Hits))
  175. for i, hit := range result.Hits {
  176. var startIndex, endIndex int = -1, -1
  177. for _, locations := range hit.Locations["Content"] {
  178. location := locations[0]
  179. locationStart := int(location.Start)
  180. locationEnd := int(location.End)
  181. if startIndex < 0 || locationStart < startIndex {
  182. startIndex = locationStart
  183. }
  184. if endIndex < 0 || locationEnd > endIndex {
  185. endIndex = locationEnd
  186. }
  187. }
  188. searchResults[i] = &RepoSearchResult{
  189. RepoID: int64(hit.Fields["RepoID"].(float64)),
  190. StartIndex: startIndex,
  191. EndIndex: endIndex,
  192. Filename: filenameOfIndexerID(hit.ID),
  193. Content: hit.Fields["Content"].(string),
  194. }
  195. }
  196. return int64(result.Total), searchResults, nil
  197. }