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.

pull.go 38 kB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
9 years ago
9 years ago
9 years ago
10 years ago
10 years ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219
  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. // Merge merges pull request to base repository.
  242. // FIXME: add repoWorkingPull make sure two merges does not happen at same time.
  243. func (pr *PullRequest) Merge(doer *User, baseGitRepo *git.Repository, mergeStyle MergeStyle, message string) (err error) {
  244. if err = pr.GetHeadRepo(); err != nil {
  245. return fmt.Errorf("GetHeadRepo: %v", err)
  246. } else if err = pr.GetBaseRepo(); err != nil {
  247. return fmt.Errorf("GetBaseRepo: %v", err)
  248. }
  249. prUnit, err := pr.BaseRepo.GetUnit(UnitTypePullRequests)
  250. if err != nil {
  251. return err
  252. }
  253. prConfig := prUnit.PullRequestsConfig()
  254. // Check if merge style is correct and allowed
  255. if !prConfig.IsMergeStyleAllowed(mergeStyle) {
  256. return ErrInvalidMergeStyle{pr.BaseRepo.ID, mergeStyle}
  257. }
  258. defer func() {
  259. go HookQueue.Add(pr.BaseRepo.ID)
  260. go AddTestPullRequestTask(doer, pr.BaseRepo.ID, pr.BaseBranch, false)
  261. }()
  262. headRepoPath := RepoPath(pr.HeadUserName, pr.HeadRepo.Name)
  263. headGitRepo, err := git.OpenRepository(headRepoPath)
  264. if err != nil {
  265. return fmt.Errorf("OpenRepository: %v", err)
  266. }
  267. // Clone base repo.
  268. tmpBasePath := path.Join(LocalCopyPath(), "merge-"+com.ToStr(time.Now().Nanosecond())+".git")
  269. if err := os.MkdirAll(path.Dir(tmpBasePath), os.ModePerm); err != nil {
  270. return fmt.Errorf("Failed to create dir %s: %v", tmpBasePath, err)
  271. }
  272. defer os.RemoveAll(path.Dir(tmpBasePath))
  273. var stderr string
  274. if _, stderr, err = process.GetManager().ExecTimeout(5*time.Minute,
  275. fmt.Sprintf("PullRequest.Merge (git clone): %s", tmpBasePath),
  276. "git", "clone", baseGitRepo.Path, tmpBasePath); err != nil {
  277. return fmt.Errorf("git clone: %s", stderr)
  278. }
  279. // Check out base branch.
  280. if _, stderr, err = process.GetManager().ExecDir(-1, tmpBasePath,
  281. fmt.Sprintf("PullRequest.Merge (git checkout): %s", tmpBasePath),
  282. "git", "checkout", pr.BaseBranch); err != nil {
  283. return fmt.Errorf("git checkout: %s", stderr)
  284. }
  285. // Add head repo remote.
  286. if _, stderr, err = process.GetManager().ExecDir(-1, tmpBasePath,
  287. fmt.Sprintf("PullRequest.Merge (git remote add): %s", tmpBasePath),
  288. "git", "remote", "add", "head_repo", headRepoPath); err != nil {
  289. return fmt.Errorf("git remote add [%s -> %s]: %s", headRepoPath, tmpBasePath, stderr)
  290. }
  291. // Merge commits.
  292. if _, stderr, err = process.GetManager().ExecDir(-1, tmpBasePath,
  293. fmt.Sprintf("PullRequest.Merge (git fetch): %s", tmpBasePath),
  294. "git", "fetch", "head_repo"); err != nil {
  295. return fmt.Errorf("git fetch [%s -> %s]: %s", headRepoPath, tmpBasePath, stderr)
  296. }
  297. switch mergeStyle {
  298. case MergeStyleMerge:
  299. if _, stderr, err = process.GetManager().ExecDir(-1, tmpBasePath,
  300. fmt.Sprintf("PullRequest.Merge (git merge --no-ff --no-commit): %s", tmpBasePath),
  301. "git", "merge", "--no-ff", "--no-commit", "head_repo/"+pr.HeadBranch); err != nil {
  302. return fmt.Errorf("git merge --no-ff --no-commit [%s]: %v - %s", tmpBasePath, err, stderr)
  303. }
  304. sig := doer.NewGitSig()
  305. if _, stderr, err = process.GetManager().ExecDir(-1, tmpBasePath,
  306. fmt.Sprintf("PullRequest.Merge (git merge): %s", tmpBasePath),
  307. "git", "commit", fmt.Sprintf("--author='%s <%s>'", sig.Name, sig.Email),
  308. "-m", message); err != nil {
  309. return fmt.Errorf("git commit [%s]: %v - %s", tmpBasePath, err, stderr)
  310. }
  311. case MergeStyleRebase:
  312. // Checkout head branch
  313. if _, stderr, err = process.GetManager().ExecDir(-1, tmpBasePath,
  314. fmt.Sprintf("PullRequest.Merge (git checkout): %s", tmpBasePath),
  315. "git", "checkout", "-b", "head_repo_"+pr.HeadBranch, "head_repo/"+pr.HeadBranch); err != nil {
  316. return fmt.Errorf("git checkout: %s", stderr)
  317. }
  318. // Rebase before merging
  319. if _, stderr, err = process.GetManager().ExecDir(-1, tmpBasePath,
  320. fmt.Sprintf("PullRequest.Merge (git rebase): %s", tmpBasePath),
  321. "git", "rebase", "-q", pr.BaseBranch); err != nil {
  322. return fmt.Errorf("git rebase [%s -> %s]: %s", headRepoPath, tmpBasePath, stderr)
  323. }
  324. // Checkout base branch again
  325. if _, stderr, err = process.GetManager().ExecDir(-1, tmpBasePath,
  326. fmt.Sprintf("PullRequest.Merge (git checkout): %s", tmpBasePath),
  327. "git", "checkout", pr.BaseBranch); err != nil {
  328. return fmt.Errorf("git checkout: %s", stderr)
  329. }
  330. // Merge fast forward
  331. if _, stderr, err = process.GetManager().ExecDir(-1, tmpBasePath,
  332. fmt.Sprintf("PullRequest.Merge (git rebase): %s", tmpBasePath),
  333. "git", "merge", "--ff-only", "-q", "head_repo_"+pr.HeadBranch); err != nil {
  334. return fmt.Errorf("git merge --ff-only [%s -> %s]: %s", headRepoPath, tmpBasePath, stderr)
  335. }
  336. case MergeStyleSquash:
  337. // Merge with squash
  338. if _, stderr, err = process.GetManager().ExecDir(-1, tmpBasePath,
  339. fmt.Sprintf("PullRequest.Merge (git squash): %s", tmpBasePath),
  340. "git", "merge", "-q", "--squash", "head_repo/"+pr.HeadBranch); err != nil {
  341. return fmt.Errorf("git merge --squash [%s -> %s]: %s", headRepoPath, tmpBasePath, stderr)
  342. }
  343. sig := pr.Issue.Poster.NewGitSig()
  344. if _, stderr, err = process.GetManager().ExecDir(-1, tmpBasePath,
  345. fmt.Sprintf("PullRequest.Merge (git squash): %s", tmpBasePath),
  346. "git", "commit", fmt.Sprintf("--author='%s <%s>'", sig.Name, sig.Email),
  347. "-m", message); err != nil {
  348. return fmt.Errorf("git commit [%s]: %v - %s", tmpBasePath, err, stderr)
  349. }
  350. default:
  351. return ErrInvalidMergeStyle{pr.BaseRepo.ID, mergeStyle}
  352. }
  353. // Push back to upstream.
  354. if _, stderr, err = process.GetManager().ExecDir(-1, tmpBasePath,
  355. fmt.Sprintf("PullRequest.Merge (git push): %s", tmpBasePath),
  356. "git", "push", baseGitRepo.Path, pr.BaseBranch); err != nil {
  357. return fmt.Errorf("git push: %s", stderr)
  358. }
  359. pr.MergedCommitID, err = baseGitRepo.GetBranchCommitID(pr.BaseBranch)
  360. if err != nil {
  361. return fmt.Errorf("GetBranchCommit: %v", err)
  362. }
  363. pr.MergedUnix = util.TimeStampNow()
  364. pr.Merger = doer
  365. pr.MergerID = doer.ID
  366. if err = pr.setMerged(); err != nil {
  367. log.Error(4, "setMerged [%d]: %v", pr.ID, err)
  368. }
  369. if err = MergePullRequestAction(doer, pr.Issue.Repo, pr.Issue); err != nil {
  370. log.Error(4, "MergePullRequestAction [%d]: %v", pr.ID, err)
  371. }
  372. // Reset cached commit count
  373. cache.Remove(pr.Issue.Repo.GetCommitsCountCacheKey(pr.BaseBranch, true))
  374. // Reload pull request information.
  375. if err = pr.LoadAttributes(); err != nil {
  376. log.Error(4, "LoadAttributes: %v", err)
  377. return nil
  378. }
  379. if err = PrepareWebhooks(pr.Issue.Repo, HookEventPullRequest, &api.PullRequestPayload{
  380. Action: api.HookIssueClosed,
  381. Index: pr.Index,
  382. PullRequest: pr.APIFormat(),
  383. Repository: pr.Issue.Repo.APIFormat(AccessModeNone),
  384. Sender: doer.APIFormat(),
  385. }); err != nil {
  386. log.Error(4, "PrepareWebhooks: %v", err)
  387. return nil
  388. }
  389. l, err := headGitRepo.CommitsBetweenIDs(pr.MergedCommitID, pr.MergeBase)
  390. if err != nil {
  391. log.Error(4, "CommitsBetweenIDs: %v", err)
  392. return nil
  393. }
  394. // It is possible that head branch is not fully sync with base branch for merge commits,
  395. // so we need to get latest head commit and append merge commit manually
  396. // to avoid strange diff commits produced.
  397. mergeCommit, err := baseGitRepo.GetBranchCommit(pr.BaseBranch)
  398. if err != nil {
  399. log.Error(4, "GetBranchCommit: %v", err)
  400. return nil
  401. }
  402. if mergeStyle == MergeStyleMerge {
  403. l.PushFront(mergeCommit)
  404. }
  405. p := &api.PushPayload{
  406. Ref: git.BranchPrefix + pr.BaseBranch,
  407. Before: pr.MergeBase,
  408. After: mergeCommit.ID.String(),
  409. CompareURL: setting.AppURL + pr.BaseRepo.ComposeCompareURL(pr.MergeBase, pr.MergedCommitID),
  410. Commits: ListToPushCommits(l).ToAPIPayloadCommits(pr.BaseRepo.HTMLURL()),
  411. Repo: pr.BaseRepo.APIFormat(AccessModeNone),
  412. Pusher: pr.HeadRepo.MustOwner().APIFormat(),
  413. Sender: doer.APIFormat(),
  414. }
  415. if err = PrepareWebhooks(pr.BaseRepo, HookEventPush, p); err != nil {
  416. return fmt.Errorf("PrepareWebhooks: %v", err)
  417. }
  418. return nil
  419. }
  420. // setMerged sets a pull request to merged and closes the corresponding issue
  421. func (pr *PullRequest) setMerged() (err error) {
  422. if pr.HasMerged {
  423. return fmt.Errorf("PullRequest[%d] already merged", pr.Index)
  424. }
  425. if pr.MergedCommitID == "" || pr.MergedUnix == 0 || pr.Merger == nil {
  426. return fmt.Errorf("Unable to merge PullRequest[%d], some required fields are empty", pr.Index)
  427. }
  428. pr.HasMerged = true
  429. sess := x.NewSession()
  430. defer sess.Close()
  431. if err = sess.Begin(); err != nil {
  432. return err
  433. }
  434. if err = pr.loadIssue(sess); err != nil {
  435. return err
  436. }
  437. if err = pr.Issue.loadRepo(sess); err != nil {
  438. return err
  439. }
  440. if err = pr.Issue.Repo.getOwner(sess); err != nil {
  441. return err
  442. }
  443. if err = pr.Issue.changeStatus(sess, pr.Merger, pr.Issue.Repo, true); err != nil {
  444. return fmt.Errorf("Issue.changeStatus: %v", err)
  445. }
  446. if _, err = sess.ID(pr.ID).Cols("has_merged, status, merged_commit_id, merger_id, merged_unix").Update(pr); err != nil {
  447. return fmt.Errorf("update pull request: %v", err)
  448. }
  449. if err = sess.Commit(); err != nil {
  450. return fmt.Errorf("Commit: %v", err)
  451. }
  452. return nil
  453. }
  454. // manuallyMerged checks if a pull request got manually merged
  455. // When a pull request got manually merged mark the pull request as merged
  456. func (pr *PullRequest) manuallyMerged() bool {
  457. commit, err := pr.getMergeCommit()
  458. if err != nil {
  459. log.Error(4, "PullRequest[%d].getMergeCommit: %v", pr.ID, err)
  460. return false
  461. }
  462. if commit != nil {
  463. pr.MergedCommitID = commit.ID.String()
  464. pr.MergedUnix = util.TimeStamp(commit.Author.When.Unix())
  465. pr.Status = PullRequestStatusManuallyMerged
  466. merger, _ := GetUserByEmail(commit.Author.Email)
  467. // When the commit author is unknown set the BaseRepo owner as merger
  468. if merger == nil {
  469. if pr.BaseRepo.Owner == nil {
  470. if err = pr.BaseRepo.getOwner(x); err != nil {
  471. log.Error(4, "BaseRepo.getOwner[%d]: %v", pr.ID, err)
  472. return false
  473. }
  474. }
  475. merger = pr.BaseRepo.Owner
  476. }
  477. pr.Merger = merger
  478. pr.MergerID = merger.ID
  479. if err = pr.setMerged(); err != nil {
  480. log.Error(4, "PullRequest[%d].setMerged : %v", pr.ID, err)
  481. return false
  482. }
  483. 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())
  484. return true
  485. }
  486. return false
  487. }
  488. // getMergeCommit checks if a pull request got merged
  489. // Returns the git.Commit of the pull request if merged
  490. func (pr *PullRequest) getMergeCommit() (*git.Commit, error) {
  491. if pr.BaseRepo == nil {
  492. var err error
  493. pr.BaseRepo, err = GetRepositoryByID(pr.BaseRepoID)
  494. if err != nil {
  495. return nil, fmt.Errorf("GetRepositoryByID: %v", err)
  496. }
  497. }
  498. indexTmpPath := filepath.Join(os.TempDir(), "gitea-"+pr.BaseRepo.Name+"-"+strconv.Itoa(time.Now().Nanosecond()))
  499. defer os.Remove(indexTmpPath)
  500. headFile := pr.GetGitRefName()
  501. // Check if a pull request is merged into BaseBranch
  502. _, stderr, err := process.GetManager().ExecDirEnv(-1, "", fmt.Sprintf("isMerged (git merge-base --is-ancestor): %d", pr.BaseRepo.ID),
  503. []string{"GIT_INDEX_FILE=" + indexTmpPath, "GIT_DIR=" + pr.BaseRepo.RepoPath()},
  504. "git", "merge-base", "--is-ancestor", headFile, pr.BaseBranch)
  505. if err != nil {
  506. // Errors are signaled by a non-zero status that is not 1
  507. if strings.Contains(err.Error(), "exit status 1") {
  508. return nil, nil
  509. }
  510. return nil, fmt.Errorf("git merge-base --is-ancestor: %v %v", stderr, err)
  511. }
  512. commitIDBytes, err := ioutil.ReadFile(pr.BaseRepo.RepoPath() + "/" + headFile)
  513. if err != nil {
  514. return nil, fmt.Errorf("ReadFile(%s): %v", headFile, err)
  515. }
  516. commitID := string(commitIDBytes)
  517. if len(commitID) < 40 {
  518. return nil, fmt.Errorf(`ReadFile(%s): invalid commit-ID "%s"`, headFile, commitID)
  519. }
  520. cmd := commitID[:40] + ".." + pr.BaseBranch
  521. // Get the commit from BaseBranch where the pull request got merged
  522. mergeCommit, stderr, err := process.GetManager().ExecDirEnv(-1, "", fmt.Sprintf("isMerged (git rev-list --ancestry-path --merges --reverse): %d", pr.BaseRepo.ID),
  523. []string{"GIT_INDEX_FILE=" + indexTmpPath, "GIT_DIR=" + pr.BaseRepo.RepoPath()},
  524. "git", "rev-list", "--ancestry-path", "--merges", "--reverse", cmd)
  525. if err != nil {
  526. return nil, fmt.Errorf("git rev-list --ancestry-path --merges --reverse: %v %v", stderr, err)
  527. } else if len(mergeCommit) < 40 {
  528. // PR was fast-forwarded, so just use last commit of PR
  529. mergeCommit = commitID[:40]
  530. }
  531. gitRepo, err := git.OpenRepository(pr.BaseRepo.RepoPath())
  532. if err != nil {
  533. return nil, fmt.Errorf("OpenRepository: %v", err)
  534. }
  535. commit, err := gitRepo.GetCommit(mergeCommit[:40])
  536. if err != nil {
  537. return nil, fmt.Errorf("GetCommit: %v", err)
  538. }
  539. return commit, nil
  540. }
  541. // patchConflicts is a list of conflict description from Git.
  542. var patchConflicts = []string{
  543. "patch does not apply",
  544. "already exists in working directory",
  545. "unrecognized input",
  546. "error:",
  547. }
  548. // testPatch checks if patch can be merged to base repository without conflict.
  549. func (pr *PullRequest) testPatch() (err error) {
  550. if pr.BaseRepo == nil {
  551. pr.BaseRepo, err = GetRepositoryByID(pr.BaseRepoID)
  552. if err != nil {
  553. return fmt.Errorf("GetRepositoryByID: %v", err)
  554. }
  555. }
  556. patchPath, err := pr.BaseRepo.PatchPath(pr.Index)
  557. if err != nil {
  558. return fmt.Errorf("BaseRepo.PatchPath: %v", err)
  559. }
  560. // Fast fail if patch does not exist, this assumes data is corrupted.
  561. if !com.IsFile(patchPath) {
  562. log.Trace("PullRequest[%d].testPatch: ignored corrupted data", pr.ID)
  563. return nil
  564. }
  565. repoWorkingPool.CheckIn(com.ToStr(pr.BaseRepoID))
  566. defer repoWorkingPool.CheckOut(com.ToStr(pr.BaseRepoID))
  567. log.Trace("PullRequest[%d].testPatch (patchPath): %s", pr.ID, patchPath)
  568. pr.Status = PullRequestStatusChecking
  569. indexTmpPath := filepath.Join(os.TempDir(), "gitea-"+pr.BaseRepo.Name+"-"+strconv.Itoa(time.Now().Nanosecond()))
  570. defer os.Remove(indexTmpPath)
  571. var stderr string
  572. _, stderr, err = process.GetManager().ExecDirEnv(-1, "", fmt.Sprintf("testPatch (git read-tree): %d", pr.BaseRepo.ID),
  573. []string{"GIT_DIR=" + pr.BaseRepo.RepoPath(), "GIT_INDEX_FILE=" + indexTmpPath},
  574. "git", "read-tree", pr.BaseBranch)
  575. if err != nil {
  576. return fmt.Errorf("git read-tree --index-output=%s %s: %v - %s", indexTmpPath, pr.BaseBranch, err, stderr)
  577. }
  578. prUnit, err := pr.BaseRepo.GetUnit(UnitTypePullRequests)
  579. if err != nil {
  580. return err
  581. }
  582. prConfig := prUnit.PullRequestsConfig()
  583. args := []string{"apply", "--check", "--cached"}
  584. if prConfig.IgnoreWhitespaceConflicts {
  585. args = append(args, "--ignore-whitespace")
  586. }
  587. args = append(args, patchPath)
  588. _, stderr, err = process.GetManager().ExecDirEnv(-1, "", fmt.Sprintf("testPatch (git apply --check): %d", pr.BaseRepo.ID),
  589. []string{"GIT_INDEX_FILE=" + indexTmpPath, "GIT_DIR=" + pr.BaseRepo.RepoPath()},
  590. "git", args...)
  591. if err != nil {
  592. for i := range patchConflicts {
  593. if strings.Contains(stderr, patchConflicts[i]) {
  594. log.Trace("PullRequest[%d].testPatch (apply): has conflict", pr.ID)
  595. fmt.Println(stderr)
  596. pr.Status = PullRequestStatusConflict
  597. return nil
  598. }
  599. }
  600. return fmt.Errorf("git apply --check: %v - %s", err, stderr)
  601. }
  602. return nil
  603. }
  604. // NewPullRequest creates new pull request with labels for repository.
  605. func NewPullRequest(repo *Repository, pull *Issue, labelIDs []int64, uuids []string, pr *PullRequest, patch []byte) (err error) {
  606. sess := x.NewSession()
  607. defer sess.Close()
  608. if err = sess.Begin(); err != nil {
  609. return err
  610. }
  611. if err = newIssue(sess, pull.Poster, NewIssueOptions{
  612. Repo: repo,
  613. Issue: pull,
  614. LabelIDs: labelIDs,
  615. Attachments: uuids,
  616. IsPull: true,
  617. }); err != nil {
  618. return fmt.Errorf("newIssue: %v", err)
  619. }
  620. pr.Index = pull.Index
  621. if err = repo.SavePatch(pr.Index, patch); err != nil {
  622. return fmt.Errorf("SavePatch: %v", err)
  623. }
  624. pr.BaseRepo = repo
  625. if err = pr.testPatch(); err != nil {
  626. return fmt.Errorf("testPatch: %v", err)
  627. }
  628. // No conflict appears after test means mergeable.
  629. if pr.Status == PullRequestStatusChecking {
  630. pr.Status = PullRequestStatusMergeable
  631. }
  632. pr.IssueID = pull.ID
  633. if _, err = sess.Insert(pr); err != nil {
  634. return fmt.Errorf("insert pull repo: %v", err)
  635. }
  636. if err = sess.Commit(); err != nil {
  637. return fmt.Errorf("Commit: %v", err)
  638. }
  639. UpdateIssueIndexer(pull.ID)
  640. if err = NotifyWatchers(&Action{
  641. ActUserID: pull.Poster.ID,
  642. ActUser: pull.Poster,
  643. OpType: ActionCreatePullRequest,
  644. Content: fmt.Sprintf("%d|%s", pull.Index, pull.Title),
  645. RepoID: repo.ID,
  646. Repo: repo,
  647. IsPrivate: repo.IsPrivate,
  648. }); err != nil {
  649. log.Error(4, "NotifyWatchers: %v", err)
  650. } else if err = pull.MailParticipants(); err != nil {
  651. log.Error(4, "MailParticipants: %v", err)
  652. }
  653. pr.Issue = pull
  654. pull.PullRequest = pr
  655. if err = PrepareWebhooks(repo, HookEventPullRequest, &api.PullRequestPayload{
  656. Action: api.HookIssueOpened,
  657. Index: pull.Index,
  658. PullRequest: pr.APIFormat(),
  659. Repository: repo.APIFormat(AccessModeNone),
  660. Sender: pull.Poster.APIFormat(),
  661. }); err != nil {
  662. log.Error(4, "PrepareWebhooks: %v", err)
  663. }
  664. go HookQueue.Add(repo.ID)
  665. return nil
  666. }
  667. // PullRequestsOptions holds the options for PRs
  668. type PullRequestsOptions struct {
  669. Page int
  670. State string
  671. SortType string
  672. Labels []string
  673. MilestoneID int64
  674. }
  675. func listPullRequestStatement(baseRepoID int64, opts *PullRequestsOptions) (*xorm.Session, error) {
  676. sess := x.Where("pull_request.base_repo_id=?", baseRepoID)
  677. sess.Join("INNER", "issue", "pull_request.issue_id = issue.id")
  678. switch opts.State {
  679. case "closed", "open":
  680. sess.And("issue.is_closed=?", opts.State == "closed")
  681. }
  682. if labelIDs, err := base.StringsToInt64s(opts.Labels); err != nil {
  683. return nil, err
  684. } else if len(labelIDs) > 0 {
  685. sess.Join("INNER", "issue_label", "issue.id = issue_label.issue_id").
  686. In("issue_label.label_id", labelIDs)
  687. }
  688. if opts.MilestoneID > 0 {
  689. sess.And("issue.milestone_id=?", opts.MilestoneID)
  690. }
  691. return sess, nil
  692. }
  693. // PullRequests returns all pull requests for a base Repo by the given conditions
  694. func PullRequests(baseRepoID int64, opts *PullRequestsOptions) ([]*PullRequest, int64, error) {
  695. if opts.Page <= 0 {
  696. opts.Page = 1
  697. }
  698. countSession, err := listPullRequestStatement(baseRepoID, opts)
  699. if err != nil {
  700. log.Error(4, "listPullRequestStatement", err)
  701. return nil, 0, err
  702. }
  703. maxResults, err := countSession.Count(new(PullRequest))
  704. if err != nil {
  705. log.Error(4, "Count PRs", err)
  706. return nil, maxResults, err
  707. }
  708. prs := make([]*PullRequest, 0, ItemsPerPage)
  709. findSession, err := listPullRequestStatement(baseRepoID, opts)
  710. sortIssuesSession(findSession, opts.SortType)
  711. if err != nil {
  712. log.Error(4, "listPullRequestStatement", err)
  713. return nil, maxResults, err
  714. }
  715. findSession.Limit(ItemsPerPage, (opts.Page-1)*ItemsPerPage)
  716. return prs, maxResults, findSession.Find(&prs)
  717. }
  718. // GetUnmergedPullRequest returns a pull request that is open and has not been merged
  719. // by given head/base and repo/branch.
  720. func GetUnmergedPullRequest(headRepoID, baseRepoID int64, headBranch, baseBranch string) (*PullRequest, error) {
  721. pr := new(PullRequest)
  722. has, err := x.
  723. Where("head_repo_id=? AND head_branch=? AND base_repo_id=? AND base_branch=? AND has_merged=? AND issue.is_closed=?",
  724. headRepoID, headBranch, baseRepoID, baseBranch, false, false).
  725. Join("INNER", "issue", "issue.id=pull_request.issue_id").
  726. Get(pr)
  727. if err != nil {
  728. return nil, err
  729. } else if !has {
  730. return nil, ErrPullRequestNotExist{0, 0, headRepoID, baseRepoID, headBranch, baseBranch}
  731. }
  732. return pr, nil
  733. }
  734. // GetUnmergedPullRequestsByHeadInfo returns all pull requests that are open and has not been merged
  735. // by given head information (repo and branch).
  736. func GetUnmergedPullRequestsByHeadInfo(repoID int64, branch string) ([]*PullRequest, error) {
  737. prs := make([]*PullRequest, 0, 2)
  738. return prs, x.
  739. Where("head_repo_id = ? AND head_branch = ? AND has_merged = ? AND issue.is_closed = ?",
  740. repoID, branch, false, false).
  741. Join("INNER", "issue", "issue.id = pull_request.issue_id").
  742. Find(&prs)
  743. }
  744. // GetUnmergedPullRequestsByBaseInfo returns all pull requests that are open and has not been merged
  745. // by given base information (repo and branch).
  746. func GetUnmergedPullRequestsByBaseInfo(repoID int64, branch string) ([]*PullRequest, error) {
  747. prs := make([]*PullRequest, 0, 2)
  748. return prs, x.
  749. Where("base_repo_id=? AND base_branch=? AND has_merged=? AND issue.is_closed=?",
  750. repoID, branch, false, false).
  751. Join("INNER", "issue", "issue.id=pull_request.issue_id").
  752. Find(&prs)
  753. }
  754. // GetPullRequestByIndex returns a pull request by the given index
  755. func GetPullRequestByIndex(repoID int64, index int64) (*PullRequest, error) {
  756. pr := &PullRequest{
  757. BaseRepoID: repoID,
  758. Index: index,
  759. }
  760. has, err := x.Get(pr)
  761. if err != nil {
  762. return nil, err
  763. } else if !has {
  764. return nil, ErrPullRequestNotExist{0, 0, 0, repoID, "", ""}
  765. }
  766. if err = pr.LoadAttributes(); err != nil {
  767. return nil, err
  768. }
  769. if err = pr.LoadIssue(); err != nil {
  770. return nil, err
  771. }
  772. return pr, nil
  773. }
  774. func getPullRequestByID(e Engine, id int64) (*PullRequest, error) {
  775. pr := new(PullRequest)
  776. has, err := e.ID(id).Get(pr)
  777. if err != nil {
  778. return nil, err
  779. } else if !has {
  780. return nil, ErrPullRequestNotExist{id, 0, 0, 0, "", ""}
  781. }
  782. return pr, pr.loadAttributes(e)
  783. }
  784. // GetPullRequestByID returns a pull request by given ID.
  785. func GetPullRequestByID(id int64) (*PullRequest, error) {
  786. return getPullRequestByID(x, id)
  787. }
  788. func getPullRequestByIssueID(e Engine, issueID int64) (*PullRequest, error) {
  789. pr := &PullRequest{
  790. IssueID: issueID,
  791. }
  792. has, err := e.Get(pr)
  793. if err != nil {
  794. return nil, err
  795. } else if !has {
  796. return nil, ErrPullRequestNotExist{0, issueID, 0, 0, "", ""}
  797. }
  798. return pr, pr.loadAttributes(e)
  799. }
  800. // GetPullRequestByIssueID returns pull request by given issue ID.
  801. func GetPullRequestByIssueID(issueID int64) (*PullRequest, error) {
  802. return getPullRequestByIssueID(x, issueID)
  803. }
  804. // Update updates all fields of pull request.
  805. func (pr *PullRequest) Update() error {
  806. _, err := x.ID(pr.ID).AllCols().Update(pr)
  807. return err
  808. }
  809. // UpdateCols updates specific fields of pull request.
  810. func (pr *PullRequest) UpdateCols(cols ...string) error {
  811. _, err := x.ID(pr.ID).Cols(cols...).Update(pr)
  812. return err
  813. }
  814. // UpdatePatch generates and saves a new patch.
  815. func (pr *PullRequest) UpdatePatch() (err error) {
  816. if err = pr.GetHeadRepo(); err != nil {
  817. return fmt.Errorf("GetHeadRepo: %v", err)
  818. } else if pr.HeadRepo == nil {
  819. log.Trace("PullRequest[%d].UpdatePatch: ignored cruppted data", pr.ID)
  820. return nil
  821. }
  822. if err = pr.GetBaseRepo(); err != nil {
  823. return fmt.Errorf("GetBaseRepo: %v", err)
  824. }
  825. headGitRepo, err := git.OpenRepository(pr.HeadRepo.RepoPath())
  826. if err != nil {
  827. return fmt.Errorf("OpenRepository: %v", err)
  828. }
  829. // Add a temporary remote.
  830. tmpRemote := com.ToStr(time.Now().UnixNano())
  831. if err = headGitRepo.AddRemote(tmpRemote, RepoPath(pr.BaseRepo.MustOwner().Name, pr.BaseRepo.Name), true); err != nil {
  832. return fmt.Errorf("AddRemote: %v", err)
  833. }
  834. defer func() {
  835. headGitRepo.RemoveRemote(tmpRemote)
  836. }()
  837. remoteBranch := "remotes/" + tmpRemote + "/" + pr.BaseBranch
  838. pr.MergeBase, err = headGitRepo.GetMergeBase(remoteBranch, pr.HeadBranch)
  839. if err != nil {
  840. return fmt.Errorf("GetMergeBase: %v", err)
  841. } else if err = pr.Update(); err != nil {
  842. return fmt.Errorf("Update: %v", err)
  843. }
  844. patch, err := headGitRepo.GetPatch(pr.MergeBase, pr.HeadBranch)
  845. if err != nil {
  846. return fmt.Errorf("GetPatch: %v", err)
  847. }
  848. if err = pr.BaseRepo.SavePatch(pr.Index, patch); err != nil {
  849. return fmt.Errorf("BaseRepo.SavePatch: %v", err)
  850. }
  851. return nil
  852. }
  853. // PushToBaseRepo pushes commits from branches of head repository to
  854. // corresponding branches of base repository.
  855. // FIXME: Only push branches that are actually updates?
  856. func (pr *PullRequest) PushToBaseRepo() (err error) {
  857. log.Trace("PushToBaseRepo[%d]: pushing commits to base repo '%s'", pr.BaseRepoID, pr.GetGitRefName())
  858. headRepoPath := pr.HeadRepo.RepoPath()
  859. headGitRepo, err := git.OpenRepository(headRepoPath)
  860. if err != nil {
  861. return fmt.Errorf("OpenRepository: %v", err)
  862. }
  863. tmpRemoteName := fmt.Sprintf("tmp-pull-%d", pr.ID)
  864. if err = headGitRepo.AddRemote(tmpRemoteName, pr.BaseRepo.RepoPath(), false); err != nil {
  865. return fmt.Errorf("headGitRepo.AddRemote: %v", err)
  866. }
  867. // Make sure to remove the remote even if the push fails
  868. defer headGitRepo.RemoveRemote(tmpRemoteName)
  869. headFile := pr.GetGitRefName()
  870. // Remove head in case there is a conflict.
  871. file := path.Join(pr.BaseRepo.RepoPath(), headFile)
  872. _ = os.Remove(file)
  873. if err = git.Push(headRepoPath, git.PushOptions{
  874. Remote: tmpRemoteName,
  875. Branch: fmt.Sprintf("%s:%s", pr.HeadBranch, headFile),
  876. Force: true,
  877. }); err != nil {
  878. return fmt.Errorf("Push: %v", err)
  879. }
  880. return nil
  881. }
  882. // AddToTaskQueue adds itself to pull request test task queue.
  883. func (pr *PullRequest) AddToTaskQueue() {
  884. go pullRequestQueue.AddFunc(pr.ID, func() {
  885. pr.Status = PullRequestStatusChecking
  886. if err := pr.UpdateCols("status"); err != nil {
  887. log.Error(5, "AddToTaskQueue.UpdateCols[%d].(add to queue): %v", pr.ID, err)
  888. }
  889. })
  890. }
  891. // PullRequestList defines a list of pull requests
  892. type PullRequestList []*PullRequest
  893. func (prs PullRequestList) loadAttributes(e Engine) error {
  894. if len(prs) == 0 {
  895. return nil
  896. }
  897. // Load issues.
  898. issueIDs := make([]int64, 0, len(prs))
  899. for i := range prs {
  900. issueIDs = append(issueIDs, prs[i].IssueID)
  901. }
  902. issues := make([]*Issue, 0, len(issueIDs))
  903. if err := e.
  904. Where("id > 0").
  905. In("id", issueIDs).
  906. Find(&issues); err != nil {
  907. return fmt.Errorf("find issues: %v", err)
  908. }
  909. set := make(map[int64]*Issue)
  910. for i := range issues {
  911. set[issues[i].ID] = issues[i]
  912. }
  913. for i := range prs {
  914. prs[i].Issue = set[prs[i].IssueID]
  915. }
  916. return nil
  917. }
  918. // LoadAttributes load all the prs attributes
  919. func (prs PullRequestList) LoadAttributes() error {
  920. return prs.loadAttributes(x)
  921. }
  922. func addHeadRepoTasks(prs []*PullRequest) {
  923. for _, pr := range prs {
  924. log.Trace("addHeadRepoTasks[%d]: composing new test task", pr.ID)
  925. if err := pr.UpdatePatch(); err != nil {
  926. log.Error(4, "UpdatePatch: %v", err)
  927. continue
  928. } else if err := pr.PushToBaseRepo(); err != nil {
  929. log.Error(4, "PushToBaseRepo: %v", err)
  930. continue
  931. }
  932. pr.AddToTaskQueue()
  933. }
  934. }
  935. // AddTestPullRequestTask adds new test tasks by given head/base repository and head/base branch,
  936. // and generate new patch for testing as needed.
  937. func AddTestPullRequestTask(doer *User, repoID int64, branch string, isSync bool) {
  938. log.Trace("AddTestPullRequestTask [head_repo_id: %d, head_branch: %s]: finding pull requests", repoID, branch)
  939. prs, err := GetUnmergedPullRequestsByHeadInfo(repoID, branch)
  940. if err != nil {
  941. log.Error(4, "Find pull requests [head_repo_id: %d, head_branch: %s]: %v", repoID, branch, err)
  942. return
  943. }
  944. if isSync {
  945. if err = PullRequestList(prs).LoadAttributes(); err != nil {
  946. log.Error(4, "PullRequestList.LoadAttributes: %v", err)
  947. }
  948. if err == nil {
  949. for _, pr := range prs {
  950. pr.Issue.PullRequest = pr
  951. if err = pr.Issue.LoadAttributes(); err != nil {
  952. log.Error(4, "LoadAttributes: %v", err)
  953. continue
  954. }
  955. if err = PrepareWebhooks(pr.Issue.Repo, HookEventPullRequest, &api.PullRequestPayload{
  956. Action: api.HookIssueSynchronized,
  957. Index: pr.Issue.Index,
  958. PullRequest: pr.Issue.PullRequest.APIFormat(),
  959. Repository: pr.Issue.Repo.APIFormat(AccessModeNone),
  960. Sender: doer.APIFormat(),
  961. }); err != nil {
  962. log.Error(4, "PrepareWebhooks [pull_id: %v]: %v", pr.ID, err)
  963. continue
  964. }
  965. go HookQueue.Add(pr.Issue.Repo.ID)
  966. }
  967. }
  968. }
  969. addHeadRepoTasks(prs)
  970. log.Trace("AddTestPullRequestTask [base_repo_id: %d, base_branch: %s]: finding pull requests", repoID, branch)
  971. prs, err = GetUnmergedPullRequestsByBaseInfo(repoID, branch)
  972. if err != nil {
  973. log.Error(4, "Find pull requests [base_repo_id: %d, base_branch: %s]: %v", repoID, branch, err)
  974. return
  975. }
  976. for _, pr := range prs {
  977. pr.AddToTaskQueue()
  978. }
  979. }
  980. // ChangeUsernameInPullRequests changes the name of head_user_name
  981. func ChangeUsernameInPullRequests(oldUserName, newUserName string) error {
  982. pr := PullRequest{
  983. HeadUserName: strings.ToLower(newUserName),
  984. }
  985. _, err := x.
  986. Cols("head_user_name").
  987. Where("head_user_name = ?", strings.ToLower(oldUserName)).
  988. Update(pr)
  989. return err
  990. }
  991. // checkAndUpdateStatus checks if pull request is possible to leaving checking status,
  992. // and set to be either conflict or mergeable.
  993. func (pr *PullRequest) checkAndUpdateStatus() {
  994. // Status is not changed to conflict means mergeable.
  995. if pr.Status == PullRequestStatusChecking {
  996. pr.Status = PullRequestStatusMergeable
  997. }
  998. // Make sure there is no waiting test to process before leaving the checking status.
  999. if !pullRequestQueue.Exist(pr.ID) {
  1000. if err := pr.UpdateCols("status"); err != nil {
  1001. log.Error(4, "Update[%d]: %v", pr.ID, err)
  1002. }
  1003. }
  1004. }
  1005. // TestPullRequests checks and tests untested patches of pull requests.
  1006. // TODO: test more pull requests at same time.
  1007. func TestPullRequests() {
  1008. prs := make([]*PullRequest, 0, 10)
  1009. err := x.Where("status = ?", PullRequestStatusChecking).Find(&prs)
  1010. if err != nil {
  1011. log.Error(3, "Find Checking PRs", err)
  1012. return
  1013. }
  1014. var checkedPRs = make(map[int64]struct{})
  1015. // Update pull request status.
  1016. for _, pr := range prs {
  1017. checkedPRs[pr.ID] = struct{}{}
  1018. if err := pr.GetBaseRepo(); err != nil {
  1019. log.Error(3, "GetBaseRepo: %v", err)
  1020. continue
  1021. }
  1022. if pr.manuallyMerged() {
  1023. continue
  1024. }
  1025. if err := pr.testPatch(); err != nil {
  1026. log.Error(3, "testPatch: %v", err)
  1027. continue
  1028. }
  1029. pr.checkAndUpdateStatus()
  1030. }
  1031. // Start listening on new test requests.
  1032. for prID := range pullRequestQueue.Queue() {
  1033. log.Trace("TestPullRequests[%v]: processing test task", prID)
  1034. pullRequestQueue.Remove(prID)
  1035. id := com.StrTo(prID).MustInt64()
  1036. if _, ok := checkedPRs[id]; ok {
  1037. continue
  1038. }
  1039. pr, err := GetPullRequestByID(id)
  1040. if err != nil {
  1041. log.Error(4, "GetPullRequestByID[%s]: %v", prID, err)
  1042. continue
  1043. } else if pr.manuallyMerged() {
  1044. continue
  1045. } else if err = pr.testPatch(); err != nil {
  1046. log.Error(4, "testPatch[%d]: %v", pr.ID, err)
  1047. continue
  1048. }
  1049. pr.checkAndUpdateStatus()
  1050. }
  1051. }
  1052. // InitTestPullRequests runs the task to test all the checking status pull requests
  1053. func InitTestPullRequests() {
  1054. go TestPullRequests()
  1055. }