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.

pull.go 20KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700
  1. // Copyright 2019 The Gitea Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package pull
  5. import (
  6. "bufio"
  7. "bytes"
  8. "context"
  9. "fmt"
  10. "os"
  11. "path"
  12. "strings"
  13. "time"
  14. "code.gitea.io/gitea/models"
  15. "code.gitea.io/gitea/modules/git"
  16. "code.gitea.io/gitea/modules/graceful"
  17. "code.gitea.io/gitea/modules/log"
  18. "code.gitea.io/gitea/modules/notification"
  19. "code.gitea.io/gitea/modules/setting"
  20. issue_service "code.gitea.io/gitea/services/issue"
  21. "github.com/unknwon/com"
  22. )
  23. // NewPullRequest creates new pull request with labels for repository.
  24. func NewPullRequest(repo *models.Repository, pull *models.Issue, labelIDs []int64, uuids []string, pr *models.PullRequest, assigneeIDs []int64) error {
  25. if err := TestPatch(pr); err != nil {
  26. return err
  27. }
  28. divergence, err := GetDiverging(pr)
  29. if err != nil {
  30. return err
  31. }
  32. pr.CommitsAhead = divergence.Ahead
  33. pr.CommitsBehind = divergence.Behind
  34. if err := models.NewPullRequest(repo, pull, labelIDs, uuids, pr); err != nil {
  35. return err
  36. }
  37. for _, assigneeID := range assigneeIDs {
  38. if err := issue_service.AddAssigneeIfNotAssigned(pull, pull.Poster, assigneeID); err != nil {
  39. return err
  40. }
  41. }
  42. pr.Issue = pull
  43. pull.PullRequest = pr
  44. if err := PushToBaseRepo(pr); err != nil {
  45. return err
  46. }
  47. notification.NotifyNewPullRequest(pr)
  48. return nil
  49. }
  50. // ChangeTargetBranch changes the target branch of this pull request, as the given user.
  51. func ChangeTargetBranch(pr *models.PullRequest, doer *models.User, targetBranch string) (err error) {
  52. // Current target branch is already the same
  53. if pr.BaseBranch == targetBranch {
  54. return nil
  55. }
  56. if pr.Issue.IsClosed {
  57. return models.ErrIssueIsClosed{
  58. ID: pr.Issue.ID,
  59. RepoID: pr.Issue.RepoID,
  60. Index: pr.Issue.Index,
  61. }
  62. }
  63. if pr.HasMerged {
  64. return models.ErrPullRequestHasMerged{
  65. ID: pr.ID,
  66. IssueID: pr.Index,
  67. HeadRepoID: pr.HeadRepoID,
  68. BaseRepoID: pr.BaseRepoID,
  69. HeadBranch: pr.HeadBranch,
  70. BaseBranch: pr.BaseBranch,
  71. }
  72. }
  73. // Check if branches are equal
  74. branchesEqual, err := IsHeadEqualWithBranch(pr, targetBranch)
  75. if err != nil {
  76. return err
  77. }
  78. if branchesEqual {
  79. return models.ErrBranchesEqual{
  80. HeadBranchName: pr.HeadBranch,
  81. BaseBranchName: targetBranch,
  82. }
  83. }
  84. // Check if pull request for the new target branch already exists
  85. existingPr, err := models.GetUnmergedPullRequest(pr.HeadRepoID, pr.BaseRepoID, pr.HeadBranch, targetBranch)
  86. if existingPr != nil {
  87. return models.ErrPullRequestAlreadyExists{
  88. ID: existingPr.ID,
  89. IssueID: existingPr.Index,
  90. HeadRepoID: existingPr.HeadRepoID,
  91. BaseRepoID: existingPr.BaseRepoID,
  92. HeadBranch: existingPr.HeadBranch,
  93. BaseBranch: existingPr.BaseBranch,
  94. }
  95. }
  96. if err != nil && !models.IsErrPullRequestNotExist(err) {
  97. return err
  98. }
  99. // Set new target branch
  100. oldBranch := pr.BaseBranch
  101. pr.BaseBranch = targetBranch
  102. // Refresh patch
  103. if err := TestPatch(pr); err != nil {
  104. return err
  105. }
  106. // Update target branch, PR diff and status
  107. // This is the same as checkAndUpdateStatus in check service, but also updates base_branch
  108. if pr.Status == models.PullRequestStatusChecking {
  109. pr.Status = models.PullRequestStatusMergeable
  110. }
  111. // Update Commit Divergence
  112. divergence, err := GetDiverging(pr)
  113. if err != nil {
  114. return err
  115. }
  116. pr.CommitsAhead = divergence.Ahead
  117. pr.CommitsBehind = divergence.Behind
  118. if err := pr.UpdateColsIfNotMerged("merge_base", "status", "conflicted_files", "base_branch", "commits_ahead", "commits_behind"); err != nil {
  119. return err
  120. }
  121. // Create comment
  122. options := &models.CreateCommentOptions{
  123. Type: models.CommentTypeChangeTargetBranch,
  124. Doer: doer,
  125. Repo: pr.Issue.Repo,
  126. Issue: pr.Issue,
  127. OldRef: oldBranch,
  128. NewRef: targetBranch,
  129. }
  130. if _, err = models.CreateComment(options); err != nil {
  131. return fmt.Errorf("CreateChangeTargetBranchComment: %v", err)
  132. }
  133. return nil
  134. }
  135. func checkForInvalidation(requests models.PullRequestList, repoID int64, doer *models.User, branch string) error {
  136. repo, err := models.GetRepositoryByID(repoID)
  137. if err != nil {
  138. return fmt.Errorf("GetRepositoryByID: %v", err)
  139. }
  140. gitRepo, err := git.OpenRepository(repo.RepoPath())
  141. if err != nil {
  142. return fmt.Errorf("git.OpenRepository: %v", err)
  143. }
  144. go func() {
  145. // FIXME: graceful: We need to tell the manager we're doing something...
  146. err := requests.InvalidateCodeComments(doer, gitRepo, branch)
  147. if err != nil {
  148. log.Error("PullRequestList.InvalidateCodeComments: %v", err)
  149. }
  150. gitRepo.Close()
  151. }()
  152. return nil
  153. }
  154. func addHeadRepoTasks(prs []*models.PullRequest) {
  155. for _, pr := range prs {
  156. log.Trace("addHeadRepoTasks[%d]: composing new test task", pr.ID)
  157. if err := PushToBaseRepo(pr); err != nil {
  158. log.Error("PushToBaseRepo: %v", err)
  159. continue
  160. }
  161. AddToTaskQueue(pr)
  162. }
  163. }
  164. // AddTestPullRequestTask adds new test tasks by given head/base repository and head/base branch,
  165. // and generate new patch for testing as needed.
  166. func AddTestPullRequestTask(doer *models.User, repoID int64, branch string, isSync bool, oldCommitID, newCommitID string) {
  167. log.Trace("AddTestPullRequestTask [head_repo_id: %d, head_branch: %s]: finding pull requests", repoID, branch)
  168. graceful.GetManager().RunWithShutdownContext(func(ctx context.Context) {
  169. // There is no sensible way to shut this down ":-("
  170. // If you don't let it run all the way then you will lose data
  171. // FIXME: graceful: AddTestPullRequestTask needs to become a queue!
  172. prs, err := models.GetUnmergedPullRequestsByHeadInfo(repoID, branch)
  173. if err != nil {
  174. log.Error("Find pull requests [head_repo_id: %d, head_branch: %s]: %v", repoID, branch, err)
  175. return
  176. }
  177. if isSync {
  178. requests := models.PullRequestList(prs)
  179. if err = requests.LoadAttributes(); err != nil {
  180. log.Error("PullRequestList.LoadAttributes: %v", err)
  181. }
  182. if invalidationErr := checkForInvalidation(requests, repoID, doer, branch); invalidationErr != nil {
  183. log.Error("checkForInvalidation: %v", invalidationErr)
  184. }
  185. if err == nil {
  186. for _, pr := range prs {
  187. if newCommitID != "" && newCommitID != git.EmptySHA {
  188. changed, err := checkIfPRContentChanged(pr, oldCommitID, newCommitID)
  189. if err != nil {
  190. log.Error("checkIfPRContentChanged: %v", err)
  191. }
  192. if changed {
  193. // Mark old reviews as stale if diff to mergebase has changed
  194. if err := models.MarkReviewsAsStale(pr.IssueID); err != nil {
  195. log.Error("MarkReviewsAsStale: %v", err)
  196. }
  197. }
  198. if err := models.MarkReviewsAsNotStale(pr.IssueID, newCommitID); err != nil {
  199. log.Error("MarkReviewsAsNotStale: %v", err)
  200. }
  201. divergence, err := GetDiverging(pr)
  202. if err != nil {
  203. log.Error("GetDiverging: %v", err)
  204. } else {
  205. err = pr.UpdateCommitDivergence(divergence.Ahead, divergence.Behind)
  206. if err != nil {
  207. log.Error("UpdateCommitDivergence: %v", err)
  208. }
  209. }
  210. }
  211. pr.Issue.PullRequest = pr
  212. notification.NotifyPullRequestSynchronized(doer, pr)
  213. }
  214. }
  215. }
  216. addHeadRepoTasks(prs)
  217. log.Trace("AddTestPullRequestTask [base_repo_id: %d, base_branch: %s]: finding pull requests", repoID, branch)
  218. prs, err = models.GetUnmergedPullRequestsByBaseInfo(repoID, branch)
  219. if err != nil {
  220. log.Error("Find pull requests [base_repo_id: %d, base_branch: %s]: %v", repoID, branch, err)
  221. return
  222. }
  223. for _, pr := range prs {
  224. divergence, err := GetDiverging(pr)
  225. if err != nil {
  226. log.Error("GetDiverging: %v", err)
  227. } else {
  228. err = pr.UpdateCommitDivergence(divergence.Ahead, divergence.Behind)
  229. if err != nil {
  230. log.Error("UpdateCommitDivergence: %v", err)
  231. }
  232. }
  233. AddToTaskQueue(pr)
  234. }
  235. })
  236. }
  237. // checkIfPRContentChanged checks if diff to target branch has changed by push
  238. // A commit can be considered to leave the PR untouched if the patch/diff with its merge base is unchanged
  239. func checkIfPRContentChanged(pr *models.PullRequest, oldCommitID, newCommitID string) (hasChanged bool, err error) {
  240. if err = pr.LoadHeadRepo(); err != nil {
  241. return false, fmt.Errorf("LoadHeadRepo: %v", err)
  242. } else if pr.HeadRepo == nil {
  243. // corrupt data assumed changed
  244. return true, nil
  245. }
  246. if err = pr.LoadBaseRepo(); err != nil {
  247. return false, fmt.Errorf("LoadBaseRepo: %v", err)
  248. }
  249. headGitRepo, err := git.OpenRepository(pr.HeadRepo.RepoPath())
  250. if err != nil {
  251. return false, fmt.Errorf("OpenRepository: %v", err)
  252. }
  253. defer headGitRepo.Close()
  254. // Add a temporary remote.
  255. tmpRemote := "checkIfPRContentChanged-" + com.ToStr(time.Now().UnixNano())
  256. if err = headGitRepo.AddRemote(tmpRemote, pr.BaseRepo.RepoPath(), true); err != nil {
  257. return false, fmt.Errorf("AddRemote: %s/%s-%s: %v", pr.HeadRepo.OwnerName, pr.HeadRepo.Name, tmpRemote, err)
  258. }
  259. defer func() {
  260. if err := headGitRepo.RemoveRemote(tmpRemote); err != nil {
  261. log.Error("checkIfPRContentChanged: RemoveRemote: %s/%s-%s: %v", pr.HeadRepo.OwnerName, pr.HeadRepo.Name, tmpRemote, err)
  262. }
  263. }()
  264. // To synchronize repo and get a base ref
  265. _, base, err := headGitRepo.GetMergeBase(tmpRemote, pr.BaseBranch, pr.HeadBranch)
  266. if err != nil {
  267. return false, fmt.Errorf("GetMergeBase: %v", err)
  268. }
  269. diffBefore := &bytes.Buffer{}
  270. diffAfter := &bytes.Buffer{}
  271. if err := headGitRepo.GetDiffFromMergeBase(base, oldCommitID, diffBefore); err != nil {
  272. // If old commit not found, assume changed.
  273. log.Debug("GetDiffFromMergeBase: %v", err)
  274. return true, nil
  275. }
  276. if err := headGitRepo.GetDiffFromMergeBase(base, newCommitID, diffAfter); err != nil {
  277. // New commit should be found
  278. return false, fmt.Errorf("GetDiffFromMergeBase: %v", err)
  279. }
  280. diffBeforeLines := bufio.NewScanner(diffBefore)
  281. diffAfterLines := bufio.NewScanner(diffAfter)
  282. for diffBeforeLines.Scan() && diffAfterLines.Scan() {
  283. if strings.HasPrefix(diffBeforeLines.Text(), "index") && strings.HasPrefix(diffAfterLines.Text(), "index") {
  284. // file hashes can change without the diff changing
  285. continue
  286. } else if strings.HasPrefix(diffBeforeLines.Text(), "@@") && strings.HasPrefix(diffAfterLines.Text(), "@@") {
  287. // the location of the difference may change
  288. continue
  289. } else if !bytes.Equal(diffBeforeLines.Bytes(), diffAfterLines.Bytes()) {
  290. return true, nil
  291. }
  292. }
  293. if diffBeforeLines.Scan() || diffAfterLines.Scan() {
  294. // Diffs not of equal length
  295. return true, nil
  296. }
  297. return false, nil
  298. }
  299. // PushToBaseRepo pushes commits from branches of head repository to
  300. // corresponding branches of base repository.
  301. // FIXME: Only push branches that are actually updates?
  302. func PushToBaseRepo(pr *models.PullRequest) (err error) {
  303. log.Trace("PushToBaseRepo[%d]: pushing commits to base repo '%s'", pr.BaseRepoID, pr.GetGitRefName())
  304. // Clone base repo.
  305. tmpBasePath, err := models.CreateTemporaryPath("pull")
  306. if err != nil {
  307. log.Error("CreateTemporaryPath: %v", err)
  308. return err
  309. }
  310. defer func() {
  311. err := models.RemoveTemporaryPath(tmpBasePath)
  312. if err != nil {
  313. log.Error("Error whilst removing temporary path: %s Error: %v", tmpBasePath, err)
  314. }
  315. }()
  316. if err := pr.LoadHeadRepo(); err != nil {
  317. log.Error("Unable to load head repository for PR[%d] Error: %v", pr.ID, err)
  318. return err
  319. }
  320. headRepoPath := pr.HeadRepo.RepoPath()
  321. if err := git.Clone(headRepoPath, tmpBasePath, git.CloneRepoOptions{
  322. Bare: true,
  323. Shared: true,
  324. Branch: pr.HeadBranch,
  325. Quiet: true,
  326. }); err != nil {
  327. log.Error("git clone tmpBasePath: %v", err)
  328. return err
  329. }
  330. gitRepo, err := git.OpenRepository(tmpBasePath)
  331. if err != nil {
  332. return fmt.Errorf("OpenRepository: %v", err)
  333. }
  334. if err := pr.LoadBaseRepo(); err != nil {
  335. log.Error("Unable to load base repository for PR[%d] Error: %v", pr.ID, err)
  336. return err
  337. }
  338. if err := gitRepo.AddRemote("base", pr.BaseRepo.RepoPath(), false); err != nil {
  339. return fmt.Errorf("tmpGitRepo.AddRemote: %v", err)
  340. }
  341. defer gitRepo.Close()
  342. headFile := pr.GetGitRefName()
  343. // Remove head in case there is a conflict.
  344. file := path.Join(pr.BaseRepo.RepoPath(), headFile)
  345. _ = os.Remove(file)
  346. if err = pr.LoadIssue(); err != nil {
  347. return fmt.Errorf("unable to load issue %d for pr %d: %v", pr.IssueID, pr.ID, err)
  348. }
  349. if err = pr.Issue.LoadPoster(); err != nil {
  350. return fmt.Errorf("unable to load poster %d for pr %d: %v", pr.Issue.PosterID, pr.ID, err)
  351. }
  352. if err = git.Push(tmpBasePath, git.PushOptions{
  353. Remote: "base",
  354. Branch: fmt.Sprintf("%s:%s", pr.HeadBranch, headFile),
  355. Force: true,
  356. // Use InternalPushingEnvironment here because we know that pre-receive and post-receive do not run on a refs/pulls/...
  357. Env: models.InternalPushingEnvironment(pr.Issue.Poster, pr.BaseRepo),
  358. }); err != nil {
  359. if git.IsErrPushOutOfDate(err) {
  360. // This should not happen as we're using force!
  361. log.Error("Unable to push PR head for %s#%d (%-v:%s) due to ErrPushOfDate: %v", pr.BaseRepo.FullName(), pr.Index, pr.BaseRepo, headFile, err)
  362. return err
  363. } else if git.IsErrPushRejected(err) {
  364. rejectErr := err.(*git.ErrPushRejected)
  365. log.Info("Unable to push PR head for %s#%d (%-v:%s) due to rejection:\nStdout: %s\nStderr: %s\nError: %v", pr.BaseRepo.FullName(), pr.Index, pr.BaseRepo, headFile, rejectErr.StdOut, rejectErr.StdErr, rejectErr.Err)
  366. return err
  367. }
  368. log.Error("Unable to push PR head for %s#%d (%-v:%s) due to Error: %v", pr.BaseRepo.FullName(), pr.Index, pr.BaseRepo, headFile, err)
  369. return fmt.Errorf("Push: %s:%s %s:%s %v", pr.HeadRepo.FullName(), pr.HeadBranch, pr.BaseRepo.FullName(), headFile, err)
  370. }
  371. return nil
  372. }
  373. type errlist []error
  374. func (errs errlist) Error() string {
  375. if len(errs) > 0 {
  376. var buf strings.Builder
  377. for i, err := range errs {
  378. if i > 0 {
  379. buf.WriteString(", ")
  380. }
  381. buf.WriteString(err.Error())
  382. }
  383. return buf.String()
  384. }
  385. return ""
  386. }
  387. // CloseBranchPulls close all the pull requests who's head branch is the branch
  388. func CloseBranchPulls(doer *models.User, repoID int64, branch string) error {
  389. prs, err := models.GetUnmergedPullRequestsByHeadInfo(repoID, branch)
  390. if err != nil {
  391. return err
  392. }
  393. prs2, err := models.GetUnmergedPullRequestsByBaseInfo(repoID, branch)
  394. if err != nil {
  395. return err
  396. }
  397. prs = append(prs, prs2...)
  398. if err := models.PullRequestList(prs).LoadAttributes(); err != nil {
  399. return err
  400. }
  401. var errs errlist
  402. for _, pr := range prs {
  403. if err = issue_service.ChangeStatus(pr.Issue, doer, true); err != nil && !models.IsErrPullWasClosed(err) {
  404. errs = append(errs, err)
  405. }
  406. }
  407. if len(errs) > 0 {
  408. return errs
  409. }
  410. return nil
  411. }
  412. // CloseRepoBranchesPulls close all pull requests which head branches are in the given repository
  413. func CloseRepoBranchesPulls(doer *models.User, repo *models.Repository) error {
  414. branches, err := git.GetBranchesByPath(repo.RepoPath())
  415. if err != nil {
  416. return err
  417. }
  418. var errs errlist
  419. for _, branch := range branches {
  420. prs, err := models.GetUnmergedPullRequestsByHeadInfo(repo.ID, branch.Name)
  421. if err != nil {
  422. return err
  423. }
  424. if err = models.PullRequestList(prs).LoadAttributes(); err != nil {
  425. return err
  426. }
  427. for _, pr := range prs {
  428. if err = issue_service.ChangeStatus(pr.Issue, doer, true); err != nil && !models.IsErrPullWasClosed(err) {
  429. errs = append(errs, err)
  430. }
  431. }
  432. }
  433. if len(errs) > 0 {
  434. return errs
  435. }
  436. return nil
  437. }
  438. // GetCommitMessages returns the commit messages between head and merge base (if there is one)
  439. func GetCommitMessages(pr *models.PullRequest) string {
  440. if err := pr.LoadIssue(); err != nil {
  441. log.Error("Cannot load issue %d for PR id %d: Error: %v", pr.IssueID, pr.ID, err)
  442. return ""
  443. }
  444. if err := pr.Issue.LoadPoster(); err != nil {
  445. log.Error("Cannot load poster %d for pr id %d, index %d Error: %v", pr.Issue.PosterID, pr.ID, pr.Index, err)
  446. return ""
  447. }
  448. if pr.HeadRepo == nil {
  449. var err error
  450. pr.HeadRepo, err = models.GetRepositoryByID(pr.HeadRepoID)
  451. if err != nil {
  452. log.Error("GetRepositoryById[%d]: %v", pr.HeadRepoID, err)
  453. return ""
  454. }
  455. }
  456. gitRepo, err := git.OpenRepository(pr.HeadRepo.RepoPath())
  457. if err != nil {
  458. log.Error("Unable to open head repository: Error: %v", err)
  459. return ""
  460. }
  461. defer gitRepo.Close()
  462. headCommit, err := gitRepo.GetBranchCommit(pr.HeadBranch)
  463. if err != nil {
  464. log.Error("Unable to get head commit: %s Error: %v", pr.HeadBranch, err)
  465. return ""
  466. }
  467. mergeBase, err := gitRepo.GetCommit(pr.MergeBase)
  468. if err != nil {
  469. log.Error("Unable to get merge base commit: %s Error: %v", pr.MergeBase, err)
  470. return ""
  471. }
  472. limit := setting.Repository.PullRequest.DefaultMergeMessageCommitsLimit
  473. list, err := gitRepo.CommitsBetweenLimit(headCommit, mergeBase, limit, 0)
  474. if err != nil {
  475. log.Error("Unable to get commits between: %s %s Error: %v", pr.HeadBranch, pr.MergeBase, err)
  476. return ""
  477. }
  478. maxSize := setting.Repository.PullRequest.DefaultMergeMessageSize
  479. posterSig := pr.Issue.Poster.NewGitSig().String()
  480. authorsMap := map[string]bool{}
  481. authors := make([]string, 0, list.Len())
  482. stringBuilder := strings.Builder{}
  483. element := list.Front()
  484. for element != nil {
  485. commit := element.Value.(*git.Commit)
  486. if maxSize < 0 || stringBuilder.Len() < maxSize {
  487. toWrite := []byte(commit.CommitMessage)
  488. if len(toWrite) > maxSize-stringBuilder.Len() && maxSize > -1 {
  489. toWrite = append(toWrite[:maxSize-stringBuilder.Len()], "..."...)
  490. }
  491. if _, err := stringBuilder.Write(toWrite); err != nil {
  492. log.Error("Unable to write commit message Error: %v", err)
  493. return ""
  494. }
  495. if _, err := stringBuilder.WriteRune('\n'); err != nil {
  496. log.Error("Unable to write commit message Error: %v", err)
  497. return ""
  498. }
  499. }
  500. authorString := commit.Author.String()
  501. if !authorsMap[authorString] && authorString != posterSig {
  502. authors = append(authors, authorString)
  503. authorsMap[authorString] = true
  504. }
  505. element = element.Next()
  506. }
  507. // Consider collecting the remaining authors
  508. if limit >= 0 && setting.Repository.PullRequest.DefaultMergeMessageAllAuthors {
  509. skip := limit
  510. limit = 30
  511. for {
  512. list, err := gitRepo.CommitsBetweenLimit(headCommit, mergeBase, limit, skip)
  513. if err != nil {
  514. log.Error("Unable to get commits between: %s %s Error: %v", pr.HeadBranch, pr.MergeBase, err)
  515. return ""
  516. }
  517. if list.Len() == 0 {
  518. break
  519. }
  520. element := list.Front()
  521. for element != nil {
  522. commit := element.Value.(*git.Commit)
  523. authorString := commit.Author.String()
  524. if !authorsMap[authorString] && authorString != posterSig {
  525. authors = append(authors, authorString)
  526. authorsMap[authorString] = true
  527. }
  528. element = element.Next()
  529. }
  530. }
  531. }
  532. if len(authors) > 0 {
  533. if _, err := stringBuilder.WriteRune('\n'); err != nil {
  534. log.Error("Unable to write to string builder Error: %v", err)
  535. return ""
  536. }
  537. }
  538. for _, author := range authors {
  539. if _, err := stringBuilder.Write([]byte("Co-authored-by: ")); err != nil {
  540. log.Error("Unable to write to string builder Error: %v", err)
  541. return ""
  542. }
  543. if _, err := stringBuilder.Write([]byte(author)); err != nil {
  544. log.Error("Unable to write to string builder Error: %v", err)
  545. return ""
  546. }
  547. if _, err := stringBuilder.WriteRune('\n'); err != nil {
  548. log.Error("Unable to write to string builder Error: %v", err)
  549. return ""
  550. }
  551. }
  552. return stringBuilder.String()
  553. }
  554. // GetLastCommitStatus returns the last commit status for this pull request.
  555. func GetLastCommitStatus(pr *models.PullRequest) (status *models.CommitStatus, err error) {
  556. if err = pr.LoadHeadRepo(); err != nil {
  557. return nil, err
  558. }
  559. if pr.HeadRepo == nil {
  560. return nil, models.ErrPullRequestHeadRepoMissing{ID: pr.ID, HeadRepoID: pr.HeadRepoID}
  561. }
  562. headGitRepo, err := git.OpenRepository(pr.HeadRepo.RepoPath())
  563. if err != nil {
  564. return nil, err
  565. }
  566. defer headGitRepo.Close()
  567. lastCommitID, err := headGitRepo.GetBranchCommitID(pr.HeadBranch)
  568. if err != nil {
  569. return nil, err
  570. }
  571. err = pr.LoadBaseRepo()
  572. if err != nil {
  573. return nil, err
  574. }
  575. statusList, err := models.GetLatestCommitStatus(pr.BaseRepo, lastCommitID, 0)
  576. if err != nil {
  577. return nil, err
  578. }
  579. return models.CalcCommitStatus(statusList), nil
  580. }
  581. // IsHeadEqualWithBranch returns if the commits of branchName are available in pull request head
  582. func IsHeadEqualWithBranch(pr *models.PullRequest, branchName string) (bool, error) {
  583. var err error
  584. if err = pr.LoadBaseRepo(); err != nil {
  585. return false, err
  586. }
  587. baseGitRepo, err := git.OpenRepository(pr.BaseRepo.RepoPath())
  588. if err != nil {
  589. return false, err
  590. }
  591. baseCommit, err := baseGitRepo.GetBranchCommit(branchName)
  592. if err != nil {
  593. return false, err
  594. }
  595. if err = pr.LoadHeadRepo(); err != nil {
  596. return false, err
  597. }
  598. headGitRepo, err := git.OpenRepository(pr.HeadRepo.RepoPath())
  599. if err != nil {
  600. return false, err
  601. }
  602. headCommit, err := headGitRepo.GetBranchCommit(pr.HeadBranch)
  603. if err != nil {
  604. return false, err
  605. }
  606. return baseCommit.HasPreviousCommit(headCommit.ID)
  607. }