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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944
  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. "os"
  8. "path"
  9. "strings"
  10. "time"
  11. "code.gitea.io/git"
  12. "code.gitea.io/gitea/modules/log"
  13. "code.gitea.io/gitea/modules/process"
  14. "code.gitea.io/gitea/modules/setting"
  15. "code.gitea.io/gitea/modules/sync"
  16. api "code.gitea.io/sdk/gitea"
  17. "github.com/Unknwon/com"
  18. "github.com/go-xorm/xorm"
  19. )
  20. var pullRequestQueue = sync.NewUniqueQueue(setting.Repository.PullRequestQueueLength)
  21. // PullRequestType defines pull request type
  22. type PullRequestType int
  23. // Enumerate all the pull request types
  24. const (
  25. PullRequestGitea PullRequestType = iota
  26. PullRequestGit
  27. )
  28. // PullRequestStatus defines pull request status
  29. type PullRequestStatus int
  30. // Enumerate all the pull request status
  31. const (
  32. PullRequestStatusConflict PullRequestStatus = iota
  33. PullRequestStatusChecking
  34. PullRequestStatusMergeable
  35. )
  36. // PullRequest represents relation between pull request and repositories.
  37. type PullRequest struct {
  38. ID int64 `xorm:"pk autoincr"`
  39. Type PullRequestType
  40. Status PullRequestStatus
  41. IssueID int64 `xorm:"INDEX"`
  42. Issue *Issue `xorm:"-"`
  43. Index int64
  44. HeadRepoID int64
  45. HeadRepo *Repository `xorm:"-"`
  46. BaseRepoID int64
  47. BaseRepo *Repository `xorm:"-"`
  48. HeadUserName string
  49. HeadBranch string
  50. BaseBranch string
  51. MergeBase string `xorm:"VARCHAR(40)"`
  52. HasMerged bool
  53. MergedCommitID string `xorm:"VARCHAR(40)"`
  54. MergerID int64
  55. Merger *User `xorm:"-"`
  56. Merged time.Time `xorm:"-"`
  57. MergedUnix int64
  58. }
  59. // BeforeUpdate is invoked from XORM before updating an object of this type.
  60. func (pr *PullRequest) BeforeUpdate() {
  61. pr.MergedUnix = pr.Merged.Unix()
  62. }
  63. // AfterSet is invoked from XORM after setting the value of a field of this object.
  64. // Note: don't try to get Issue because will end up recursive querying.
  65. func (pr *PullRequest) AfterSet(colName string, _ xorm.Cell) {
  66. switch colName {
  67. case "merged_unix":
  68. if !pr.HasMerged {
  69. return
  70. }
  71. pr.Merged = time.Unix(pr.MergedUnix, 0).Local()
  72. }
  73. }
  74. // Note: don't try to get Issue because will end up recursive querying.
  75. func (pr *PullRequest) loadAttributes(e Engine) (err error) {
  76. if pr.HasMerged && pr.Merger == nil {
  77. pr.Merger, err = getUserByID(e, pr.MergerID)
  78. if IsErrUserNotExist(err) {
  79. pr.MergerID = -1
  80. pr.Merger = NewGhostUser()
  81. } else if err != nil {
  82. return fmt.Errorf("getUserByID [%d]: %v", pr.MergerID, err)
  83. }
  84. }
  85. return nil
  86. }
  87. // LoadAttributes loads pull request attributes from database
  88. func (pr *PullRequest) LoadAttributes() error {
  89. return pr.loadAttributes(x)
  90. }
  91. // LoadIssue loads issue information from database
  92. func (pr *PullRequest) LoadIssue() (err error) {
  93. if pr.Issue != nil {
  94. return nil
  95. }
  96. pr.Issue, err = GetIssueByID(pr.IssueID)
  97. return err
  98. }
  99. // APIFormat assumes following fields have been assigned with valid values:
  100. // Required - Issue
  101. // Optional - Merger
  102. func (pr *PullRequest) APIFormat() *api.PullRequest {
  103. var (
  104. baseBranch *Branch
  105. headBranch *Branch
  106. baseCommit *git.Commit
  107. headCommit *git.Commit
  108. err error
  109. )
  110. apiIssue := pr.Issue.APIFormat()
  111. if pr.BaseRepo == nil {
  112. pr.BaseRepo, err = GetRepositoryByID(pr.BaseRepoID)
  113. if err != nil {
  114. log.Error(log.ERROR, "GetRepositoryById[%d]: %v", pr.ID, err)
  115. return nil
  116. }
  117. }
  118. if pr.HeadRepo == nil {
  119. pr.HeadRepo, err = GetRepositoryByID(pr.HeadRepoID)
  120. if err != nil {
  121. log.Error(log.ERROR, "GetRepositoryById[%d]: %v", pr.ID, err)
  122. return nil
  123. }
  124. }
  125. if baseBranch, err = pr.BaseRepo.GetBranch(pr.BaseBranch); err != nil {
  126. return nil
  127. }
  128. if baseCommit, err = baseBranch.GetCommit(); err != nil {
  129. return nil
  130. }
  131. if headBranch, err = pr.HeadRepo.GetBranch(pr.HeadBranch); err != nil {
  132. return nil
  133. }
  134. if headCommit, err = headBranch.GetCommit(); err != nil {
  135. return nil
  136. }
  137. apiBaseBranchInfo := &api.PRBranchInfo{
  138. Name: pr.BaseBranch,
  139. Ref: pr.BaseBranch,
  140. Sha: baseCommit.ID.String(),
  141. RepoID: pr.BaseRepoID,
  142. Repository: pr.BaseRepo.APIFormat(AccessModeNone),
  143. }
  144. apiHeadBranchInfo := &api.PRBranchInfo{
  145. Name: pr.HeadBranch,
  146. Ref: pr.HeadBranch,
  147. Sha: headCommit.ID.String(),
  148. RepoID: pr.HeadRepoID,
  149. Repository: pr.HeadRepo.APIFormat(AccessModeNone),
  150. }
  151. apiPullRequest := &api.PullRequest{
  152. ID: pr.ID,
  153. Index: pr.Index,
  154. Poster: apiIssue.Poster,
  155. Title: apiIssue.Title,
  156. Body: apiIssue.Body,
  157. Labels: apiIssue.Labels,
  158. Milestone: apiIssue.Milestone,
  159. Assignee: apiIssue.Assignee,
  160. State: apiIssue.State,
  161. Comments: apiIssue.Comments,
  162. HTMLURL: pr.Issue.HTMLURL(),
  163. DiffURL: pr.Issue.DiffURL(),
  164. PatchURL: pr.Issue.PatchURL(),
  165. HasMerged: pr.HasMerged,
  166. Base: apiBaseBranchInfo,
  167. Head: apiHeadBranchInfo,
  168. MergeBase: pr.MergeBase,
  169. }
  170. if pr.Status != PullRequestStatusChecking {
  171. mergeable := pr.Status != PullRequestStatusConflict
  172. apiPullRequest.Mergeable = mergeable
  173. }
  174. if pr.HasMerged {
  175. apiPullRequest.Merged = &pr.Merged
  176. apiPullRequest.MergedCommitID = &pr.MergedCommitID
  177. apiPullRequest.MergedBy = pr.Merger.APIFormat()
  178. }
  179. return apiPullRequest
  180. }
  181. func (pr *PullRequest) getHeadRepo(e Engine) (err error) {
  182. pr.HeadRepo, err = getRepositoryByID(e, pr.HeadRepoID)
  183. if err != nil && !IsErrRepoNotExist(err) {
  184. return fmt.Errorf("getRepositoryByID(head): %v", err)
  185. }
  186. return nil
  187. }
  188. // GetHeadRepo loads the head repository
  189. func (pr *PullRequest) GetHeadRepo() error {
  190. return pr.getHeadRepo(x)
  191. }
  192. // GetBaseRepo loads the target repository
  193. func (pr *PullRequest) GetBaseRepo() (err error) {
  194. if pr.BaseRepo != nil {
  195. return nil
  196. }
  197. pr.BaseRepo, err = GetRepositoryByID(pr.BaseRepoID)
  198. if err != nil {
  199. return fmt.Errorf("GetRepositoryByID(base): %v", err)
  200. }
  201. return nil
  202. }
  203. // IsChecking returns true if this pull request is still checking conflict.
  204. func (pr *PullRequest) IsChecking() bool {
  205. return pr.Status == PullRequestStatusChecking
  206. }
  207. // CanAutoMerge returns true if this pull request can be merged automatically.
  208. func (pr *PullRequest) CanAutoMerge() bool {
  209. return pr.Status == PullRequestStatusMergeable
  210. }
  211. // Merge merges pull request to base repository.
  212. // FIXME: add repoWorkingPull make sure two merges does not happen at same time.
  213. func (pr *PullRequest) Merge(doer *User, baseGitRepo *git.Repository) (err error) {
  214. if err = pr.GetHeadRepo(); err != nil {
  215. return fmt.Errorf("GetHeadRepo: %v", err)
  216. } else if err = pr.GetBaseRepo(); err != nil {
  217. return fmt.Errorf("GetBaseRepo: %v", err)
  218. }
  219. defer func() {
  220. go HookQueue.Add(pr.BaseRepo.ID)
  221. go AddTestPullRequestTask(doer, pr.BaseRepo.ID, pr.BaseBranch, false)
  222. }()
  223. sess := x.NewSession()
  224. defer sessionRelease(sess)
  225. if err = sess.Begin(); err != nil {
  226. return err
  227. }
  228. if err = pr.Issue.changeStatus(sess, doer, pr.Issue.Repo, true); err != nil {
  229. return fmt.Errorf("Issue.changeStatus: %v", err)
  230. }
  231. headRepoPath := RepoPath(pr.HeadUserName, pr.HeadRepo.Name)
  232. headGitRepo, err := git.OpenRepository(headRepoPath)
  233. if err != nil {
  234. return fmt.Errorf("OpenRepository: %v", err)
  235. }
  236. // Clone base repo.
  237. tmpBasePath := path.Join(setting.AppDataPath, "tmp/repos", com.ToStr(time.Now().Nanosecond())+".git")
  238. if err := os.MkdirAll(path.Dir(tmpBasePath), os.ModePerm); err != nil {
  239. return fmt.Errorf("Fail to create dir %s: %v", tmpBasePath, err)
  240. }
  241. defer os.RemoveAll(path.Dir(tmpBasePath))
  242. var stderr string
  243. if _, stderr, err = process.ExecTimeout(5*time.Minute,
  244. fmt.Sprintf("PullRequest.Merge (git clone): %s", tmpBasePath),
  245. "git", "clone", baseGitRepo.Path, tmpBasePath); err != nil {
  246. return fmt.Errorf("git clone: %s", stderr)
  247. }
  248. // Check out base branch.
  249. if _, stderr, err = process.ExecDir(-1, tmpBasePath,
  250. fmt.Sprintf("PullRequest.Merge (git checkout): %s", tmpBasePath),
  251. "git", "checkout", pr.BaseBranch); err != nil {
  252. return fmt.Errorf("git checkout: %s", stderr)
  253. }
  254. // Add head repo remote.
  255. if _, stderr, err = process.ExecDir(-1, tmpBasePath,
  256. fmt.Sprintf("PullRequest.Merge (git remote add): %s", tmpBasePath),
  257. "git", "remote", "add", "head_repo", headRepoPath); err != nil {
  258. return fmt.Errorf("git remote add [%s -> %s]: %s", headRepoPath, tmpBasePath, stderr)
  259. }
  260. // Merge commits.
  261. if _, stderr, err = process.ExecDir(-1, tmpBasePath,
  262. fmt.Sprintf("PullRequest.Merge (git fetch): %s", tmpBasePath),
  263. "git", "fetch", "head_repo"); err != nil {
  264. return fmt.Errorf("git fetch [%s -> %s]: %s", headRepoPath, tmpBasePath, stderr)
  265. }
  266. if _, stderr, err = process.ExecDir(-1, tmpBasePath,
  267. fmt.Sprintf("PullRequest.Merge (git merge --no-ff --no-commit): %s", tmpBasePath),
  268. "git", "merge", "--no-ff", "--no-commit", "head_repo/"+pr.HeadBranch); err != nil {
  269. return fmt.Errorf("git merge --no-ff --no-commit [%s]: %v - %s", tmpBasePath, err, stderr)
  270. }
  271. sig := doer.NewGitSig()
  272. if _, stderr, err = process.ExecDir(-1, tmpBasePath,
  273. fmt.Sprintf("PullRequest.Merge (git merge): %s", tmpBasePath),
  274. "git", "commit", fmt.Sprintf("--author='%s <%s>'", sig.Name, sig.Email),
  275. "-m", fmt.Sprintf("Merge branch '%s' of %s/%s into %s", pr.HeadBranch, pr.HeadUserName, pr.HeadRepo.Name, pr.BaseBranch)); err != nil {
  276. return fmt.Errorf("git commit [%s]: %v - %s", tmpBasePath, err, stderr)
  277. }
  278. // Push back to upstream.
  279. if _, stderr, err = process.ExecDir(-1, tmpBasePath,
  280. fmt.Sprintf("PullRequest.Merge (git push): %s", tmpBasePath),
  281. "git", "push", baseGitRepo.Path, pr.BaseBranch); err != nil {
  282. return fmt.Errorf("git push: %s", stderr)
  283. }
  284. pr.MergedCommitID, err = headGitRepo.GetBranchCommitID(pr.HeadBranch)
  285. if err != nil {
  286. return fmt.Errorf("GetBranchCommit: %v", err)
  287. }
  288. pr.HasMerged = true
  289. pr.Merged = time.Now()
  290. pr.MergerID = doer.ID
  291. if _, err = sess.Id(pr.ID).AllCols().Update(pr); err != nil {
  292. return fmt.Errorf("update pull request: %v", err)
  293. }
  294. if err = sess.Commit(); err != nil {
  295. return fmt.Errorf("Commit: %v", err)
  296. }
  297. if err = MergePullRequestAction(doer, pr.Issue.Repo, pr.Issue); err != nil {
  298. log.Error(4, "MergePullRequestAction [%d]: %v", pr.ID, err)
  299. }
  300. // Reload pull request information.
  301. if err = pr.LoadAttributes(); err != nil {
  302. log.Error(4, "LoadAttributes: %v", err)
  303. return nil
  304. }
  305. if err = PrepareWebhooks(pr.Issue.Repo, HookEventPullRequest, &api.PullRequestPayload{
  306. Action: api.HookIssueClosed,
  307. Index: pr.Index,
  308. PullRequest: pr.APIFormat(),
  309. Repository: pr.Issue.Repo.APIFormat(AccessModeNone),
  310. Sender: doer.APIFormat(),
  311. }); err != nil {
  312. log.Error(4, "PrepareWebhooks: %v", err)
  313. return nil
  314. }
  315. l, err := headGitRepo.CommitsBetweenIDs(pr.MergedCommitID, pr.MergeBase)
  316. if err != nil {
  317. log.Error(4, "CommitsBetweenIDs: %v", err)
  318. return nil
  319. }
  320. // TODO: when squash commits, no need to append merge commit.
  321. // It is possible that head branch is not fully sync with base branch for merge commits,
  322. // so we need to get latest head commit and append merge commit manully
  323. // to avoid strange diff commits produced.
  324. mergeCommit, err := baseGitRepo.GetBranchCommit(pr.BaseBranch)
  325. if err != nil {
  326. log.Error(4, "GetBranchCommit: %v", err)
  327. return nil
  328. }
  329. l.PushFront(mergeCommit)
  330. p := &api.PushPayload{
  331. Ref: git.BRANCH_PREFIX + pr.BaseBranch,
  332. Before: pr.MergeBase,
  333. After: pr.MergedCommitID,
  334. CompareURL: setting.AppURL + pr.BaseRepo.ComposeCompareURL(pr.MergeBase, pr.MergedCommitID),
  335. Commits: ListToPushCommits(l).ToAPIPayloadCommits(pr.BaseRepo.HTMLURL()),
  336. Repo: pr.BaseRepo.APIFormat(AccessModeNone),
  337. Pusher: pr.HeadRepo.MustOwner().APIFormat(),
  338. Sender: doer.APIFormat(),
  339. }
  340. if err = PrepareWebhooks(pr.BaseRepo, HookEventPush, p); err != nil {
  341. return fmt.Errorf("PrepareWebhooks: %v", err)
  342. }
  343. return nil
  344. }
  345. // patchConflicts is a list of conflict description from Git.
  346. var patchConflicts = []string{
  347. "patch does not apply",
  348. "already exists in working directory",
  349. "unrecognized input",
  350. "error:",
  351. }
  352. // testPatch checks if patch can be merged to base repository without conflict.
  353. // FIXME: make a mechanism to clean up stable local copies.
  354. func (pr *PullRequest) testPatch() (err error) {
  355. if pr.BaseRepo == nil {
  356. pr.BaseRepo, err = GetRepositoryByID(pr.BaseRepoID)
  357. if err != nil {
  358. return fmt.Errorf("GetRepositoryByID: %v", err)
  359. }
  360. }
  361. patchPath, err := pr.BaseRepo.PatchPath(pr.Index)
  362. if err != nil {
  363. return fmt.Errorf("BaseRepo.PatchPath: %v", err)
  364. }
  365. // Fast fail if patch does not exist, this assumes data is cruppted.
  366. if !com.IsFile(patchPath) {
  367. log.Trace("PullRequest[%d].testPatch: ignored cruppted data", pr.ID)
  368. return nil
  369. }
  370. repoWorkingPool.CheckIn(com.ToStr(pr.BaseRepoID))
  371. defer repoWorkingPool.CheckOut(com.ToStr(pr.BaseRepoID))
  372. log.Trace("PullRequest[%d].testPatch (patchPath): %s", pr.ID, patchPath)
  373. if err := pr.BaseRepo.UpdateLocalCopyBranch(pr.BaseBranch); err != nil {
  374. return fmt.Errorf("UpdateLocalCopy: %v", err)
  375. }
  376. pr.Status = PullRequestStatusChecking
  377. _, stderr, err := process.ExecDir(-1, pr.BaseRepo.LocalCopyPath(),
  378. fmt.Sprintf("testPatch (git apply --check): %d", pr.BaseRepo.ID),
  379. "git", "apply", "--check", patchPath)
  380. if err != nil {
  381. for i := range patchConflicts {
  382. if strings.Contains(stderr, patchConflicts[i]) {
  383. log.Trace("PullRequest[%d].testPatch (apply): has conflict", pr.ID)
  384. fmt.Println(stderr)
  385. pr.Status = PullRequestStatusConflict
  386. return nil
  387. }
  388. }
  389. return fmt.Errorf("git apply --check: %v - %s", err, stderr)
  390. }
  391. return nil
  392. }
  393. // NewPullRequest creates new pull request with labels for repository.
  394. func NewPullRequest(repo *Repository, pull *Issue, labelIDs []int64, uuids []string, pr *PullRequest, patch []byte) (err error) {
  395. sess := x.NewSession()
  396. defer sessionRelease(sess)
  397. if err = sess.Begin(); err != nil {
  398. return err
  399. }
  400. if err = newIssue(sess, NewIssueOptions{
  401. Repo: repo,
  402. Issue: pull,
  403. LableIDs: labelIDs,
  404. Attachments: uuids,
  405. IsPull: true,
  406. }); err != nil {
  407. return fmt.Errorf("newIssue: %v", err)
  408. }
  409. pr.Index = pull.Index
  410. if err = repo.SavePatch(pr.Index, patch); err != nil {
  411. return fmt.Errorf("SavePatch: %v", err)
  412. }
  413. pr.BaseRepo = repo
  414. if err = pr.testPatch(); err != nil {
  415. return fmt.Errorf("testPatch: %v", err)
  416. }
  417. // No conflict appears after test means mergeable.
  418. if pr.Status == PullRequestStatusChecking {
  419. pr.Status = PullRequestStatusMergeable
  420. }
  421. pr.IssueID = pull.ID
  422. if _, err = sess.Insert(pr); err != nil {
  423. return fmt.Errorf("insert pull repo: %v", err)
  424. }
  425. if err = sess.Commit(); err != nil {
  426. return fmt.Errorf("Commit: %v", err)
  427. }
  428. if err = NotifyWatchers(&Action{
  429. ActUserID: pull.Poster.ID,
  430. ActUserName: pull.Poster.Name,
  431. OpType: ActionCreatePullRequest,
  432. Content: fmt.Sprintf("%d|%s", pull.Index, pull.Title),
  433. RepoID: repo.ID,
  434. RepoUserName: repo.Owner.Name,
  435. RepoName: repo.Name,
  436. IsPrivate: repo.IsPrivate,
  437. }); err != nil {
  438. log.Error(4, "NotifyWatchers: %v", err)
  439. } else if err = pull.MailParticipants(); err != nil {
  440. log.Error(4, "MailParticipants: %v", err)
  441. }
  442. pr.Issue = pull
  443. pull.PullRequest = pr
  444. if err = PrepareWebhooks(repo, HookEventPullRequest, &api.PullRequestPayload{
  445. Action: api.HookIssueOpened,
  446. Index: pull.Index,
  447. PullRequest: pr.APIFormat(),
  448. Repository: repo.APIFormat(AccessModeNone),
  449. Sender: pull.Poster.APIFormat(),
  450. }); err != nil {
  451. log.Error(4, "PrepareWebhooks: %v", err)
  452. }
  453. go HookQueue.Add(repo.ID)
  454. return nil
  455. }
  456. // PullRequestsOptions holds the options for PRs
  457. type PullRequestsOptions struct {
  458. Page int
  459. State string
  460. SortType string
  461. Labels []string
  462. MilestoneID int64
  463. }
  464. func listPullRequestStatement(baseRepoID int64, opts *PullRequestsOptions) *xorm.Session {
  465. sess := x.Where("pull_request.base_repo_id=?", baseRepoID)
  466. sess.Join("INNER", "issue", "pull_request.issue_id = issue.id")
  467. switch opts.State {
  468. case "closed", "open":
  469. sess.And("issue.is_closed=?", opts.State == "closed")
  470. }
  471. return sess
  472. }
  473. // PullRequests returns all pull requests for a base Repo by the given conditions
  474. func PullRequests(baseRepoID int64, opts *PullRequestsOptions) ([]*PullRequest, int64, error) {
  475. if opts.Page <= 0 {
  476. opts.Page = 1
  477. }
  478. countSession := listPullRequestStatement(baseRepoID, opts)
  479. maxResults, err := countSession.Count(new(PullRequest))
  480. if err != nil {
  481. log.Error(4, "Count PRs", err)
  482. return nil, maxResults, err
  483. }
  484. prs := make([]*PullRequest, 0, ItemsPerPage)
  485. findSession := listPullRequestStatement(baseRepoID, opts)
  486. findSession.Limit(ItemsPerPage, (opts.Page-1)*ItemsPerPage)
  487. return prs, maxResults, findSession.Find(&prs)
  488. }
  489. // GetUnmergedPullRequest returnss a pull request that is open and has not been merged
  490. // by given head/base and repo/branch.
  491. func GetUnmergedPullRequest(headRepoID, baseRepoID int64, headBranch, baseBranch string) (*PullRequest, error) {
  492. pr := new(PullRequest)
  493. has, err := x.
  494. Where("head_repo_id=? AND head_branch=? AND base_repo_id=? AND base_branch=? AND has_merged=? AND issue.is_closed=?",
  495. headRepoID, headBranch, baseRepoID, baseBranch, false, false).
  496. Join("INNER", "issue", "issue.id=pull_request.issue_id").
  497. Get(pr)
  498. if err != nil {
  499. return nil, err
  500. } else if !has {
  501. return nil, ErrPullRequestNotExist{0, 0, headRepoID, baseRepoID, headBranch, baseBranch}
  502. }
  503. return pr, nil
  504. }
  505. // GetUnmergedPullRequestsByHeadInfo returnss all pull requests that are open and has not been merged
  506. // by given head information (repo and branch).
  507. func GetUnmergedPullRequestsByHeadInfo(repoID int64, branch string) ([]*PullRequest, error) {
  508. prs := make([]*PullRequest, 0, 2)
  509. return prs, x.
  510. Where("head_repo_id = ? AND head_branch = ? AND has_merged = ? AND issue.is_closed = ?",
  511. repoID, branch, false, false).
  512. Join("INNER", "issue", "issue.id = pull_request.issue_id").
  513. Find(&prs)
  514. }
  515. // GetUnmergedPullRequestsByBaseInfo returnss all pull requests that are open and has not been merged
  516. // by given base information (repo and branch).
  517. func GetUnmergedPullRequestsByBaseInfo(repoID int64, branch string) ([]*PullRequest, error) {
  518. prs := make([]*PullRequest, 0, 2)
  519. return prs, x.
  520. Where("base_repo_id=? AND base_branch=? AND has_merged=? AND issue.is_closed=?",
  521. repoID, branch, false, false).
  522. Join("INNER", "issue", "issue.id=pull_request.issue_id").
  523. Find(&prs)
  524. }
  525. // GetPullRequestByIndex returns a pull request by the given index
  526. func GetPullRequestByIndex(repoID int64, index int64) (*PullRequest, error) {
  527. pr := &PullRequest{
  528. BaseRepoID: repoID,
  529. Index: index,
  530. }
  531. has, err := x.Get(pr)
  532. if err != nil {
  533. return nil, err
  534. } else if !has {
  535. return nil, ErrPullRequestNotExist{0, repoID, index, 0, "", ""}
  536. }
  537. if err = pr.LoadAttributes(); err != nil {
  538. return nil, err
  539. }
  540. if err = pr.LoadIssue(); err != nil {
  541. return nil, err
  542. }
  543. return pr, nil
  544. }
  545. func getPullRequestByID(e Engine, id int64) (*PullRequest, error) {
  546. pr := new(PullRequest)
  547. has, err := e.Id(id).Get(pr)
  548. if err != nil {
  549. return nil, err
  550. } else if !has {
  551. return nil, ErrPullRequestNotExist{id, 0, 0, 0, "", ""}
  552. }
  553. return pr, pr.loadAttributes(e)
  554. }
  555. // GetPullRequestByID returns a pull request by given ID.
  556. func GetPullRequestByID(id int64) (*PullRequest, error) {
  557. return getPullRequestByID(x, id)
  558. }
  559. func getPullRequestByIssueID(e Engine, issueID int64) (*PullRequest, error) {
  560. pr := &PullRequest{
  561. IssueID: issueID,
  562. }
  563. has, err := e.Get(pr)
  564. if err != nil {
  565. return nil, err
  566. } else if !has {
  567. return nil, ErrPullRequestNotExist{0, issueID, 0, 0, "", ""}
  568. }
  569. return pr, pr.loadAttributes(e)
  570. }
  571. // GetPullRequestByIssueID returns pull request by given issue ID.
  572. func GetPullRequestByIssueID(issueID int64) (*PullRequest, error) {
  573. return getPullRequestByIssueID(x, issueID)
  574. }
  575. // Update updates all fields of pull request.
  576. func (pr *PullRequest) Update() error {
  577. _, err := x.Id(pr.ID).AllCols().Update(pr)
  578. return err
  579. }
  580. // UpdateCols updates specific fields of pull request.
  581. func (pr *PullRequest) UpdateCols(cols ...string) error {
  582. _, err := x.Id(pr.ID).Cols(cols...).Update(pr)
  583. return err
  584. }
  585. // UpdatePatch generates and saves a new patch.
  586. func (pr *PullRequest) UpdatePatch() (err error) {
  587. if err = pr.GetHeadRepo(); err != nil {
  588. return fmt.Errorf("GetHeadRepo: %v", err)
  589. } else if pr.HeadRepo == nil {
  590. log.Trace("PullRequest[%d].UpdatePatch: ignored cruppted data", pr.ID)
  591. return nil
  592. }
  593. if err = pr.GetBaseRepo(); err != nil {
  594. return fmt.Errorf("GetBaseRepo: %v", err)
  595. }
  596. headGitRepo, err := git.OpenRepository(pr.HeadRepo.RepoPath())
  597. if err != nil {
  598. return fmt.Errorf("OpenRepository: %v", err)
  599. }
  600. // Add a temporary remote.
  601. tmpRemote := com.ToStr(time.Now().UnixNano())
  602. if err = headGitRepo.AddRemote(tmpRemote, RepoPath(pr.BaseRepo.MustOwner().Name, pr.BaseRepo.Name), true); err != nil {
  603. return fmt.Errorf("AddRemote: %v", err)
  604. }
  605. defer func() {
  606. headGitRepo.RemoveRemote(tmpRemote)
  607. }()
  608. remoteBranch := "remotes/" + tmpRemote + "/" + pr.BaseBranch
  609. pr.MergeBase, err = headGitRepo.GetMergeBase(remoteBranch, pr.HeadBranch)
  610. if err != nil {
  611. return fmt.Errorf("GetMergeBase: %v", err)
  612. } else if err = pr.Update(); err != nil {
  613. return fmt.Errorf("Update: %v", err)
  614. }
  615. patch, err := headGitRepo.GetPatch(pr.MergeBase, pr.HeadBranch)
  616. if err != nil {
  617. return fmt.Errorf("GetPatch: %v", err)
  618. }
  619. if err = pr.BaseRepo.SavePatch(pr.Index, patch); err != nil {
  620. return fmt.Errorf("BaseRepo.SavePatch: %v", err)
  621. }
  622. return nil
  623. }
  624. // PushToBaseRepo pushes commits from branches of head repository to
  625. // corresponding branches of base repository.
  626. // FIXME: Only push branches that are actually updates?
  627. func (pr *PullRequest) PushToBaseRepo() (err error) {
  628. log.Trace("PushToBaseRepo[%d]: pushing commits to base repo 'refs/pull/%d/head'", pr.BaseRepoID, pr.Index)
  629. headRepoPath := pr.HeadRepo.RepoPath()
  630. headGitRepo, err := git.OpenRepository(headRepoPath)
  631. if err != nil {
  632. return fmt.Errorf("OpenRepository: %v", err)
  633. }
  634. tmpRemoteName := fmt.Sprintf("tmp-pull-%d", pr.ID)
  635. if err = headGitRepo.AddRemote(tmpRemoteName, pr.BaseRepo.RepoPath(), false); err != nil {
  636. return fmt.Errorf("headGitRepo.AddRemote: %v", err)
  637. }
  638. // Make sure to remove the remote even if the push fails
  639. defer headGitRepo.RemoveRemote(tmpRemoteName)
  640. headFile := fmt.Sprintf("refs/pull/%d/head", pr.Index)
  641. // Remove head in case there is a conflict.
  642. file := path.Join(pr.BaseRepo.RepoPath(), headFile)
  643. _ = os.Remove(file)
  644. if err = git.Push(headRepoPath, tmpRemoteName, fmt.Sprintf("%s:%s", pr.HeadBranch, headFile)); err != nil {
  645. return fmt.Errorf("Push: %v", err)
  646. }
  647. return nil
  648. }
  649. // AddToTaskQueue adds itself to pull request test task queue.
  650. func (pr *PullRequest) AddToTaskQueue() {
  651. go pullRequestQueue.AddFunc(pr.ID, func() {
  652. pr.Status = PullRequestStatusChecking
  653. if err := pr.UpdateCols("status"); err != nil {
  654. log.Error(5, "AddToTaskQueue.UpdateCols[%d].(add to queue): %v", pr.ID, err)
  655. }
  656. })
  657. }
  658. // PullRequestList defines a list of pull requests
  659. type PullRequestList []*PullRequest
  660. func (prs PullRequestList) loadAttributes(e Engine) error {
  661. if len(prs) == 0 {
  662. return nil
  663. }
  664. // Load issues.
  665. issueIDs := make([]int64, 0, len(prs))
  666. for i := range prs {
  667. issueIDs = append(issueIDs, prs[i].IssueID)
  668. }
  669. issues := make([]*Issue, 0, len(issueIDs))
  670. if err := e.
  671. Where("id > 0").
  672. In("id", issueIDs).
  673. Find(&issues); err != nil {
  674. return fmt.Errorf("find issues: %v", err)
  675. }
  676. set := make(map[int64]*Issue)
  677. for i := range issues {
  678. set[issues[i].ID] = issues[i]
  679. }
  680. for i := range prs {
  681. prs[i].Issue = set[prs[i].IssueID]
  682. }
  683. return nil
  684. }
  685. // LoadAttributes load all the prs attributes
  686. func (prs PullRequestList) LoadAttributes() error {
  687. return prs.loadAttributes(x)
  688. }
  689. func addHeadRepoTasks(prs []*PullRequest) {
  690. for _, pr := range prs {
  691. log.Trace("addHeadRepoTasks[%d]: composing new test task", pr.ID)
  692. if err := pr.UpdatePatch(); err != nil {
  693. log.Error(4, "UpdatePatch: %v", err)
  694. continue
  695. } else if err := pr.PushToBaseRepo(); err != nil {
  696. log.Error(4, "PushToBaseRepo: %v", err)
  697. continue
  698. }
  699. pr.AddToTaskQueue()
  700. }
  701. }
  702. // AddTestPullRequestTask adds new test tasks by given head/base repository and head/base branch,
  703. // and generate new patch for testing as needed.
  704. func AddTestPullRequestTask(doer *User, repoID int64, branch string, isSync bool) {
  705. log.Trace("AddTestPullRequestTask [head_repo_id: %d, head_branch: %s]: finding pull requests", repoID, branch)
  706. prs, err := GetUnmergedPullRequestsByHeadInfo(repoID, branch)
  707. if err != nil {
  708. log.Error(4, "Find pull requests [head_repo_id: %d, head_branch: %s]: %v", repoID, branch, err)
  709. return
  710. }
  711. if isSync {
  712. if err = PullRequestList(prs).LoadAttributes(); err != nil {
  713. log.Error(4, "PullRequestList.LoadAttributes: %v", err)
  714. }
  715. if err == nil {
  716. for _, pr := range prs {
  717. pr.Issue.PullRequest = pr
  718. if err = pr.Issue.LoadAttributes(); err != nil {
  719. log.Error(4, "LoadAttributes: %v", err)
  720. continue
  721. }
  722. if err = PrepareWebhooks(pr.Issue.Repo, HookEventPullRequest, &api.PullRequestPayload{
  723. Action: api.HookIssueSynchronized,
  724. Index: pr.Issue.Index,
  725. PullRequest: pr.Issue.PullRequest.APIFormat(),
  726. Repository: pr.Issue.Repo.APIFormat(AccessModeNone),
  727. Sender: doer.APIFormat(),
  728. }); err != nil {
  729. log.Error(4, "PrepareWebhooks [pull_id: %v]: %v", pr.ID, err)
  730. continue
  731. }
  732. go HookQueue.Add(pr.Issue.Repo.ID)
  733. }
  734. }
  735. }
  736. addHeadRepoTasks(prs)
  737. log.Trace("AddTestPullRequestTask [base_repo_id: %d, base_branch: %s]: finding pull requests", repoID, branch)
  738. prs, err = GetUnmergedPullRequestsByBaseInfo(repoID, branch)
  739. if err != nil {
  740. log.Error(4, "Find pull requests [base_repo_id: %d, base_branch: %s]: %v", repoID, branch, err)
  741. return
  742. }
  743. for _, pr := range prs {
  744. pr.AddToTaskQueue()
  745. }
  746. }
  747. // ChangeUsernameInPullRequests changes the name of head_user_name
  748. func ChangeUsernameInPullRequests(oldUserName, newUserName string) error {
  749. pr := PullRequest{
  750. HeadUserName: strings.ToLower(newUserName),
  751. }
  752. _, err := x.
  753. Cols("head_user_name").
  754. Where("head_user_name = ?", strings.ToLower(oldUserName)).
  755. Update(pr)
  756. return err
  757. }
  758. // checkAndUpdateStatus checks if pull request is possible to levaing checking status,
  759. // and set to be either conflict or mergeable.
  760. func (pr *PullRequest) checkAndUpdateStatus() {
  761. // Status is not changed to conflict means mergeable.
  762. if pr.Status == PullRequestStatusChecking {
  763. pr.Status = PullRequestStatusMergeable
  764. }
  765. // Make sure there is no waiting test to process before levaing the checking status.
  766. if !pullRequestQueue.Exist(pr.ID) {
  767. if err := pr.UpdateCols("status"); err != nil {
  768. log.Error(4, "Update[%d]: %v", pr.ID, err)
  769. }
  770. }
  771. }
  772. // TestPullRequests checks and tests untested patches of pull requests.
  773. // TODO: test more pull requests at same time.
  774. func TestPullRequests() {
  775. prs := make([]*PullRequest, 0, 10)
  776. x.Iterate(PullRequest{
  777. Status: PullRequestStatusChecking,
  778. },
  779. func(idx int, bean interface{}) error {
  780. pr := bean.(*PullRequest)
  781. if err := pr.GetBaseRepo(); err != nil {
  782. log.Error(3, "GetBaseRepo: %v", err)
  783. return nil
  784. }
  785. if err := pr.testPatch(); err != nil {
  786. log.Error(3, "testPatch: %v", err)
  787. return nil
  788. }
  789. prs = append(prs, pr)
  790. return nil
  791. })
  792. // Update pull request status.
  793. for _, pr := range prs {
  794. pr.checkAndUpdateStatus()
  795. }
  796. // Start listening on new test requests.
  797. for prID := range pullRequestQueue.Queue() {
  798. log.Trace("TestPullRequests[%v]: processing test task", prID)
  799. pullRequestQueue.Remove(prID)
  800. pr, err := GetPullRequestByID(com.StrTo(prID).MustInt64())
  801. if err != nil {
  802. log.Error(4, "GetPullRequestByID[%d]: %v", prID, err)
  803. continue
  804. } else if err = pr.testPatch(); err != nil {
  805. log.Error(4, "testPatch[%d]: %v", pr.ID, err)
  806. continue
  807. }
  808. pr.checkAndUpdateStatus()
  809. }
  810. }
  811. // InitTestPullRequests runs the task to test all the checking status pull requests
  812. func InitTestPullRequests() {
  813. go TestPullRequests()
  814. }