選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. // Copyright 2019 The Gitea Authors.
  2. // All rights reserved.
  3. // Use of this source code is governed by a MIT-style
  4. // license that can be found in the LICENSE file.
  5. package pull
  6. import (
  7. "context"
  8. "fmt"
  9. "io/ioutil"
  10. "os"
  11. "strconv"
  12. "strings"
  13. "code.gitea.io/gitea/models"
  14. "code.gitea.io/gitea/modules/git"
  15. "code.gitea.io/gitea/modules/graceful"
  16. "code.gitea.io/gitea/modules/log"
  17. "code.gitea.io/gitea/modules/notification"
  18. "code.gitea.io/gitea/modules/queue"
  19. "code.gitea.io/gitea/modules/timeutil"
  20. "github.com/unknwon/com"
  21. )
  22. // prQueue represents a queue to handle update pull request tests
  23. var prQueue queue.UniqueQueue
  24. // AddToTaskQueue adds itself to pull request test task queue.
  25. func AddToTaskQueue(pr *models.PullRequest) {
  26. go func() {
  27. err := prQueue.PushFunc(strconv.FormatInt(pr.ID, 10), func() error {
  28. pr.Status = models.PullRequestStatusChecking
  29. err := pr.UpdateColsIfNotMerged("status")
  30. if err != nil {
  31. log.Error("AddToTaskQueue.UpdateCols[%d].(add to queue): %v", pr.ID, err)
  32. } else {
  33. log.Trace("Adding PR ID: %d to the test pull requests queue", pr.ID)
  34. }
  35. return err
  36. })
  37. if err != nil && err != queue.ErrAlreadyInQueue {
  38. log.Error("Error adding prID %d to the test pull requests queue: %v", pr.ID, err)
  39. }
  40. }()
  41. }
  42. // checkAndUpdateStatus checks if pull request is possible to leaving checking status,
  43. // and set to be either conflict or mergeable.
  44. func checkAndUpdateStatus(pr *models.PullRequest) {
  45. // Status is not changed to conflict means mergeable.
  46. if pr.Status == models.PullRequestStatusChecking {
  47. pr.Status = models.PullRequestStatusMergeable
  48. }
  49. // Make sure there is no waiting test to process before leaving the checking status.
  50. has, err := prQueue.Has(strconv.FormatInt(pr.ID, 10))
  51. if err != nil {
  52. log.Error("Unable to check if the queue is waiting to reprocess pr.ID %d. Error: %v", pr.ID, err)
  53. }
  54. if !has {
  55. if err := pr.UpdateColsIfNotMerged("merge_base", "status", "conflicted_files"); err != nil {
  56. log.Error("Update[%d]: %v", pr.ID, err)
  57. }
  58. }
  59. }
  60. // getMergeCommit checks if a pull request got merged
  61. // Returns the git.Commit of the pull request if merged
  62. func getMergeCommit(pr *models.PullRequest) (*git.Commit, error) {
  63. if pr.BaseRepo == nil {
  64. var err error
  65. pr.BaseRepo, err = models.GetRepositoryByID(pr.BaseRepoID)
  66. if err != nil {
  67. return nil, fmt.Errorf("GetRepositoryByID: %v", err)
  68. }
  69. }
  70. indexTmpPath, err := ioutil.TempDir(os.TempDir(), "gitea-"+pr.BaseRepo.Name)
  71. if err != nil {
  72. return nil, fmt.Errorf("Failed to create temp dir for repository %s: %v", pr.BaseRepo.RepoPath(), err)
  73. }
  74. defer os.RemoveAll(indexTmpPath)
  75. headFile := pr.GetGitRefName()
  76. // Check if a pull request is merged into BaseBranch
  77. _, err = git.NewCommand("merge-base", "--is-ancestor", headFile, pr.BaseBranch).
  78. RunInDirWithEnv(pr.BaseRepo.RepoPath(), []string{"GIT_INDEX_FILE=" + indexTmpPath, "GIT_DIR=" + pr.BaseRepo.RepoPath()})
  79. if err != nil {
  80. // Errors are signaled by a non-zero status that is not 1
  81. if strings.Contains(err.Error(), "exit status 1") {
  82. return nil, nil
  83. }
  84. return nil, fmt.Errorf("git merge-base --is-ancestor: %v", err)
  85. }
  86. commitIDBytes, err := ioutil.ReadFile(pr.BaseRepo.RepoPath() + "/" + headFile)
  87. if err != nil {
  88. return nil, fmt.Errorf("ReadFile(%s): %v", headFile, err)
  89. }
  90. commitID := string(commitIDBytes)
  91. if len(commitID) < 40 {
  92. return nil, fmt.Errorf(`ReadFile(%s): invalid commit-ID "%s"`, headFile, commitID)
  93. }
  94. cmd := commitID[:40] + ".." + pr.BaseBranch
  95. // Get the commit from BaseBranch where the pull request got merged
  96. mergeCommit, err := git.NewCommand("rev-list", "--ancestry-path", "--merges", "--reverse", cmd).
  97. RunInDirWithEnv("", []string{"GIT_INDEX_FILE=" + indexTmpPath, "GIT_DIR=" + pr.BaseRepo.RepoPath()})
  98. if err != nil {
  99. return nil, fmt.Errorf("git rev-list --ancestry-path --merges --reverse: %v", err)
  100. } else if len(mergeCommit) < 40 {
  101. // PR was fast-forwarded, so just use last commit of PR
  102. mergeCommit = commitID[:40]
  103. }
  104. gitRepo, err := git.OpenRepository(pr.BaseRepo.RepoPath())
  105. if err != nil {
  106. return nil, fmt.Errorf("OpenRepository: %v", err)
  107. }
  108. defer gitRepo.Close()
  109. commit, err := gitRepo.GetCommit(mergeCommit[:40])
  110. if err != nil {
  111. return nil, fmt.Errorf("GetCommit: %v", err)
  112. }
  113. return commit, nil
  114. }
  115. // manuallyMerged checks if a pull request got manually merged
  116. // When a pull request got manually merged mark the pull request as merged
  117. func manuallyMerged(pr *models.PullRequest) bool {
  118. commit, err := getMergeCommit(pr)
  119. if err != nil {
  120. log.Error("PullRequest[%d].getMergeCommit: %v", pr.ID, err)
  121. return false
  122. }
  123. if commit != nil {
  124. pr.MergedCommitID = commit.ID.String()
  125. pr.MergedUnix = timeutil.TimeStamp(commit.Author.When.Unix())
  126. pr.Status = models.PullRequestStatusManuallyMerged
  127. merger, _ := models.GetUserByEmail(commit.Author.Email)
  128. // When the commit author is unknown set the BaseRepo owner as merger
  129. if merger == nil {
  130. if pr.BaseRepo.Owner == nil {
  131. if err = pr.BaseRepo.GetOwner(); err != nil {
  132. log.Error("BaseRepo.GetOwner[%d]: %v", pr.ID, err)
  133. return false
  134. }
  135. }
  136. merger = pr.BaseRepo.Owner
  137. }
  138. pr.Merger = merger
  139. pr.MergerID = merger.ID
  140. if merged, err := pr.SetMerged(); err != nil {
  141. log.Error("PullRequest[%d].setMerged : %v", pr.ID, err)
  142. return false
  143. } else if !merged {
  144. return false
  145. }
  146. notification.NotifyMergePullRequest(pr, merger)
  147. log.Info("manuallyMerged[%d]: Marked as manually merged into %s/%s by commit id: %s", pr.ID, pr.BaseRepo.Name, pr.BaseBranch, commit.ID.String())
  148. return true
  149. }
  150. return false
  151. }
  152. // InitializePullRequests checks and tests untested patches of pull requests.
  153. func InitializePullRequests(ctx context.Context) {
  154. prs, err := models.GetPullRequestIDsByCheckStatus(models.PullRequestStatusChecking)
  155. if err != nil {
  156. log.Error("Find Checking PRs: %v", err)
  157. return
  158. }
  159. for _, prID := range prs {
  160. select {
  161. case <-ctx.Done():
  162. return
  163. default:
  164. if err := prQueue.PushFunc(strconv.FormatInt(prID, 10), func() error {
  165. log.Trace("Adding PR ID: %d to the pull requests patch checking queue", prID)
  166. return nil
  167. }); err != nil {
  168. log.Error("Error adding prID: %s to the pull requests patch checking queue %v", prID, err)
  169. }
  170. }
  171. }
  172. }
  173. // handle passed PR IDs and test the PRs
  174. func handle(data ...queue.Data) {
  175. for _, datum := range data {
  176. prID := datum.(string)
  177. id := com.StrTo(prID).MustInt64()
  178. log.Trace("Testing PR ID %d from the pull requests patch checking queue", id)
  179. pr, err := models.GetPullRequestByID(id)
  180. if err != nil {
  181. log.Error("GetPullRequestByID[%s]: %v", prID, err)
  182. continue
  183. } else if pr.HasMerged {
  184. continue
  185. } else if manuallyMerged(pr) {
  186. continue
  187. } else if err = TestPatch(pr); err != nil {
  188. log.Error("testPatch[%d]: %v", pr.ID, err)
  189. pr.Status = models.PullRequestStatusError
  190. if err := pr.UpdateCols("status"); err != nil {
  191. log.Error("update pr [%d] status to PullRequestStatusError failed: %v", pr.ID, err)
  192. }
  193. continue
  194. }
  195. checkAndUpdateStatus(pr)
  196. }
  197. }
  198. // Init runs the task queue to test all the checking status pull requests
  199. func Init() error {
  200. prQueue = queue.CreateUniqueQueue("pr_patch_checker", handle, "").(queue.UniqueQueue)
  201. if prQueue == nil {
  202. return fmt.Errorf("Unable to create pr_patch_checker Queue")
  203. }
  204. go graceful.GetManager().RunWithShutdownFns(prQueue.Run)
  205. go graceful.GetManager().RunWithShutdownContext(InitializePullRequests)
  206. return nil
  207. }