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.6KB

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