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 6.3 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  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. "path/filepath"
  12. "strconv"
  13. "strings"
  14. "time"
  15. "code.gitea.io/gitea/models"
  16. "code.gitea.io/gitea/modules/git"
  17. "code.gitea.io/gitea/modules/graceful"
  18. "code.gitea.io/gitea/modules/log"
  19. "code.gitea.io/gitea/modules/setting"
  20. "code.gitea.io/gitea/modules/sync"
  21. "code.gitea.io/gitea/modules/timeutil"
  22. "github.com/unknwon/com"
  23. )
  24. // pullRequestQueue represents a queue to handle update pull request tests
  25. var pullRequestQueue = sync.NewUniqueQueue(setting.Repository.PullRequestQueueLength)
  26. // AddToTaskQueue adds itself to pull request test task queue.
  27. func AddToTaskQueue(pr *models.PullRequest) {
  28. go pullRequestQueue.AddFunc(pr.ID, func() {
  29. pr.Status = models.PullRequestStatusChecking
  30. if err := pr.UpdateCols("status"); err != nil {
  31. log.Error("AddToTaskQueue.UpdateCols[%d].(add to queue): %v", pr.ID, err)
  32. }
  33. })
  34. }
  35. // checkAndUpdateStatus checks if pull request is possible to leaving checking status,
  36. // and set to be either conflict or mergeable.
  37. func checkAndUpdateStatus(pr *models.PullRequest) {
  38. // Status is not changed to conflict means mergeable.
  39. if pr.Status == models.PullRequestStatusChecking {
  40. pr.Status = models.PullRequestStatusMergeable
  41. }
  42. // Make sure there is no waiting test to process before leaving the checking status.
  43. if !pullRequestQueue.Exist(pr.ID) {
  44. if err := pr.UpdateCols("status, conflicted_files"); err != nil {
  45. log.Error("Update[%d]: %v", pr.ID, err)
  46. }
  47. }
  48. }
  49. // getMergeCommit checks if a pull request got merged
  50. // Returns the git.Commit of the pull request if merged
  51. func getMergeCommit(pr *models.PullRequest) (*git.Commit, error) {
  52. if pr.BaseRepo == nil {
  53. var err error
  54. pr.BaseRepo, err = models.GetRepositoryByID(pr.BaseRepoID)
  55. if err != nil {
  56. return nil, fmt.Errorf("GetRepositoryByID: %v", err)
  57. }
  58. }
  59. indexTmpPath := filepath.Join(os.TempDir(), "gitea-"+pr.BaseRepo.Name+"-"+strconv.Itoa(time.Now().Nanosecond()))
  60. defer os.Remove(indexTmpPath)
  61. headFile := pr.GetGitRefName()
  62. // Check if a pull request is merged into BaseBranch
  63. _, err := git.NewCommand("merge-base", "--is-ancestor", headFile, pr.BaseBranch).RunInDirWithEnv(pr.BaseRepo.RepoPath(), []string{"GIT_INDEX_FILE=" + indexTmpPath, "GIT_DIR=" + pr.BaseRepo.RepoPath()})
  64. if err != nil {
  65. // Errors are signaled by a non-zero status that is not 1
  66. if strings.Contains(err.Error(), "exit status 1") {
  67. return nil, nil
  68. }
  69. return nil, fmt.Errorf("git merge-base --is-ancestor: %v", err)
  70. }
  71. commitIDBytes, err := ioutil.ReadFile(pr.BaseRepo.RepoPath() + "/" + headFile)
  72. if err != nil {
  73. return nil, fmt.Errorf("ReadFile(%s): %v", headFile, err)
  74. }
  75. commitID := string(commitIDBytes)
  76. if len(commitID) < 40 {
  77. return nil, fmt.Errorf(`ReadFile(%s): invalid commit-ID "%s"`, headFile, commitID)
  78. }
  79. cmd := commitID[:40] + ".." + pr.BaseBranch
  80. // Get the commit from BaseBranch where the pull request got merged
  81. mergeCommit, err := git.NewCommand("rev-list", "--ancestry-path", "--merges", "--reverse", cmd).RunInDirWithEnv("", []string{"GIT_INDEX_FILE=" + indexTmpPath, "GIT_DIR=" + pr.BaseRepo.RepoPath()})
  82. if err != nil {
  83. return nil, fmt.Errorf("git rev-list --ancestry-path --merges --reverse: %v", err)
  84. } else if len(mergeCommit) < 40 {
  85. // PR was fast-forwarded, so just use last commit of PR
  86. mergeCommit = commitID[:40]
  87. }
  88. gitRepo, err := git.OpenRepository(pr.BaseRepo.RepoPath())
  89. if err != nil {
  90. return nil, fmt.Errorf("OpenRepository: %v", err)
  91. }
  92. defer gitRepo.Close()
  93. commit, err := gitRepo.GetCommit(mergeCommit[:40])
  94. if err != nil {
  95. return nil, fmt.Errorf("GetCommit: %v", err)
  96. }
  97. return commit, nil
  98. }
  99. // manuallyMerged checks if a pull request got manually merged
  100. // When a pull request got manually merged mark the pull request as merged
  101. func manuallyMerged(pr *models.PullRequest) bool {
  102. commit, err := getMergeCommit(pr)
  103. if err != nil {
  104. log.Error("PullRequest[%d].getMergeCommit: %v", pr.ID, err)
  105. return false
  106. }
  107. if commit != nil {
  108. pr.MergedCommitID = commit.ID.String()
  109. pr.MergedUnix = timeutil.TimeStamp(commit.Author.When.Unix())
  110. pr.Status = models.PullRequestStatusManuallyMerged
  111. merger, _ := models.GetUserByEmail(commit.Author.Email)
  112. // When the commit author is unknown set the BaseRepo owner as merger
  113. if merger == nil {
  114. if pr.BaseRepo.Owner == nil {
  115. if err = pr.BaseRepo.GetOwner(); err != nil {
  116. log.Error("BaseRepo.GetOwner[%d]: %v", pr.ID, err)
  117. return false
  118. }
  119. }
  120. merger = pr.BaseRepo.Owner
  121. }
  122. pr.Merger = merger
  123. pr.MergerID = merger.ID
  124. if err = pr.SetMerged(); err != nil {
  125. log.Error("PullRequest[%d].setMerged : %v", pr.ID, err)
  126. return false
  127. }
  128. 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())
  129. return true
  130. }
  131. return false
  132. }
  133. // TestPullRequests checks and tests untested patches of pull requests.
  134. // TODO: test more pull requests at same time.
  135. func TestPullRequests(ctx context.Context) {
  136. go func() {
  137. prs, err := models.GetPullRequestIDsByCheckStatus(models.PullRequestStatusChecking)
  138. if err != nil {
  139. log.Error("Find Checking PRs: %v", err)
  140. return
  141. }
  142. for _, prID := range prs {
  143. select {
  144. case <-ctx.Done():
  145. return
  146. default:
  147. pullRequestQueue.Add(prID)
  148. }
  149. }
  150. }()
  151. // Start listening on new test requests.
  152. for {
  153. select {
  154. case prID := <-pullRequestQueue.Queue():
  155. log.Trace("TestPullRequests[%v]: processing test task", prID)
  156. pullRequestQueue.Remove(prID)
  157. id := com.StrTo(prID).MustInt64()
  158. pr, err := models.GetPullRequestByID(id)
  159. if err != nil {
  160. log.Error("GetPullRequestByID[%s]: %v", prID, err)
  161. continue
  162. } else if manuallyMerged(pr) {
  163. continue
  164. } else if err = TestPatch(pr); err != nil {
  165. log.Error("testPatch[%d]: %v", pr.ID, err)
  166. continue
  167. }
  168. checkAndUpdateStatus(pr)
  169. case <-ctx.Done():
  170. pullRequestQueue.Close()
  171. log.Info("PID: %d Pull Request testing shutdown", os.Getpid())
  172. return
  173. }
  174. }
  175. }
  176. // Init runs the task queue to test all the checking status pull requests
  177. func Init() {
  178. go graceful.GetManager().RunWithShutdownContext(TestPullRequests)
  179. }