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

Only check for conflicts/merging if the PR has not been merged in the interim (#10132) * Only check for merging if the PR has not been merged in the interim * fixup! Only check for merging if the PR has not been merged in the interim * Try to fix test failure * Use PR2 not PR1 in tests as PR1 merges automatically * return already merged error * enforce locking * enforce locking - fix-test * enforce locking - fix-testx2 * enforce locking - fix-testx3 * move pullrequest checking to after merge This might improve the chance that the race does not affect us but does not prevent it. * Remove minor race with getting merge commit id * fixup * move check pr after merge * Remove unnecessary prepareTestEnv - onGiteaRun does this for us * Add information about when merging occuring * fix fmt * More logging * Attempt to fix mysql * Try MySQL fix again * try again * Try again?! * Try again?! * Sigh * remove the count - perhaps that will help * next remove the update id * next remove the update id - make it updated_unix instead * On failure to merge ensure that the pr is rechecked for conflict errors * On failure to merge ensure that the pr is rechecked for conflict errors * Update models/pull.go * Update models/pull.go Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> * Apply suggestions from code review Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> Co-authored-by: Lauris BH <lauris@nix.lv> Co-authored-by: guillep2k <18600385+guillep2k@users.noreply.github.com>
5 years ago
[Enhancement] Allow admin to merge pr with protected file changes (#12078) * [Enhancement] Allow admin to merge pr with protected file changes As tilte, show protected message in diff page and merge box. Signed-off-by: a1012112796 <1012112796@qq.com> * remove unused ver * Update options/locale/locale_en-US.ini Co-authored-by: Cirno the Strongest <1447794+CirnoT@users.noreply.github.com> * Add TrN * Apply suggestions from code review * fix lint * Update options/locale/locale_en-US.ini Co-authored-by: zeripath <art27@cantab.net> * Apply suggestions from code review * move pr proteced files check to TestPatch * Call TestPatch when protected branches settings changed * Apply review suggestion @CirnoT * move to service @lunny * slightly restructure routers/private/hook.go Adds a lot of comments and simplifies the logic Signed-off-by: Andrew Thornton <art27@cantab.net> * placate lint Signed-off-by: Andrew Thornton <art27@cantab.net> * skip duplicate protected files check * fix check logic * slight refactor of TestPatch Signed-off-by: Andrew Thornton <art27@cantab.net> * When checking for protected files changes in TestPatch use the temporary repository Signed-off-by: Andrew Thornton <art27@cantab.net> * fix introduced issue with hook Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove the check on PR index being greater than 0 as it unnecessary Signed-off-by: Andrew Thornton <art27@cantab.net> Co-authored-by: techknowlogick <matti@mdranta.net> Co-authored-by: Cirno the Strongest <1447794+CirnoT@users.noreply.github.com> Co-authored-by: zeripath <art27@cantab.net> Co-authored-by: techknowlogick <techknowlogick@gitea.io>
4 years ago
Only check for conflicts/merging if the PR has not been merged in the interim (#10132) * Only check for merging if the PR has not been merged in the interim * fixup! Only check for merging if the PR has not been merged in the interim * Try to fix test failure * Use PR2 not PR1 in tests as PR1 merges automatically * return already merged error * enforce locking * enforce locking - fix-test * enforce locking - fix-testx2 * enforce locking - fix-testx3 * move pullrequest checking to after merge This might improve the chance that the race does not affect us but does not prevent it. * Remove minor race with getting merge commit id * fixup * move check pr after merge * Remove unnecessary prepareTestEnv - onGiteaRun does this for us * Add information about when merging occuring * fix fmt * More logging * Attempt to fix mysql * Try MySQL fix again * try again * Try again?! * Try again?! * Sigh * remove the count - perhaps that will help * next remove the update id * next remove the update id - make it updated_unix instead * On failure to merge ensure that the pr is rechecked for conflict errors * On failure to merge ensure that the pr is rechecked for conflict errors * Update models/pull.go * Update models/pull.go Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> * Apply suggestions from code review Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> Co-authored-by: Lauris BH <lauris@nix.lv> Co-authored-by: guillep2k <18600385+guillep2k@users.noreply.github.com>
5 years ago
Only check for conflicts/merging if the PR has not been merged in the interim (#10132) * Only check for merging if the PR has not been merged in the interim * fixup! Only check for merging if the PR has not been merged in the interim * Try to fix test failure * Use PR2 not PR1 in tests as PR1 merges automatically * return already merged error * enforce locking * enforce locking - fix-test * enforce locking - fix-testx2 * enforce locking - fix-testx3 * move pullrequest checking to after merge This might improve the chance that the race does not affect us but does not prevent it. * Remove minor race with getting merge commit id * fixup * move check pr after merge * Remove unnecessary prepareTestEnv - onGiteaRun does this for us * Add information about when merging occuring * fix fmt * More logging * Attempt to fix mysql * Try MySQL fix again * try again * Try again?! * Try again?! * Sigh * remove the count - perhaps that will help * next remove the update id * next remove the update id - make it updated_unix instead * On failure to merge ensure that the pr is rechecked for conflict errors * On failure to merge ensure that the pr is rechecked for conflict errors * Update models/pull.go * Update models/pull.go Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> * Apply suggestions from code review Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> Co-authored-by: Lauris BH <lauris@nix.lv> Co-authored-by: guillep2k <18600385+guillep2k@users.noreply.github.com>
5 years ago
Only check for conflicts/merging if the PR has not been merged in the interim (#10132) * Only check for merging if the PR has not been merged in the interim * fixup! Only check for merging if the PR has not been merged in the interim * Try to fix test failure * Use PR2 not PR1 in tests as PR1 merges automatically * return already merged error * enforce locking * enforce locking - fix-test * enforce locking - fix-testx2 * enforce locking - fix-testx3 * move pullrequest checking to after merge This might improve the chance that the race does not affect us but does not prevent it. * Remove minor race with getting merge commit id * fixup * move check pr after merge * Remove unnecessary prepareTestEnv - onGiteaRun does this for us * Add information about when merging occuring * fix fmt * More logging * Attempt to fix mysql * Try MySQL fix again * try again * Try again?! * Try again?! * Sigh * remove the count - perhaps that will help * next remove the update id * next remove the update id - make it updated_unix instead * On failure to merge ensure that the pr is rechecked for conflict errors * On failure to merge ensure that the pr is rechecked for conflict errors * Update models/pull.go * Update models/pull.go Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> * Apply suggestions from code review Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> Co-authored-by: Lauris BH <lauris@nix.lv> Co-authored-by: guillep2k <18600385+guillep2k@users.noreply.github.com>
5 years ago
[Enhancement] Allow admin to merge pr with protected file changes (#12078) * [Enhancement] Allow admin to merge pr with protected file changes As tilte, show protected message in diff page and merge box. Signed-off-by: a1012112796 <1012112796@qq.com> * remove unused ver * Update options/locale/locale_en-US.ini Co-authored-by: Cirno the Strongest <1447794+CirnoT@users.noreply.github.com> * Add TrN * Apply suggestions from code review * fix lint * Update options/locale/locale_en-US.ini Co-authored-by: zeripath <art27@cantab.net> * Apply suggestions from code review * move pr proteced files check to TestPatch * Call TestPatch when protected branches settings changed * Apply review suggestion @CirnoT * move to service @lunny * slightly restructure routers/private/hook.go Adds a lot of comments and simplifies the logic Signed-off-by: Andrew Thornton <art27@cantab.net> * placate lint Signed-off-by: Andrew Thornton <art27@cantab.net> * skip duplicate protected files check * fix check logic * slight refactor of TestPatch Signed-off-by: Andrew Thornton <art27@cantab.net> * When checking for protected files changes in TestPatch use the temporary repository Signed-off-by: Andrew Thornton <art27@cantab.net> * fix introduced issue with hook Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove the check on PR index being greater than 0 as it unnecessary Signed-off-by: Andrew Thornton <art27@cantab.net> Co-authored-by: techknowlogick <matti@mdranta.net> Co-authored-by: Cirno the Strongest <1447794+CirnoT@users.noreply.github.com> Co-authored-by: zeripath <art27@cantab.net> Co-authored-by: techknowlogick <techknowlogick@gitea.io>
4 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  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. "code.gitea.io/gitea/modules/util"
  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", "changed_protected_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 func() {
  75. if err := util.RemoveAll(indexTmpPath); err != nil {
  76. log.Warn("Unable to remove temporary index path: %s: Error: %v", indexTmpPath, err)
  77. }
  78. }()
  79. headFile := pr.GetGitRefName()
  80. // Check if a pull request is merged into BaseBranch
  81. _, err = git.NewCommand("merge-base", "--is-ancestor", headFile, pr.BaseBranch).
  82. RunInDirWithEnv(pr.BaseRepo.RepoPath(), []string{"GIT_INDEX_FILE=" + indexTmpPath, "GIT_DIR=" + pr.BaseRepo.RepoPath()})
  83. if err != nil {
  84. // Errors are signaled by a non-zero status that is not 1
  85. if strings.Contains(err.Error(), "exit status 1") {
  86. return nil, nil
  87. }
  88. return nil, fmt.Errorf("git merge-base --is-ancestor: %v", err)
  89. }
  90. commitIDBytes, err := ioutil.ReadFile(pr.BaseRepo.RepoPath() + "/" + headFile)
  91. if err != nil {
  92. return nil, fmt.Errorf("ReadFile(%s): %v", headFile, err)
  93. }
  94. commitID := string(commitIDBytes)
  95. if len(commitID) < 40 {
  96. return nil, fmt.Errorf(`ReadFile(%s): invalid commit-ID "%s"`, headFile, commitID)
  97. }
  98. cmd := commitID[:40] + ".." + pr.BaseBranch
  99. // Get the commit from BaseBranch where the pull request got merged
  100. mergeCommit, err := git.NewCommand("rev-list", "--ancestry-path", "--merges", "--reverse", cmd).
  101. RunInDirWithEnv("", []string{"GIT_INDEX_FILE=" + indexTmpPath, "GIT_DIR=" + pr.BaseRepo.RepoPath()})
  102. if err != nil {
  103. return nil, fmt.Errorf("git rev-list --ancestry-path --merges --reverse: %v", err)
  104. } else if len(mergeCommit) < 40 {
  105. // PR was maybe fast-forwarded, so just use last commit of PR
  106. mergeCommit = commitID[:40]
  107. }
  108. gitRepo, err := git.OpenRepository(pr.BaseRepo.RepoPath())
  109. if err != nil {
  110. return nil, fmt.Errorf("OpenRepository: %v", err)
  111. }
  112. defer gitRepo.Close()
  113. commit, err := gitRepo.GetCommit(mergeCommit[:40])
  114. if err != nil {
  115. return nil, fmt.Errorf("GetCommit: %v", err)
  116. }
  117. return commit, nil
  118. }
  119. // manuallyMerged checks if a pull request got manually merged
  120. // When a pull request got manually merged mark the pull request as merged
  121. func manuallyMerged(pr *models.PullRequest) bool {
  122. if err := pr.LoadBaseRepo(); err != nil {
  123. log.Error("PullRequest[%d].LoadBaseRepo: %v", pr.ID, err)
  124. return false
  125. }
  126. if unit, err := pr.BaseRepo.GetUnit(models.UnitTypePullRequests); err == nil {
  127. config := unit.PullRequestsConfig()
  128. if !config.AutodetectManualMerge {
  129. return false
  130. }
  131. } else {
  132. log.Error("PullRequest[%d].BaseRepo.GetUnit(models.UnitTypePullRequests): %v", pr.ID, err)
  133. return false
  134. }
  135. commit, err := getMergeCommit(pr)
  136. if err != nil {
  137. log.Error("PullRequest[%d].getMergeCommit: %v", pr.ID, err)
  138. return false
  139. }
  140. if commit != nil {
  141. pr.MergedCommitID = commit.ID.String()
  142. pr.MergedUnix = timeutil.TimeStamp(commit.Author.When.Unix())
  143. pr.Status = models.PullRequestStatusManuallyMerged
  144. merger, _ := models.GetUserByEmail(commit.Author.Email)
  145. // When the commit author is unknown set the BaseRepo owner as merger
  146. if merger == nil {
  147. if pr.BaseRepo.Owner == nil {
  148. if err = pr.BaseRepo.GetOwner(); err != nil {
  149. log.Error("BaseRepo.GetOwner[%d]: %v", pr.ID, err)
  150. return false
  151. }
  152. }
  153. merger = pr.BaseRepo.Owner
  154. }
  155. pr.Merger = merger
  156. pr.MergerID = merger.ID
  157. if merged, err := pr.SetMerged(); err != nil {
  158. log.Error("PullRequest[%d].setMerged : %v", pr.ID, err)
  159. return false
  160. } else if !merged {
  161. return false
  162. }
  163. notification.NotifyMergePullRequest(pr, merger)
  164. 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())
  165. return true
  166. }
  167. return false
  168. }
  169. // InitializePullRequests checks and tests untested patches of pull requests.
  170. func InitializePullRequests(ctx context.Context) {
  171. prs, err := models.GetPullRequestIDsByCheckStatus(models.PullRequestStatusChecking)
  172. if err != nil {
  173. log.Error("Find Checking PRs: %v", err)
  174. return
  175. }
  176. for _, prID := range prs {
  177. select {
  178. case <-ctx.Done():
  179. return
  180. default:
  181. if err := prQueue.PushFunc(strconv.FormatInt(prID, 10), func() error {
  182. log.Trace("Adding PR ID: %d to the pull requests patch checking queue", prID)
  183. return nil
  184. }); err != nil {
  185. log.Error("Error adding prID: %s to the pull requests patch checking queue %v", prID, err)
  186. }
  187. }
  188. }
  189. }
  190. // handle passed PR IDs and test the PRs
  191. func handle(data ...queue.Data) {
  192. for _, datum := range data {
  193. id, _ := strconv.ParseInt(datum.(string), 10, 64)
  194. log.Trace("Testing PR ID %d from the pull requests patch checking queue", id)
  195. pr, err := models.GetPullRequestByID(id)
  196. if err != nil {
  197. log.Error("GetPullRequestByID[%s]: %v", datum, err)
  198. continue
  199. } else if pr.HasMerged {
  200. continue
  201. } else if manuallyMerged(pr) {
  202. continue
  203. } else if err = TestPatch(pr); err != nil {
  204. log.Error("testPatch[%d]: %v", pr.ID, err)
  205. pr.Status = models.PullRequestStatusError
  206. if err := pr.UpdateCols("status"); err != nil {
  207. log.Error("update pr [%d] status to PullRequestStatusError failed: %v", pr.ID, err)
  208. }
  209. continue
  210. }
  211. checkAndUpdateStatus(pr)
  212. }
  213. }
  214. // CheckPrsForBaseBranch check all pulls with bseBrannch
  215. func CheckPrsForBaseBranch(baseRepo *models.Repository, baseBranchName string) error {
  216. prs, err := models.GetUnmergedPullRequestsByBaseInfo(baseRepo.ID, baseBranchName)
  217. if err != nil {
  218. return err
  219. }
  220. for _, pr := range prs {
  221. AddToTaskQueue(pr)
  222. }
  223. return nil
  224. }
  225. // Init runs the task queue to test all the checking status pull requests
  226. func Init() error {
  227. prQueue = queue.CreateUniqueQueue("pr_patch_checker", handle, "").(queue.UniqueQueue)
  228. if prQueue == nil {
  229. return fmt.Errorf("Unable to create pr_patch_checker Queue")
  230. }
  231. go graceful.GetManager().RunWithShutdownFns(prQueue.Run)
  232. go graceful.GetManager().RunWithShutdownContext(InitializePullRequests)
  233. return nil
  234. }