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.

check.go 8.2KB

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