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.

268 lines
7.3 KiB

Allow cross-repository dependencies on issues (#7901) * in progress changes for #7405, added ability to add cross-repo dependencies * removed unused repolink var * fixed query that was breaking ci tests; fixed check in issue dependency add so that the id of the issue and dependency is checked rather than the indexes * reverted removal of string in local files becasue these are done via crowdin, not updated manually * removed 'Select("issue.*")' from getBlockedByDependencies and getBlockingDependencies based on comments in PR review * changed getBlockedByDependencies and getBlockingDependencies to use a more xorm-like query, also updated the sidebar as a result * simplified the getBlockingDependencies and getBlockedByDependencies methods; changed the sidebar to show the dependencies in a different format where you can see the name of the repository * made some changes to the issue view in the dependencies (issue name on top, repo full name on separate line). Change view of issue in the dependency search results (also showing the full repo name on separate line) * replace call to FindUserAccessibleRepoIDs with SearchRepositoryByName. The former was hardcoded to use isPrivate = false on the repo search, but this code needed it to be true. The SearchRepositoryByName method is used more in the code including on the user's dashboard * some more tweaks to the layout of the issues when showing dependencies and in the search box when you add new dependencies * added Name to the RepositoryMeta struct * updated swagger doc * fixed total count for link header on SearchIssues * fixed indentation * fixed aligment of remove icon on dependencies in issue sidebar * removed unnecessary nil check (unnecessary because issue.loadRepo is called prior to this block) * reverting .css change, somehow missed or forgot that less is used * updated less file and generated css; updated sidebar template with styles to line up delete and issue index * added ordering to the blocked by/depends on queries * fixed sorting in issue dependency search and the depends on/blocks views to show issues from the current repo first, then by created date descending; added a "all cross repository dependencies" setting to allow this feature to be turned off, if turned off, the issue dependency search will work the way it did before (restricted to the current repository) * re-applied my swagger changes after merge * fixed split string condition in issue search * changed ALLOW_CROSS_REPOSITORY_DEPENDENCIES description to sound more global than just the issue dependency search; returning 400 in the cross repo issue search api method if not enabled; fixed bug where the issue count did not respect the state parameter * when adding a dependency to an issue, added a check to make sure the issue and dependency are in the same repo if cross repo dependencies is not enabled * updated sortIssuesSession call in PullRequests, another commit moved this method from pull.go to pull_list.go so I had to re-apply my change here * fixed incorrect setting of user id parameter in search repos call
4 years ago
Allow cross-repository dependencies on issues (#7901) * in progress changes for #7405, added ability to add cross-repo dependencies * removed unused repolink var * fixed query that was breaking ci tests; fixed check in issue dependency add so that the id of the issue and dependency is checked rather than the indexes * reverted removal of string in local files becasue these are done via crowdin, not updated manually * removed 'Select("issue.*")' from getBlockedByDependencies and getBlockingDependencies based on comments in PR review * changed getBlockedByDependencies and getBlockingDependencies to use a more xorm-like query, also updated the sidebar as a result * simplified the getBlockingDependencies and getBlockedByDependencies methods; changed the sidebar to show the dependencies in a different format where you can see the name of the repository * made some changes to the issue view in the dependencies (issue name on top, repo full name on separate line). Change view of issue in the dependency search results (also showing the full repo name on separate line) * replace call to FindUserAccessibleRepoIDs with SearchRepositoryByName. The former was hardcoded to use isPrivate = false on the repo search, but this code needed it to be true. The SearchRepositoryByName method is used more in the code including on the user's dashboard * some more tweaks to the layout of the issues when showing dependencies and in the search box when you add new dependencies * added Name to the RepositoryMeta struct * updated swagger doc * fixed total count for link header on SearchIssues * fixed indentation * fixed aligment of remove icon on dependencies in issue sidebar * removed unnecessary nil check (unnecessary because issue.loadRepo is called prior to this block) * reverting .css change, somehow missed or forgot that less is used * updated less file and generated css; updated sidebar template with styles to line up delete and issue index * added ordering to the blocked by/depends on queries * fixed sorting in issue dependency search and the depends on/blocks views to show issues from the current repo first, then by created date descending; added a "all cross repository dependencies" setting to allow this feature to be turned off, if turned off, the issue dependency search will work the way it did before (restricted to the current repository) * re-applied my swagger changes after merge * fixed split string condition in issue search * changed ALLOW_CROSS_REPOSITORY_DEPENDENCIES description to sound more global than just the issue dependency search; returning 400 in the cross repo issue search api method if not enabled; fixed bug where the issue count did not respect the state parameter * when adding a dependency to an issue, added a check to make sure the issue and dependency are in the same repo if cross repo dependencies is not enabled * updated sortIssuesSession call in PullRequests, another commit moved this method from pull.go to pull_list.go so I had to re-apply my change here * fixed incorrect setting of user id parameter in search repos call
4 years ago
Allow cross-repository dependencies on issues (#7901) * in progress changes for #7405, added ability to add cross-repo dependencies * removed unused repolink var * fixed query that was breaking ci tests; fixed check in issue dependency add so that the id of the issue and dependency is checked rather than the indexes * reverted removal of string in local files becasue these are done via crowdin, not updated manually * removed 'Select("issue.*")' from getBlockedByDependencies and getBlockingDependencies based on comments in PR review * changed getBlockedByDependencies and getBlockingDependencies to use a more xorm-like query, also updated the sidebar as a result * simplified the getBlockingDependencies and getBlockedByDependencies methods; changed the sidebar to show the dependencies in a different format where you can see the name of the repository * made some changes to the issue view in the dependencies (issue name on top, repo full name on separate line). Change view of issue in the dependency search results (also showing the full repo name on separate line) * replace call to FindUserAccessibleRepoIDs with SearchRepositoryByName. The former was hardcoded to use isPrivate = false on the repo search, but this code needed it to be true. The SearchRepositoryByName method is used more in the code including on the user's dashboard * some more tweaks to the layout of the issues when showing dependencies and in the search box when you add new dependencies * added Name to the RepositoryMeta struct * updated swagger doc * fixed total count for link header on SearchIssues * fixed indentation * fixed aligment of remove icon on dependencies in issue sidebar * removed unnecessary nil check (unnecessary because issue.loadRepo is called prior to this block) * reverting .css change, somehow missed or forgot that less is used * updated less file and generated css; updated sidebar template with styles to line up delete and issue index * added ordering to the blocked by/depends on queries * fixed sorting in issue dependency search and the depends on/blocks views to show issues from the current repo first, then by created date descending; added a "all cross repository dependencies" setting to allow this feature to be turned off, if turned off, the issue dependency search will work the way it did before (restricted to the current repository) * re-applied my swagger changes after merge * fixed split string condition in issue search * changed ALLOW_CROSS_REPOSITORY_DEPENDENCIES description to sound more global than just the issue dependency search; returning 400 in the cross repo issue search api method if not enabled; fixed bug where the issue count did not respect the state parameter * when adding a dependency to an issue, added a check to make sure the issue and dependency are in the same repo if cross repo dependencies is not enabled * updated sortIssuesSession call in PullRequests, another commit moved this method from pull.go to pull_list.go so I had to re-apply my change here * fixed incorrect setting of user id parameter in search repos call
4 years ago
  1. // Copyright 2018 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 issues
  5. import (
  6. "fmt"
  7. "os"
  8. "strconv"
  9. "code.gitea.io/gitea/modules/log"
  10. "github.com/blevesearch/bleve"
  11. "github.com/blevesearch/bleve/analysis/analyzer/custom"
  12. "github.com/blevesearch/bleve/analysis/token/lowercase"
  13. "github.com/blevesearch/bleve/analysis/token/unicodenorm"
  14. "github.com/blevesearch/bleve/analysis/tokenizer/unicode"
  15. "github.com/blevesearch/bleve/index/upsidedown"
  16. "github.com/blevesearch/bleve/mapping"
  17. "github.com/blevesearch/bleve/search/query"
  18. "github.com/ethantkoenig/rupture"
  19. )
  20. const (
  21. issueIndexerAnalyzer = "issueIndexer"
  22. issueIndexerDocType = "issueIndexerDocType"
  23. issueIndexerLatestVersion = 1
  24. )
  25. // indexerID a bleve-compatible unique identifier for an integer id
  26. func indexerID(id int64) string {
  27. return strconv.FormatInt(id, 36)
  28. }
  29. // idOfIndexerID the integer id associated with an indexer id
  30. func idOfIndexerID(indexerID string) (int64, error) {
  31. id, err := strconv.ParseInt(indexerID, 36, 64)
  32. if err != nil {
  33. return 0, fmt.Errorf("Unexpected indexer ID %s: %v", indexerID, err)
  34. }
  35. return id, nil
  36. }
  37. // numericEqualityQuery a numeric equality query for the given value and field
  38. func numericEqualityQuery(value int64, field string) *query.NumericRangeQuery {
  39. f := float64(value)
  40. tru := true
  41. q := bleve.NewNumericRangeInclusiveQuery(&f, &f, &tru, &tru)
  42. q.SetField(field)
  43. return q
  44. }
  45. func newMatchPhraseQuery(matchPhrase, field, analyzer string) *query.MatchPhraseQuery {
  46. q := bleve.NewMatchPhraseQuery(matchPhrase)
  47. q.FieldVal = field
  48. q.Analyzer = analyzer
  49. return q
  50. }
  51. const unicodeNormalizeName = "unicodeNormalize"
  52. func addUnicodeNormalizeTokenFilter(m *mapping.IndexMappingImpl) error {
  53. return m.AddCustomTokenFilter(unicodeNormalizeName, map[string]interface{}{
  54. "type": unicodenorm.Name,
  55. "form": unicodenorm.NFC,
  56. })
  57. }
  58. const maxBatchSize = 16
  59. // openIndexer open the index at the specified path, checking for metadata
  60. // updates and bleve version updates. If index needs to be created (or
  61. // re-created), returns (nil, nil)
  62. func openIndexer(path string, latestVersion int) (bleve.Index, error) {
  63. _, err := os.Stat(path)
  64. if err != nil && os.IsNotExist(err) {
  65. return nil, nil
  66. } else if err != nil {
  67. return nil, err
  68. }
  69. metadata, err := rupture.ReadIndexMetadata(path)
  70. if err != nil {
  71. return nil, err
  72. }
  73. if metadata.Version < latestVersion {
  74. // the indexer is using a previous version, so we should delete it and
  75. // re-populate
  76. return nil, os.RemoveAll(path)
  77. }
  78. index, err := bleve.Open(path)
  79. if err != nil && err == upsidedown.IncompatibleVersion {
  80. // the indexer was built with a previous version of bleve, so we should
  81. // delete it and re-populate
  82. return nil, os.RemoveAll(path)
  83. } else if err != nil {
  84. return nil, err
  85. }
  86. return index, nil
  87. }
  88. // BleveIndexerData an update to the issue indexer
  89. type BleveIndexerData IndexerData
  90. // Type returns the document type, for bleve's mapping.Classifier interface.
  91. func (i *BleveIndexerData) Type() string {
  92. return issueIndexerDocType
  93. }
  94. // createIssueIndexer create an issue indexer if one does not already exist
  95. func createIssueIndexer(path string, latestVersion int) (bleve.Index, error) {
  96. mapping := bleve.NewIndexMapping()
  97. docMapping := bleve.NewDocumentMapping()
  98. numericFieldMapping := bleve.NewNumericFieldMapping()
  99. numericFieldMapping.IncludeInAll = false
  100. docMapping.AddFieldMappingsAt("RepoID", numericFieldMapping)
  101. textFieldMapping := bleve.NewTextFieldMapping()
  102. textFieldMapping.Store = false
  103. textFieldMapping.IncludeInAll = false
  104. docMapping.AddFieldMappingsAt("Title", textFieldMapping)
  105. docMapping.AddFieldMappingsAt("Content", textFieldMapping)
  106. docMapping.AddFieldMappingsAt("Comments", textFieldMapping)
  107. if err := addUnicodeNormalizeTokenFilter(mapping); err != nil {
  108. return nil, err
  109. } else if err = mapping.AddCustomAnalyzer(issueIndexerAnalyzer, map[string]interface{}{
  110. "type": custom.Name,
  111. "char_filters": []string{},
  112. "tokenizer": unicode.Name,
  113. "token_filters": []string{unicodeNormalizeName, lowercase.Name},
  114. }); err != nil {
  115. return nil, err
  116. }
  117. mapping.DefaultAnalyzer = issueIndexerAnalyzer
  118. mapping.AddDocumentMapping(issueIndexerDocType, docMapping)
  119. mapping.AddDocumentMapping("_all", bleve.NewDocumentDisabledMapping())
  120. index, err := bleve.New(path, mapping)
  121. if err != nil {
  122. return nil, err
  123. }
  124. if err = rupture.WriteIndexMetadata(path, &rupture.IndexMetadata{
  125. Version: latestVersion,
  126. }); err != nil {
  127. return nil, err
  128. }
  129. return index, nil
  130. }
  131. var (
  132. _ Indexer = &BleveIndexer{}
  133. )
  134. // BleveIndexer implements Indexer interface
  135. type BleveIndexer struct {
  136. indexDir string
  137. indexer bleve.Index
  138. }
  139. // NewBleveIndexer creates a new bleve local indexer
  140. func NewBleveIndexer(indexDir string) *BleveIndexer {
  141. return &BleveIndexer{
  142. indexDir: indexDir,
  143. }
  144. }
  145. // Init will initial the indexer
  146. func (b *BleveIndexer) Init() (bool, error) {
  147. var err error
  148. b.indexer, err = openIndexer(b.indexDir, issueIndexerLatestVersion)
  149. if err != nil {
  150. return false, err
  151. }
  152. if b.indexer != nil {
  153. return true, nil
  154. }
  155. b.indexer, err = createIssueIndexer(b.indexDir, issueIndexerLatestVersion)
  156. return false, err
  157. }
  158. // Close will close the bleve indexer
  159. func (b *BleveIndexer) Close() {
  160. if b.indexer != nil {
  161. if err := b.indexer.Close(); err != nil {
  162. log.Error("Error whilst closing indexer: %v", err)
  163. }
  164. }
  165. }
  166. // Index will save the index data
  167. func (b *BleveIndexer) Index(issues []*IndexerData) error {
  168. batch := rupture.NewFlushingBatch(b.indexer, maxBatchSize)
  169. for _, issue := range issues {
  170. if err := batch.Index(indexerID(issue.ID), struct {
  171. RepoID int64
  172. Title string
  173. Content string
  174. Comments []string
  175. }{
  176. RepoID: issue.RepoID,
  177. Title: issue.Title,
  178. Content: issue.Content,
  179. Comments: issue.Comments,
  180. }); err != nil {
  181. return err
  182. }
  183. }
  184. return batch.Flush()
  185. }
  186. // Delete deletes indexes by ids
  187. func (b *BleveIndexer) Delete(ids ...int64) error {
  188. batch := rupture.NewFlushingBatch(b.indexer, maxBatchSize)
  189. for _, id := range ids {
  190. if err := batch.Delete(indexerID(id)); err != nil {
  191. return err
  192. }
  193. }
  194. return batch.Flush()
  195. }
  196. // Search searches for issues by given conditions.
  197. // Returns the matching issue IDs
  198. func (b *BleveIndexer) Search(keyword string, repoIDs []int64, limit, start int) (*SearchResult, error) {
  199. var repoQueriesP []*query.NumericRangeQuery
  200. for _, repoID := range repoIDs {
  201. repoQueriesP = append(repoQueriesP, numericEqualityQuery(repoID, "RepoID"))
  202. }
  203. repoQueries := make([]query.Query, len(repoQueriesP))
  204. for i, v := range repoQueriesP {
  205. repoQueries[i] = query.Query(v)
  206. }
  207. indexerQuery := bleve.NewConjunctionQuery(
  208. bleve.NewDisjunctionQuery(repoQueries...),
  209. bleve.NewDisjunctionQuery(
  210. newMatchPhraseQuery(keyword, "Title", issueIndexerAnalyzer),
  211. newMatchPhraseQuery(keyword, "Content", issueIndexerAnalyzer),
  212. newMatchPhraseQuery(keyword, "Comments", issueIndexerAnalyzer),
  213. ))
  214. search := bleve.NewSearchRequestOptions(indexerQuery, limit, start, false)
  215. result, err := b.indexer.Search(search)
  216. if err != nil {
  217. return nil, err
  218. }
  219. var ret = SearchResult{
  220. Hits: make([]Match, 0, len(result.Hits)),
  221. }
  222. for _, hit := range result.Hits {
  223. id, err := idOfIndexerID(hit.ID)
  224. if err != nil {
  225. return nil, err
  226. }
  227. ret.Hits = append(ret.Hits, Match{
  228. ID: id,
  229. })
  230. }
  231. return &ret, nil
  232. }