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

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