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 37KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244
  1. // Copyright 2015 The Gogs 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 models
  5. import (
  6. "fmt"
  7. "io/ioutil"
  8. "os"
  9. "path"
  10. "path/filepath"
  11. "strconv"
  12. "strings"
  13. "time"
  14. "code.gitea.io/git"
  15. "code.gitea.io/gitea/modules/base"
  16. "code.gitea.io/gitea/modules/cache"
  17. "code.gitea.io/gitea/modules/log"
  18. "code.gitea.io/gitea/modules/process"
  19. "code.gitea.io/gitea/modules/setting"
  20. "code.gitea.io/gitea/modules/sync"
  21. "code.gitea.io/gitea/modules/util"
  22. api "code.gitea.io/sdk/gitea"
  23. "github.com/Unknwon/com"
  24. "github.com/go-xorm/xorm"
  25. )
  26. var pullRequestQueue = sync.NewUniqueQueue(setting.Repository.PullRequestQueueLength)
  27. // PullRequestType defines pull request type
  28. type PullRequestType int
  29. // Enumerate all the pull request types
  30. const (
  31. PullRequestGitea PullRequestType = iota
  32. PullRequestGit
  33. )
  34. // PullRequestStatus defines pull request status
  35. type PullRequestStatus int
  36. // Enumerate all the pull request status
  37. const (
  38. PullRequestStatusConflict PullRequestStatus = iota
  39. PullRequestStatusChecking
  40. PullRequestStatusMergeable
  41. PullRequestStatusManuallyMerged
  42. )
  43. // PullRequest represents relation between pull request and repositories.
  44. type PullRequest struct {
  45. ID int64 `xorm:"pk autoincr"`
  46. Type PullRequestType
  47. Status PullRequestStatus
  48. IssueID int64 `xorm:"INDEX"`
  49. Issue *Issue `xorm:"-"`
  50. Index int64
  51. HeadRepoID int64 `xorm:"INDEX"`
  52. HeadRepo *Repository `xorm:"-"`
  53. BaseRepoID int64 `xorm:"INDEX"`
  54. BaseRepo *Repository `xorm:"-"`
  55. HeadUserName string
  56. HeadBranch string
  57. BaseBranch string
  58. MergeBase string `xorm:"VARCHAR(40)"`
  59. HasMerged bool `xorm:"INDEX"`
  60. MergedCommitID string `xorm:"VARCHAR(40)"`
  61. MergerID int64 `xorm:"INDEX"`
  62. Merger *User `xorm:"-"`
  63. MergedUnix util.TimeStamp `xorm:"updated INDEX"`
  64. }
  65. // Note: don't try to get Issue because will end up recursive querying.
  66. func (pr *PullRequest) loadAttributes(e Engine) (err error) {
  67. if pr.HasMerged && pr.Merger == nil {
  68. pr.Merger, err = getUserByID(e, pr.MergerID)
  69. if IsErrUserNotExist(err) {
  70. pr.MergerID = -1
  71. pr.Merger = NewGhostUser()
  72. } else if err != nil {
  73. return fmt.Errorf("getUserByID [%d]: %v", pr.MergerID, err)
  74. }
  75. }
  76. return nil
  77. }
  78. // LoadAttributes loads pull request attributes from database
  79. func (pr *PullRequest) LoadAttributes() error {
  80. return pr.loadAttributes(x)
  81. }
  82. // LoadIssue loads issue information from database
  83. func (pr *PullRequest) LoadIssue() (err error) {
  84. return pr.loadIssue(x)
  85. }
  86. func (pr *PullRequest) loadIssue(e Engine) (err error) {
  87. if pr.Issue != nil {
  88. return nil
  89. }
  90. pr.Issue, err = getIssueByID(e, pr.IssueID)
  91. return err
  92. }
  93. // GetDefaultMergeMessage returns default message used when merging pull request
  94. func (pr *PullRequest) GetDefaultMergeMessage() string {
  95. if pr.HeadRepo == nil {
  96. var err error
  97. pr.HeadRepo, err = GetRepositoryByID(pr.HeadRepoID)
  98. if err != nil {
  99. log.Error(4, "GetRepositoryById[%d]: %v", pr.HeadRepoID, err)
  100. return ""
  101. }
  102. }
  103. return fmt.Sprintf("Merge branch '%s' of %s/%s into %s", pr.HeadBranch, pr.HeadUserName, pr.HeadRepo.Name, pr.BaseBranch)
  104. }
  105. // GetDefaultSquashMessage returns default message used when squash and merging pull request
  106. func (pr *PullRequest) GetDefaultSquashMessage() string {
  107. if err := pr.LoadIssue(); err != nil {
  108. log.Error(4, "LoadIssue: %v", err)
  109. return ""
  110. }
  111. return fmt.Sprintf("%s (#%d)", pr.Issue.Title, pr.Issue.Index)
  112. }
  113. // GetGitRefName returns git ref for hidden pull request branch
  114. func (pr *PullRequest) GetGitRefName() string {
  115. return fmt.Sprintf("refs/pull/%d/head", pr.Index)
  116. }
  117. // APIFormat assumes following fields have been assigned with valid values:
  118. // Required - Issue
  119. // Optional - Merger
  120. func (pr *PullRequest) APIFormat() *api.PullRequest {
  121. var (
  122. baseBranch *Branch
  123. headBranch *Branch
  124. baseCommit *git.Commit
  125. headCommit *git.Commit
  126. err error
  127. )
  128. apiIssue := pr.Issue.APIFormat()
  129. if pr.BaseRepo == nil {
  130. pr.BaseRepo, err = GetRepositoryByID(pr.BaseRepoID)
  131. if err != nil {
  132. log.Error(log.ERROR, "GetRepositoryById[%d]: %v", pr.ID, err)
  133. return nil
  134. }
  135. }
  136. if pr.HeadRepo == nil {
  137. pr.HeadRepo, err = GetRepositoryByID(pr.HeadRepoID)
  138. if err != nil {
  139. log.Error(log.ERROR, "GetRepositoryById[%d]: %v", pr.ID, err)
  140. return nil
  141. }
  142. }
  143. if baseBranch, err = pr.BaseRepo.GetBranch(pr.BaseBranch); err != nil {
  144. return nil
  145. }
  146. if baseCommit, err = baseBranch.GetCommit(); err != nil {
  147. return nil
  148. }
  149. if headBranch, err = pr.HeadRepo.GetBranch(pr.HeadBranch); err != nil {
  150. return nil
  151. }
  152. if headCommit, err = headBranch.GetCommit(); err != nil {
  153. return nil
  154. }
  155. apiBaseBranchInfo := &api.PRBranchInfo{
  156. Name: pr.BaseBranch,
  157. Ref: pr.BaseBranch,
  158. Sha: baseCommit.ID.String(),
  159. RepoID: pr.BaseRepoID,
  160. Repository: pr.BaseRepo.APIFormat(AccessModeNone),
  161. }
  162. apiHeadBranchInfo := &api.PRBranchInfo{
  163. Name: pr.HeadBranch,
  164. Ref: pr.HeadBranch,
  165. Sha: headCommit.ID.String(),
  166. RepoID: pr.HeadRepoID,
  167. Repository: pr.HeadRepo.APIFormat(AccessModeNone),
  168. }
  169. apiPullRequest := &api.PullRequest{
  170. ID: pr.ID,
  171. Index: pr.Index,
  172. Poster: apiIssue.Poster,
  173. Title: apiIssue.Title,
  174. Body: apiIssue.Body,
  175. Labels: apiIssue.Labels,
  176. Milestone: apiIssue.Milestone,
  177. Assignee: apiIssue.Assignee,
  178. State: apiIssue.State,
  179. Comments: apiIssue.Comments,
  180. HTMLURL: pr.Issue.HTMLURL(),
  181. DiffURL: pr.Issue.DiffURL(),
  182. PatchURL: pr.Issue.PatchURL(),
  183. HasMerged: pr.HasMerged,
  184. Base: apiBaseBranchInfo,
  185. Head: apiHeadBranchInfo,
  186. MergeBase: pr.MergeBase,
  187. Created: pr.Issue.CreatedUnix.AsTimePtr(),
  188. Updated: pr.Issue.UpdatedUnix.AsTimePtr(),
  189. }
  190. if pr.Status != PullRequestStatusChecking {
  191. mergeable := pr.Status != PullRequestStatusConflict
  192. apiPullRequest.Mergeable = mergeable
  193. }
  194. if pr.HasMerged {
  195. apiPullRequest.Merged = pr.MergedUnix.AsTimePtr()
  196. apiPullRequest.MergedCommitID = &pr.MergedCommitID
  197. apiPullRequest.MergedBy = pr.Merger.APIFormat()
  198. }
  199. return apiPullRequest
  200. }
  201. func (pr *PullRequest) getHeadRepo(e Engine) (err error) {
  202. pr.HeadRepo, err = getRepositoryByID(e, pr.HeadRepoID)
  203. if err != nil && !IsErrRepoNotExist(err) {
  204. return fmt.Errorf("getRepositoryByID(head): %v", err)
  205. }
  206. return nil
  207. }
  208. // GetHeadRepo loads the head repository
  209. func (pr *PullRequest) GetHeadRepo() error {
  210. return pr.getHeadRepo(x)
  211. }
  212. // GetBaseRepo loads the target repository
  213. func (pr *PullRequest) GetBaseRepo() (err error) {
  214. if pr.BaseRepo != nil {
  215. return nil
  216. }
  217. pr.BaseRepo, err = GetRepositoryByID(pr.BaseRepoID)
  218. if err != nil {
  219. return fmt.Errorf("GetRepositoryByID(base): %v", err)
  220. }
  221. return nil
  222. }
  223. // IsChecking returns true if this pull request is still checking conflict.
  224. func (pr *PullRequest) IsChecking() bool {
  225. return pr.Status == PullRequestStatusChecking
  226. }
  227. // CanAutoMerge returns true if this pull request can be merged automatically.
  228. func (pr *PullRequest) CanAutoMerge() bool {
  229. return pr.Status == PullRequestStatusMergeable
  230. }
  231. // MergeStyle represents the approach to merge commits into base branch.
  232. type MergeStyle string
  233. const (
  234. // MergeStyleMerge create merge commit
  235. MergeStyleMerge MergeStyle = "merge"
  236. // MergeStyleRebase rebase before merging
  237. MergeStyleRebase MergeStyle = "rebase"
  238. // MergeStyleSquash squash commits into single commit before merging
  239. MergeStyleSquash MergeStyle = "squash"
  240. )
  241. // CheckUserAllowedToMerge checks whether the user is allowed to merge
  242. func (pr *PullRequest) CheckUserAllowedToMerge(doer *User) (err error) {
  243. if doer == nil {
  244. return ErrNotAllowedToMerge{
  245. "Not signed in",
  246. }
  247. }
  248. if pr.BaseRepo == nil {
  249. if err = pr.GetBaseRepo(); err != nil {
  250. return fmt.Errorf("GetBaseRepo: %v", err)
  251. }
  252. }
  253. if protected, err := pr.BaseRepo.IsProtectedBranchForMerging(pr.BaseBranch, doer); err != nil {
  254. return fmt.Errorf("IsProtectedBranch: %v", err)
  255. } else if protected {
  256. return ErrNotAllowedToMerge{
  257. "The branch is protected",
  258. }
  259. }
  260. return nil
  261. }
  262. // Merge merges pull request to base repository.
  263. // FIXME: add repoWorkingPull make sure two merges does not happen at same time.
  264. func (pr *PullRequest) Merge(doer *User, baseGitRepo *git.Repository, mergeStyle MergeStyle, message string) (err error) {
  265. if err = pr.GetHeadRepo(); err != nil {
  266. return fmt.Errorf("GetHeadRepo: %v", err)
  267. } else if err = pr.GetBaseRepo(); err != nil {
  268. return fmt.Errorf("GetBaseRepo: %v", err)
  269. }
  270. prUnit, err := pr.BaseRepo.GetUnit(UnitTypePullRequests)
  271. if err != nil {
  272. return err
  273. }
  274. prConfig := prUnit.PullRequestsConfig()
  275. if err := pr.CheckUserAllowedToMerge(doer); err != nil {
  276. return fmt.Errorf("CheckUserAllowedToMerge: %v", err)
  277. }
  278. // Check if merge style is correct and allowed
  279. if !prConfig.IsMergeStyleAllowed(mergeStyle) {
  280. return ErrInvalidMergeStyle{pr.BaseRepo.ID, mergeStyle}
  281. }
  282. defer func() {
  283. go HookQueue.Add(pr.BaseRepo.ID)
  284. go AddTestPullRequestTask(doer, pr.BaseRepo.ID, pr.BaseBranch, false)
  285. }()
  286. headRepoPath := RepoPath(pr.HeadUserName, pr.HeadRepo.Name)
  287. // Clone base repo.
  288. tmpBasePath := path.Join(LocalCopyPath(), "merge-"+com.ToStr(time.Now().Nanosecond())+".git")
  289. if err := os.MkdirAll(path.Dir(tmpBasePath), os.ModePerm); err != nil {
  290. return fmt.Errorf("Failed to create dir %s: %v", tmpBasePath, err)
  291. }
  292. defer os.RemoveAll(path.Dir(tmpBasePath))
  293. var stderr string
  294. if _, stderr, err = process.GetManager().ExecTimeout(5*time.Minute,
  295. fmt.Sprintf("PullRequest.Merge (git clone): %s", tmpBasePath),
  296. "git", "clone", baseGitRepo.Path, tmpBasePath); err != nil {
  297. return fmt.Errorf("git clone: %s", stderr)
  298. }
  299. // Check out base branch.
  300. if _, stderr, err = process.GetManager().ExecDir(-1, tmpBasePath,
  301. fmt.Sprintf("PullRequest.Merge (git checkout): %s", tmpBasePath),
  302. "git", "checkout", pr.BaseBranch); err != nil {
  303. return fmt.Errorf("git checkout: %s", stderr)
  304. }
  305. // Add head repo remote.
  306. if _, stderr, err = process.GetManager().ExecDir(-1, tmpBasePath,
  307. fmt.Sprintf("PullRequest.Merge (git remote add): %s", tmpBasePath),
  308. "git", "remote", "add", "head_repo", headRepoPath); err != nil {
  309. return fmt.Errorf("git remote add [%s -> %s]: %s", headRepoPath, tmpBasePath, stderr)
  310. }
  311. // Merge commits.
  312. if _, stderr, err = process.GetManager().ExecDir(-1, tmpBasePath,
  313. fmt.Sprintf("PullRequest.Merge (git fetch): %s", tmpBasePath),
  314. "git", "fetch", "head_repo"); err != nil {
  315. return fmt.Errorf("git fetch [%s -> %s]: %s", headRepoPath, tmpBasePath, stderr)
  316. }
  317. switch mergeStyle {
  318. case MergeStyleMerge:
  319. if _, stderr, err = process.GetManager().ExecDir(-1, tmpBasePath,
  320. fmt.Sprintf("PullRequest.Merge (git merge --no-ff --no-commit): %s", tmpBasePath),
  321. "git", "merge", "--no-ff", "--no-commit", "head_repo/"+pr.HeadBranch); err != nil {
  322. return fmt.Errorf("git merge --no-ff --no-commit [%s]: %v - %s", tmpBasePath, err, stderr)
  323. }
  324. sig := doer.NewGitSig()
  325. if _, stderr, err = process.GetManager().ExecDir(-1, tmpBasePath,
  326. fmt.Sprintf("PullRequest.Merge (git merge): %s", tmpBasePath),
  327. "git", "commit", fmt.Sprintf("--author='%s <%s>'", sig.Name, sig.Email),
  328. "-m", message); err != nil {
  329. return fmt.Errorf("git commit [%s]: %v - %s", tmpBasePath, err, stderr)
  330. }
  331. case MergeStyleRebase:
  332. // Checkout head branch
  333. if _, stderr, err = process.GetManager().ExecDir(-1, tmpBasePath,
  334. fmt.Sprintf("PullRequest.Merge (git checkout): %s", tmpBasePath),
  335. "git", "checkout", "-b", "head_repo_"+pr.HeadBranch, "head_repo/"+pr.HeadBranch); err != nil {
  336. return fmt.Errorf("git checkout: %s", stderr)
  337. }
  338. // Rebase before merging
  339. if _, stderr, err = process.GetManager().ExecDir(-1, tmpBasePath,
  340. fmt.Sprintf("PullRequest.Merge (git rebase): %s", tmpBasePath),
  341. "git", "rebase", "-q", pr.BaseBranch); err != nil {
  342. return fmt.Errorf("git rebase [%s -> %s]: %s", headRepoPath, tmpBasePath, stderr)
  343. }
  344. // Checkout base branch again
  345. if _, stderr, err = process.GetManager().ExecDir(-1, tmpBasePath,
  346. fmt.Sprintf("PullRequest.Merge (git checkout): %s", tmpBasePath),
  347. "git", "checkout", pr.BaseBranch); err != nil {
  348. return fmt.Errorf("git checkout: %s", stderr)
  349. }
  350. // Merge fast forward
  351. if _, stderr, err = process.GetManager().ExecDir(-1, tmpBasePath,
  352. fmt.Sprintf("PullRequest.Merge (git rebase): %s", tmpBasePath),
  353. "git", "merge", "--ff-only", "-q", "head_repo_"+pr.HeadBranch); err != nil {
  354. return fmt.Errorf("git merge --ff-only [%s -> %s]: %s", headRepoPath, tmpBasePath, stderr)
  355. }
  356. case MergeStyleSquash:
  357. // Merge with squash
  358. if _, stderr, err = process.GetManager().ExecDir(-1, tmpBasePath,
  359. fmt.Sprintf("PullRequest.Merge (git squash): %s", tmpBasePath),
  360. "git", "merge", "-q", "--squash", "head_repo/"+pr.HeadBranch); err != nil {
  361. return fmt.Errorf("git merge --squash [%s -> %s]: %s", headRepoPath, tmpBasePath, stderr)
  362. }
  363. sig := pr.Issue.Poster.NewGitSig()
  364. if _, stderr, err = process.GetManager().ExecDir(-1, tmpBasePath,
  365. fmt.Sprintf("PullRequest.Merge (git squash): %s", tmpBasePath),
  366. "git", "commit", fmt.Sprintf("--author='%s <%s>'", sig.Name, sig.Email),
  367. "-m", message); err != nil {
  368. return fmt.Errorf("git commit [%s]: %v - %s", tmpBasePath, err, stderr)
  369. }
  370. default:
  371. return ErrInvalidMergeStyle{pr.BaseRepo.ID, mergeStyle}
  372. }
  373. // Push back to upstream.
  374. if _, stderr, err = process.GetManager().ExecDir(-1, tmpBasePath,
  375. fmt.Sprintf("PullRequest.Merge (git push): %s", tmpBasePath),
  376. "git", "push", baseGitRepo.Path, pr.BaseBranch); err != nil {
  377. return fmt.Errorf("git push: %s", stderr)
  378. }
  379. pr.MergedCommitID, err = baseGitRepo.GetBranchCommitID(pr.BaseBranch)
  380. if err != nil {
  381. return fmt.Errorf("GetBranchCommit: %v", err)
  382. }
  383. pr.MergedUnix = util.TimeStampNow()
  384. pr.Merger = doer
  385. pr.MergerID = doer.ID
  386. if err = pr.setMerged(); err != nil {
  387. log.Error(4, "setMerged [%d]: %v", pr.ID, err)
  388. }
  389. if err = MergePullRequestAction(doer, pr.Issue.Repo, pr.Issue); err != nil {
  390. log.Error(4, "MergePullRequestAction [%d]: %v", pr.ID, err)
  391. }
  392. // Reset cached commit count
  393. cache.Remove(pr.Issue.Repo.GetCommitsCountCacheKey(pr.BaseBranch, true))
  394. // Reload pull request information.
  395. if err = pr.LoadAttributes(); err != nil {
  396. log.Error(4, "LoadAttributes: %v", err)
  397. return nil
  398. }
  399. if err = PrepareWebhooks(pr.Issue.Repo, HookEventPullRequest, &api.PullRequestPayload{
  400. Action: api.HookIssueClosed,
  401. Index: pr.Index,
  402. PullRequest: pr.APIFormat(),
  403. Repository: pr.Issue.Repo.APIFormat(AccessModeNone),
  404. Sender: doer.APIFormat(),
  405. }); err != nil {
  406. log.Error(4, "PrepareWebhooks: %v", err)
  407. return nil
  408. }
  409. l, err := baseGitRepo.CommitsBetweenIDs(pr.MergedCommitID, pr.MergeBase)
  410. if err != nil {
  411. log.Error(4, "CommitsBetweenIDs: %v", err)
  412. return nil
  413. }
  414. // It is possible that head branch is not fully sync with base branch for merge commits,
  415. // so we need to get latest head commit and append merge commit manually
  416. // to avoid strange diff commits produced.
  417. mergeCommit, err := baseGitRepo.GetBranchCommit(pr.BaseBranch)
  418. if err != nil {
  419. log.Error(4, "GetBranchCommit: %v", err)
  420. return nil
  421. }
  422. if mergeStyle == MergeStyleMerge {
  423. l.PushFront(mergeCommit)
  424. }
  425. p := &api.PushPayload{
  426. Ref: git.BranchPrefix + pr.BaseBranch,
  427. Before: pr.MergeBase,
  428. After: mergeCommit.ID.String(),
  429. CompareURL: setting.AppURL + pr.BaseRepo.ComposeCompareURL(pr.MergeBase, pr.MergedCommitID),
  430. Commits: ListToPushCommits(l).ToAPIPayloadCommits(pr.BaseRepo.HTMLURL()),
  431. Repo: pr.BaseRepo.APIFormat(AccessModeNone),
  432. Pusher: pr.HeadRepo.MustOwner().APIFormat(),
  433. Sender: doer.APIFormat(),
  434. }
  435. if err = PrepareWebhooks(pr.BaseRepo, HookEventPush, p); err != nil {
  436. return fmt.Errorf("PrepareWebhooks: %v", err)
  437. }
  438. return nil
  439. }
  440. // setMerged sets a pull request to merged and closes the corresponding issue
  441. func (pr *PullRequest) setMerged() (err error) {
  442. if pr.HasMerged {
  443. return fmt.Errorf("PullRequest[%d] already merged", pr.Index)
  444. }
  445. if pr.MergedCommitID == "" || pr.MergedUnix == 0 || pr.Merger == nil {
  446. return fmt.Errorf("Unable to merge PullRequest[%d], some required fields are empty", pr.Index)
  447. }
  448. pr.HasMerged = true
  449. sess := x.NewSession()
  450. defer sess.Close()
  451. if err = sess.Begin(); err != nil {
  452. return err
  453. }
  454. if err = pr.loadIssue(sess); err != nil {
  455. return err
  456. }
  457. if err = pr.Issue.loadRepo(sess); err != nil {
  458. return err
  459. }
  460. if err = pr.Issue.Repo.getOwner(sess); err != nil {
  461. return err
  462. }
  463. if err = pr.Issue.changeStatus(sess, pr.Merger, pr.Issue.Repo, true); err != nil {
  464. return fmt.Errorf("Issue.changeStatus: %v", err)
  465. }
  466. if _, err = sess.ID(pr.ID).Cols("has_merged, status, merged_commit_id, merger_id, merged_unix").Update(pr); err != nil {
  467. return fmt.Errorf("update pull request: %v", err)
  468. }
  469. if err = sess.Commit(); err != nil {
  470. return fmt.Errorf("Commit: %v", err)
  471. }
  472. return nil
  473. }
  474. // manuallyMerged checks if a pull request got manually merged
  475. // When a pull request got manually merged mark the pull request as merged
  476. func (pr *PullRequest) manuallyMerged() bool {
  477. commit, err := pr.getMergeCommit()
  478. if err != nil {
  479. log.Error(4, "PullRequest[%d].getMergeCommit: %v", pr.ID, err)
  480. return false
  481. }
  482. if commit != nil {
  483. pr.MergedCommitID = commit.ID.String()
  484. pr.MergedUnix = util.TimeStamp(commit.Author.When.Unix())
  485. pr.Status = PullRequestStatusManuallyMerged
  486. merger, _ := GetUserByEmail(commit.Author.Email)
  487. // When the commit author is unknown set the BaseRepo owner as merger
  488. if merger == nil {
  489. if pr.BaseRepo.Owner == nil {
  490. if err = pr.BaseRepo.getOwner(x); err != nil {
  491. log.Error(4, "BaseRepo.getOwner[%d]: %v", pr.ID, err)
  492. return false
  493. }
  494. }
  495. merger = pr.BaseRepo.Owner
  496. }
  497. pr.Merger = merger
  498. pr.MergerID = merger.ID
  499. if err = pr.setMerged(); err != nil {
  500. log.Error(4, "PullRequest[%d].setMerged : %v", pr.ID, err)
  501. return false
  502. }
  503. 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())
  504. return true
  505. }
  506. return false
  507. }
  508. // getMergeCommit checks if a pull request got merged
  509. // Returns the git.Commit of the pull request if merged
  510. func (pr *PullRequest) getMergeCommit() (*git.Commit, error) {
  511. if pr.BaseRepo == nil {
  512. var err error
  513. pr.BaseRepo, err = GetRepositoryByID(pr.BaseRepoID)
  514. if err != nil {
  515. return nil, fmt.Errorf("GetRepositoryByID: %v", err)
  516. }
  517. }
  518. indexTmpPath := filepath.Join(os.TempDir(), "gitea-"+pr.BaseRepo.Name+"-"+strconv.Itoa(time.Now().Nanosecond()))
  519. defer os.Remove(indexTmpPath)
  520. headFile := pr.GetGitRefName()
  521. // Check if a pull request is merged into BaseBranch
  522. _, stderr, err := process.GetManager().ExecDirEnv(-1, "", fmt.Sprintf("isMerged (git merge-base --is-ancestor): %d", pr.BaseRepo.ID),
  523. []string{"GIT_INDEX_FILE=" + indexTmpPath, "GIT_DIR=" + pr.BaseRepo.RepoPath()},
  524. "git", "merge-base", "--is-ancestor", headFile, pr.BaseBranch)
  525. if err != nil {
  526. // Errors are signaled by a non-zero status that is not 1
  527. if strings.Contains(err.Error(), "exit status 1") {
  528. return nil, nil
  529. }
  530. return nil, fmt.Errorf("git merge-base --is-ancestor: %v %v", stderr, err)
  531. }
  532. commitIDBytes, err := ioutil.ReadFile(pr.BaseRepo.RepoPath() + "/" + headFile)
  533. if err != nil {
  534. return nil, fmt.Errorf("ReadFile(%s): %v", headFile, err)
  535. }
  536. commitID := string(commitIDBytes)
  537. if len(commitID) < 40 {
  538. return nil, fmt.Errorf(`ReadFile(%s): invalid commit-ID "%s"`, headFile, commitID)
  539. }
  540. cmd := commitID[:40] + ".." + pr.BaseBranch
  541. // Get the commit from BaseBranch where the pull request got merged
  542. mergeCommit, stderr, err := process.GetManager().ExecDirEnv(-1, "", fmt.Sprintf("isMerged (git rev-list --ancestry-path --merges --reverse): %d", pr.BaseRepo.ID),
  543. []string{"GIT_INDEX_FILE=" + indexTmpPath, "GIT_DIR=" + pr.BaseRepo.RepoPath()},
  544. "git", "rev-list", "--ancestry-path", "--merges", "--reverse", cmd)
  545. if err != nil {
  546. return nil, fmt.Errorf("git rev-list --ancestry-path --merges --reverse: %v %v", stderr, err)
  547. } else if len(mergeCommit) < 40 {
  548. // PR was fast-forwarded, so just use last commit of PR
  549. mergeCommit = commitID[:40]
  550. }
  551. gitRepo, err := git.OpenRepository(pr.BaseRepo.RepoPath())
  552. if err != nil {
  553. return nil, fmt.Errorf("OpenRepository: %v", err)
  554. }
  555. commit, err := gitRepo.GetCommit(mergeCommit[:40])
  556. if err != nil {
  557. return nil, fmt.Errorf("GetCommit: %v", err)
  558. }
  559. return commit, nil
  560. }
  561. // patchConflicts is a list of conflict description from Git.
  562. var patchConflicts = []string{
  563. "patch does not apply",
  564. "already exists in working directory",
  565. "unrecognized input",
  566. "error:",
  567. }
  568. // testPatch checks if patch can be merged to base repository without conflict.
  569. func (pr *PullRequest) testPatch() (err error) {
  570. if pr.BaseRepo == nil {
  571. pr.BaseRepo, err = GetRepositoryByID(pr.BaseRepoID)
  572. if err != nil {
  573. return fmt.Errorf("GetRepositoryByID: %v", err)
  574. }
  575. }
  576. patchPath, err := pr.BaseRepo.PatchPath(pr.Index)
  577. if err != nil {
  578. return fmt.Errorf("BaseRepo.PatchPath: %v", err)
  579. }
  580. // Fast fail if patch does not exist, this assumes data is corrupted.
  581. if !com.IsFile(patchPath) {
  582. log.Trace("PullRequest[%d].testPatch: ignored corrupted data", pr.ID)
  583. return nil
  584. }
  585. repoWorkingPool.CheckIn(com.ToStr(pr.BaseRepoID))
  586. defer repoWorkingPool.CheckOut(com.ToStr(pr.BaseRepoID))
  587. log.Trace("PullRequest[%d].testPatch (patchPath): %s", pr.ID, patchPath)
  588. pr.Status = PullRequestStatusChecking
  589. indexTmpPath := filepath.Join(os.TempDir(), "gitea-"+pr.BaseRepo.Name+"-"+strconv.Itoa(time.Now().Nanosecond()))
  590. defer os.Remove(indexTmpPath)
  591. var stderr string
  592. _, stderr, err = process.GetManager().ExecDirEnv(-1, "", fmt.Sprintf("testPatch (git read-tree): %d", pr.BaseRepo.ID),
  593. []string{"GIT_DIR=" + pr.BaseRepo.RepoPath(), "GIT_INDEX_FILE=" + indexTmpPath},
  594. "git", "read-tree", pr.BaseBranch)
  595. if err != nil {
  596. return fmt.Errorf("git read-tree --index-output=%s %s: %v - %s", indexTmpPath, pr.BaseBranch, err, stderr)
  597. }
  598. prUnit, err := pr.BaseRepo.GetUnit(UnitTypePullRequests)
  599. if err != nil {
  600. return err
  601. }
  602. prConfig := prUnit.PullRequestsConfig()
  603. args := []string{"apply", "--check", "--cached"}
  604. if prConfig.IgnoreWhitespaceConflicts {
  605. args = append(args, "--ignore-whitespace")
  606. }
  607. args = append(args, patchPath)
  608. _, stderr, err = process.GetManager().ExecDirEnv(-1, "", fmt.Sprintf("testPatch (git apply --check): %d", pr.BaseRepo.ID),
  609. []string{"GIT_INDEX_FILE=" + indexTmpPath, "GIT_DIR=" + pr.BaseRepo.RepoPath()},
  610. "git", args...)
  611. if err != nil {
  612. for i := range patchConflicts {
  613. if strings.Contains(stderr, patchConflicts[i]) {
  614. log.Trace("PullRequest[%d].testPatch (apply): has conflict", pr.ID)
  615. fmt.Println(stderr)
  616. pr.Status = PullRequestStatusConflict
  617. return nil
  618. }
  619. }
  620. return fmt.Errorf("git apply --check: %v - %s", err, stderr)
  621. }
  622. return nil
  623. }
  624. // NewPullRequest creates new pull request with labels for repository.
  625. func NewPullRequest(repo *Repository, pull *Issue, labelIDs []int64, uuids []string, pr *PullRequest, patch []byte) (err error) {
  626. sess := x.NewSession()
  627. defer sess.Close()
  628. if err = sess.Begin(); err != nil {
  629. return err
  630. }
  631. if err = newIssue(sess, pull.Poster, NewIssueOptions{
  632. Repo: repo,
  633. Issue: pull,
  634. LabelIDs: labelIDs,
  635. Attachments: uuids,
  636. IsPull: true,
  637. }); err != nil {
  638. return fmt.Errorf("newIssue: %v", err)
  639. }
  640. pr.Index = pull.Index
  641. if err = repo.SavePatch(pr.Index, patch); err != nil {
  642. return fmt.Errorf("SavePatch: %v", err)
  643. }
  644. pr.BaseRepo = repo
  645. if err = pr.testPatch(); err != nil {
  646. return fmt.Errorf("testPatch: %v", err)
  647. }
  648. // No conflict appears after test means mergeable.
  649. if pr.Status == PullRequestStatusChecking {
  650. pr.Status = PullRequestStatusMergeable
  651. }
  652. pr.IssueID = pull.ID
  653. if _, err = sess.Insert(pr); err != nil {
  654. return fmt.Errorf("insert pull repo: %v", err)
  655. }
  656. if err = sess.Commit(); err != nil {
  657. return fmt.Errorf("Commit: %v", err)
  658. }
  659. UpdateIssueIndexer(pull.ID)
  660. if err = NotifyWatchers(&Action{
  661. ActUserID: pull.Poster.ID,
  662. ActUser: pull.Poster,
  663. OpType: ActionCreatePullRequest,
  664. Content: fmt.Sprintf("%d|%s", pull.Index, pull.Title),
  665. RepoID: repo.ID,
  666. Repo: repo,
  667. IsPrivate: repo.IsPrivate,
  668. }); err != nil {
  669. log.Error(4, "NotifyWatchers: %v", err)
  670. } else if err = pull.MailParticipants(); err != nil {
  671. log.Error(4, "MailParticipants: %v", err)
  672. }
  673. pr.Issue = pull
  674. pull.PullRequest = pr
  675. if err = PrepareWebhooks(repo, HookEventPullRequest, &api.PullRequestPayload{
  676. Action: api.HookIssueOpened,
  677. Index: pull.Index,
  678. PullRequest: pr.APIFormat(),
  679. Repository: repo.APIFormat(AccessModeNone),
  680. Sender: pull.Poster.APIFormat(),
  681. }); err != nil {
  682. log.Error(4, "PrepareWebhooks: %v", err)
  683. }
  684. go HookQueue.Add(repo.ID)
  685. return nil
  686. }
  687. // PullRequestsOptions holds the options for PRs
  688. type PullRequestsOptions struct {
  689. Page int
  690. State string
  691. SortType string
  692. Labels []string
  693. MilestoneID int64
  694. }
  695. func listPullRequestStatement(baseRepoID int64, opts *PullRequestsOptions) (*xorm.Session, error) {
  696. sess := x.Where("pull_request.base_repo_id=?", baseRepoID)
  697. sess.Join("INNER", "issue", "pull_request.issue_id = issue.id")
  698. switch opts.State {
  699. case "closed", "open":
  700. sess.And("issue.is_closed=?", opts.State == "closed")
  701. }
  702. if labelIDs, err := base.StringsToInt64s(opts.Labels); err != nil {
  703. return nil, err
  704. } else if len(labelIDs) > 0 {
  705. sess.Join("INNER", "issue_label", "issue.id = issue_label.issue_id").
  706. In("issue_label.label_id", labelIDs)
  707. }
  708. if opts.MilestoneID > 0 {
  709. sess.And("issue.milestone_id=?", opts.MilestoneID)
  710. }
  711. return sess, nil
  712. }
  713. // PullRequests returns all pull requests for a base Repo by the given conditions
  714. func PullRequests(baseRepoID int64, opts *PullRequestsOptions) ([]*PullRequest, int64, error) {
  715. if opts.Page <= 0 {
  716. opts.Page = 1
  717. }
  718. countSession, err := listPullRequestStatement(baseRepoID, opts)
  719. if err != nil {
  720. log.Error(4, "listPullRequestStatement", err)
  721. return nil, 0, err
  722. }
  723. maxResults, err := countSession.Count(new(PullRequest))
  724. if err != nil {
  725. log.Error(4, "Count PRs", err)
  726. return nil, maxResults, err
  727. }
  728. prs := make([]*PullRequest, 0, ItemsPerPage)
  729. findSession, err := listPullRequestStatement(baseRepoID, opts)
  730. sortIssuesSession(findSession, opts.SortType)
  731. if err != nil {
  732. log.Error(4, "listPullRequestStatement", err)
  733. return nil, maxResults, err
  734. }
  735. findSession.Limit(ItemsPerPage, (opts.Page-1)*ItemsPerPage)
  736. return prs, maxResults, findSession.Find(&prs)
  737. }
  738. // GetUnmergedPullRequest returns a pull request that is open and has not been merged
  739. // by given head/base and repo/branch.
  740. func GetUnmergedPullRequest(headRepoID, baseRepoID int64, headBranch, baseBranch string) (*PullRequest, error) {
  741. pr := new(PullRequest)
  742. has, err := x.
  743. Where("head_repo_id=? AND head_branch=? AND base_repo_id=? AND base_branch=? AND has_merged=? AND issue.is_closed=?",
  744. headRepoID, headBranch, baseRepoID, baseBranch, false, false).
  745. Join("INNER", "issue", "issue.id=pull_request.issue_id").
  746. Get(pr)
  747. if err != nil {
  748. return nil, err
  749. } else if !has {
  750. return nil, ErrPullRequestNotExist{0, 0, headRepoID, baseRepoID, headBranch, baseBranch}
  751. }
  752. return pr, nil
  753. }
  754. // GetUnmergedPullRequestsByHeadInfo returns all pull requests that are open and has not been merged
  755. // by given head information (repo and branch).
  756. func GetUnmergedPullRequestsByHeadInfo(repoID int64, branch string) ([]*PullRequest, error) {
  757. prs := make([]*PullRequest, 0, 2)
  758. return prs, x.
  759. Where("head_repo_id = ? AND head_branch = ? AND has_merged = ? AND issue.is_closed = ?",
  760. repoID, branch, false, false).
  761. Join("INNER", "issue", "issue.id = pull_request.issue_id").
  762. Find(&prs)
  763. }
  764. // GetUnmergedPullRequestsByBaseInfo returns all pull requests that are open and has not been merged
  765. // by given base information (repo and branch).
  766. func GetUnmergedPullRequestsByBaseInfo(repoID int64, branch string) ([]*PullRequest, error) {
  767. prs := make([]*PullRequest, 0, 2)
  768. return prs, x.
  769. Where("base_repo_id=? AND base_branch=? AND has_merged=? AND issue.is_closed=?",
  770. repoID, branch, false, false).
  771. Join("INNER", "issue", "issue.id=pull_request.issue_id").
  772. Find(&prs)
  773. }
  774. // GetPullRequestByIndex returns a pull request by the given index
  775. func GetPullRequestByIndex(repoID int64, index int64) (*PullRequest, error) {
  776. pr := &PullRequest{
  777. BaseRepoID: repoID,
  778. Index: index,
  779. }
  780. has, err := x.Get(pr)
  781. if err != nil {
  782. return nil, err
  783. } else if !has {
  784. return nil, ErrPullRequestNotExist{0, 0, 0, repoID, "", ""}
  785. }
  786. if err = pr.LoadAttributes(); err != nil {
  787. return nil, err
  788. }
  789. if err = pr.LoadIssue(); err != nil {
  790. return nil, err
  791. }
  792. return pr, nil
  793. }
  794. func getPullRequestByID(e Engine, id int64) (*PullRequest, error) {
  795. pr := new(PullRequest)
  796. has, err := e.ID(id).Get(pr)
  797. if err != nil {
  798. return nil, err
  799. } else if !has {
  800. return nil, ErrPullRequestNotExist{id, 0, 0, 0, "", ""}
  801. }
  802. return pr, pr.loadAttributes(e)
  803. }
  804. // GetPullRequestByID returns a pull request by given ID.
  805. func GetPullRequestByID(id int64) (*PullRequest, error) {
  806. return getPullRequestByID(x, id)
  807. }
  808. func getPullRequestByIssueID(e Engine, issueID int64) (*PullRequest, error) {
  809. pr := &PullRequest{
  810. IssueID: issueID,
  811. }
  812. has, err := e.Get(pr)
  813. if err != nil {
  814. return nil, err
  815. } else if !has {
  816. return nil, ErrPullRequestNotExist{0, issueID, 0, 0, "", ""}
  817. }
  818. return pr, pr.loadAttributes(e)
  819. }
  820. // GetPullRequestByIssueID returns pull request by given issue ID.
  821. func GetPullRequestByIssueID(issueID int64) (*PullRequest, error) {
  822. return getPullRequestByIssueID(x, issueID)
  823. }
  824. // Update updates all fields of pull request.
  825. func (pr *PullRequest) Update() error {
  826. _, err := x.ID(pr.ID).AllCols().Update(pr)
  827. return err
  828. }
  829. // UpdateCols updates specific fields of pull request.
  830. func (pr *PullRequest) UpdateCols(cols ...string) error {
  831. _, err := x.ID(pr.ID).Cols(cols...).Update(pr)
  832. return err
  833. }
  834. // UpdatePatch generates and saves a new patch.
  835. func (pr *PullRequest) UpdatePatch() (err error) {
  836. if err = pr.GetHeadRepo(); err != nil {
  837. return fmt.Errorf("GetHeadRepo: %v", err)
  838. } else if pr.HeadRepo == nil {
  839. log.Trace("PullRequest[%d].UpdatePatch: ignored cruppted data", pr.ID)
  840. return nil
  841. }
  842. if err = pr.GetBaseRepo(); err != nil {
  843. return fmt.Errorf("GetBaseRepo: %v", err)
  844. }
  845. headGitRepo, err := git.OpenRepository(pr.HeadRepo.RepoPath())
  846. if err != nil {
  847. return fmt.Errorf("OpenRepository: %v", err)
  848. }
  849. // Add a temporary remote.
  850. tmpRemote := com.ToStr(time.Now().UnixNano())
  851. if err = headGitRepo.AddRemote(tmpRemote, RepoPath(pr.BaseRepo.MustOwner().Name, pr.BaseRepo.Name), true); err != nil {
  852. return fmt.Errorf("AddRemote: %v", err)
  853. }
  854. defer func() {
  855. headGitRepo.RemoveRemote(tmpRemote)
  856. }()
  857. remoteBranch := "remotes/" + tmpRemote + "/" + pr.BaseBranch
  858. pr.MergeBase, err = headGitRepo.GetMergeBase(remoteBranch, pr.HeadBranch)
  859. if err != nil {
  860. return fmt.Errorf("GetMergeBase: %v", err)
  861. } else if err = pr.Update(); err != nil {
  862. return fmt.Errorf("Update: %v", err)
  863. }
  864. patch, err := headGitRepo.GetPatch(pr.MergeBase, pr.HeadBranch)
  865. if err != nil {
  866. return fmt.Errorf("GetPatch: %v", err)
  867. }
  868. if err = pr.BaseRepo.SavePatch(pr.Index, patch); err != nil {
  869. return fmt.Errorf("BaseRepo.SavePatch: %v", err)
  870. }
  871. return nil
  872. }
  873. // PushToBaseRepo pushes commits from branches of head repository to
  874. // corresponding branches of base repository.
  875. // FIXME: Only push branches that are actually updates?
  876. func (pr *PullRequest) PushToBaseRepo() (err error) {
  877. log.Trace("PushToBaseRepo[%d]: pushing commits to base repo '%s'", pr.BaseRepoID, pr.GetGitRefName())
  878. headRepoPath := pr.HeadRepo.RepoPath()
  879. headGitRepo, err := git.OpenRepository(headRepoPath)
  880. if err != nil {
  881. return fmt.Errorf("OpenRepository: %v", err)
  882. }
  883. tmpRemoteName := fmt.Sprintf("tmp-pull-%d", pr.ID)
  884. if err = headGitRepo.AddRemote(tmpRemoteName, pr.BaseRepo.RepoPath(), false); err != nil {
  885. return fmt.Errorf("headGitRepo.AddRemote: %v", err)
  886. }
  887. // Make sure to remove the remote even if the push fails
  888. defer headGitRepo.RemoveRemote(tmpRemoteName)
  889. headFile := pr.GetGitRefName()
  890. // Remove head in case there is a conflict.
  891. file := path.Join(pr.BaseRepo.RepoPath(), headFile)
  892. _ = os.Remove(file)
  893. if err = git.Push(headRepoPath, git.PushOptions{
  894. Remote: tmpRemoteName,
  895. Branch: fmt.Sprintf("%s:%s", pr.HeadBranch, headFile),
  896. Force: true,
  897. }); err != nil {
  898. return fmt.Errorf("Push: %v", err)
  899. }
  900. return nil
  901. }
  902. // AddToTaskQueue adds itself to pull request test task queue.
  903. func (pr *PullRequest) AddToTaskQueue() {
  904. go pullRequestQueue.AddFunc(pr.ID, func() {
  905. pr.Status = PullRequestStatusChecking
  906. if err := pr.UpdateCols("status"); err != nil {
  907. log.Error(5, "AddToTaskQueue.UpdateCols[%d].(add to queue): %v", pr.ID, err)
  908. }
  909. })
  910. }
  911. // PullRequestList defines a list of pull requests
  912. type PullRequestList []*PullRequest
  913. func (prs PullRequestList) loadAttributes(e Engine) error {
  914. if len(prs) == 0 {
  915. return nil
  916. }
  917. // Load issues.
  918. issueIDs := make([]int64, 0, len(prs))
  919. for i := range prs {
  920. issueIDs = append(issueIDs, prs[i].IssueID)
  921. }
  922. issues := make([]*Issue, 0, len(issueIDs))
  923. if err := e.
  924. Where("id > 0").
  925. In("id", issueIDs).
  926. Find(&issues); err != nil {
  927. return fmt.Errorf("find issues: %v", err)
  928. }
  929. set := make(map[int64]*Issue)
  930. for i := range issues {
  931. set[issues[i].ID] = issues[i]
  932. }
  933. for i := range prs {
  934. prs[i].Issue = set[prs[i].IssueID]
  935. }
  936. return nil
  937. }
  938. // LoadAttributes load all the prs attributes
  939. func (prs PullRequestList) LoadAttributes() error {
  940. return prs.loadAttributes(x)
  941. }
  942. func addHeadRepoTasks(prs []*PullRequest) {
  943. for _, pr := range prs {
  944. log.Trace("addHeadRepoTasks[%d]: composing new test task", pr.ID)
  945. if err := pr.UpdatePatch(); err != nil {
  946. log.Error(4, "UpdatePatch: %v", err)
  947. continue
  948. } else if err := pr.PushToBaseRepo(); err != nil {
  949. log.Error(4, "PushToBaseRepo: %v", err)
  950. continue
  951. }
  952. pr.AddToTaskQueue()
  953. }
  954. }
  955. // AddTestPullRequestTask adds new test tasks by given head/base repository and head/base branch,
  956. // and generate new patch for testing as needed.
  957. func AddTestPullRequestTask(doer *User, repoID int64, branch string, isSync bool) {
  958. log.Trace("AddTestPullRequestTask [head_repo_id: %d, head_branch: %s]: finding pull requests", repoID, branch)
  959. prs, err := GetUnmergedPullRequestsByHeadInfo(repoID, branch)
  960. if err != nil {
  961. log.Error(4, "Find pull requests [head_repo_id: %d, head_branch: %s]: %v", repoID, branch, err)
  962. return
  963. }
  964. if isSync {
  965. if err = PullRequestList(prs).LoadAttributes(); err != nil {
  966. log.Error(4, "PullRequestList.LoadAttributes: %v", err)
  967. }
  968. if err == nil {
  969. for _, pr := range prs {
  970. pr.Issue.PullRequest = pr
  971. if err = pr.Issue.LoadAttributes(); err != nil {
  972. log.Error(4, "LoadAttributes: %v", err)
  973. continue
  974. }
  975. if err = PrepareWebhooks(pr.Issue.Repo, HookEventPullRequest, &api.PullRequestPayload{
  976. Action: api.HookIssueSynchronized,
  977. Index: pr.Issue.Index,
  978. PullRequest: pr.Issue.PullRequest.APIFormat(),
  979. Repository: pr.Issue.Repo.APIFormat(AccessModeNone),
  980. Sender: doer.APIFormat(),
  981. }); err != nil {
  982. log.Error(4, "PrepareWebhooks [pull_id: %v]: %v", pr.ID, err)
  983. continue
  984. }
  985. go HookQueue.Add(pr.Issue.Repo.ID)
  986. }
  987. }
  988. }
  989. addHeadRepoTasks(prs)
  990. log.Trace("AddTestPullRequestTask [base_repo_id: %d, base_branch: %s]: finding pull requests", repoID, branch)
  991. prs, err = GetUnmergedPullRequestsByBaseInfo(repoID, branch)
  992. if err != nil {
  993. log.Error(4, "Find pull requests [base_repo_id: %d, base_branch: %s]: %v", repoID, branch, err)
  994. return
  995. }
  996. for _, pr := range prs {
  997. pr.AddToTaskQueue()
  998. }
  999. }
  1000. // ChangeUsernameInPullRequests changes the name of head_user_name
  1001. func ChangeUsernameInPullRequests(oldUserName, newUserName string) error {
  1002. pr := PullRequest{
  1003. HeadUserName: strings.ToLower(newUserName),
  1004. }
  1005. _, err := x.
  1006. Cols("head_user_name").
  1007. Where("head_user_name = ?", strings.ToLower(oldUserName)).
  1008. Update(pr)
  1009. return err
  1010. }
  1011. // checkAndUpdateStatus checks if pull request is possible to leaving checking status,
  1012. // and set to be either conflict or mergeable.
  1013. func (pr *PullRequest) checkAndUpdateStatus() {
  1014. // Status is not changed to conflict means mergeable.
  1015. if pr.Status == PullRequestStatusChecking {
  1016. pr.Status = PullRequestStatusMergeable
  1017. }
  1018. // Make sure there is no waiting test to process before leaving the checking status.
  1019. if !pullRequestQueue.Exist(pr.ID) {
  1020. if err := pr.UpdateCols("status"); err != nil {
  1021. log.Error(4, "Update[%d]: %v", pr.ID, err)
  1022. }
  1023. }
  1024. }
  1025. // TestPullRequests checks and tests untested patches of pull requests.
  1026. // TODO: test more pull requests at same time.
  1027. func TestPullRequests() {
  1028. prs := make([]*PullRequest, 0, 10)
  1029. err := x.Where("status = ?", PullRequestStatusChecking).Find(&prs)
  1030. if err != nil {
  1031. log.Error(3, "Find Checking PRs", err)
  1032. return
  1033. }
  1034. var checkedPRs = make(map[int64]struct{})
  1035. // Update pull request status.
  1036. for _, pr := range prs {
  1037. checkedPRs[pr.ID] = struct{}{}
  1038. if err := pr.GetBaseRepo(); err != nil {
  1039. log.Error(3, "GetBaseRepo: %v", err)
  1040. continue
  1041. }
  1042. if pr.manuallyMerged() {
  1043. continue
  1044. }
  1045. if err := pr.testPatch(); err != nil {
  1046. log.Error(3, "testPatch: %v", err)
  1047. continue
  1048. }
  1049. pr.checkAndUpdateStatus()
  1050. }
  1051. // Start listening on new test requests.
  1052. for prID := range pullRequestQueue.Queue() {
  1053. log.Trace("TestPullRequests[%v]: processing test task", prID)
  1054. pullRequestQueue.Remove(prID)
  1055. id := com.StrTo(prID).MustInt64()
  1056. if _, ok := checkedPRs[id]; ok {
  1057. continue
  1058. }
  1059. pr, err := GetPullRequestByID(id)
  1060. if err != nil {
  1061. log.Error(4, "GetPullRequestByID[%s]: %v", prID, err)
  1062. continue
  1063. } else if pr.manuallyMerged() {
  1064. continue
  1065. } else if err = pr.testPatch(); err != nil {
  1066. log.Error(4, "testPatch[%d]: %v", pr.ID, err)
  1067. continue
  1068. }
  1069. pr.checkAndUpdateStatus()
  1070. }
  1071. }
  1072. // InitTestPullRequests runs the task to test all the checking status pull requests
  1073. func InitTestPullRequests() {
  1074. go TestPullRequests()
  1075. }