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

check.go 7.4 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  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.UpdateCols("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.UpdateCols("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 err = pr.SetMerged(); err != nil {
  141. log.Error("PullRequest[%d].setMerged : %v", pr.ID, err)
  142. return false
  143. }
  144. notification.NotifyMergePullRequest(pr, merger)
  145. 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())
  146. return true
  147. }
  148. return false
  149. }
  150. // InitializePullRequests checks and tests untested patches of pull requests.
  151. func InitializePullRequests(ctx context.Context) {
  152. prs, err := models.GetPullRequestIDsByCheckStatus(models.PullRequestStatusChecking)
  153. if err != nil {
  154. log.Error("Find Checking PRs: %v", err)
  155. return
  156. }
  157. for _, prID := range prs {
  158. select {
  159. case <-ctx.Done():
  160. return
  161. default:
  162. if err := prQueue.PushFunc(strconv.FormatInt(prID, 10), func() error {
  163. log.Trace("Adding PR ID: %d to the pull requests patch checking queue", prID)
  164. return nil
  165. }); err != nil {
  166. log.Error("Error adding prID: %s to the pull requests patch checking queue %v", prID, err)
  167. }
  168. }
  169. }
  170. }
  171. // handle passed PR IDs and test the PRs
  172. func handle(data ...queue.Data) {
  173. for _, datum := range data {
  174. prID := datum.(string)
  175. id := com.StrTo(prID).MustInt64()
  176. log.Trace("Testing PR ID %d from the pull requests patch checking queue", id)
  177. pr, err := models.GetPullRequestByID(id)
  178. if err != nil {
  179. log.Error("GetPullRequestByID[%s]: %v", prID, err)
  180. continue
  181. } else if pr.Status != models.PullRequestStatusChecking {
  182. continue
  183. } else if manuallyMerged(pr) {
  184. continue
  185. } else if err = TestPatch(pr); err != nil {
  186. log.Error("testPatch[%d]: %v", pr.ID, err)
  187. pr.Status = models.PullRequestStatusError
  188. if err := pr.UpdateCols("status"); err != nil {
  189. log.Error("update pr [%d] status to PullRequestStatusError failed: %v", pr.ID, err)
  190. }
  191. continue
  192. }
  193. checkAndUpdateStatus(pr)
  194. }
  195. }
  196. // Init runs the task queue to test all the checking status pull requests
  197. func Init() error {
  198. prQueue = queue.CreateUniqueQueue("pr_patch_checker", handle, "").(queue.UniqueQueue)
  199. if prQueue == nil {
  200. return fmt.Errorf("Unable to create pr_patch_checker Queue")
  201. }
  202. go graceful.GetManager().RunWithShutdownFns(prQueue.Run)
  203. go graceful.GetManager().RunWithShutdownContext(InitializePullRequests)
  204. return nil
  205. }