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.

946 lines
27 KiB

9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 years ago
8 years ago
8 years ago
8 years ago
9 years ago
9 years ago
  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.BranchPrefix + 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. func (pr *PullRequest) testPatch() (err error) {
  354. if pr.BaseRepo == nil {
  355. pr.BaseRepo, err = GetRepositoryByID(pr.BaseRepoID)
  356. if err != nil {
  357. return fmt.Errorf("GetRepositoryByID: %v", err)
  358. }
  359. }
  360. patchPath, err := pr.BaseRepo.PatchPath(pr.Index)
  361. if err != nil {
  362. return fmt.Errorf("BaseRepo.PatchPath: %v", err)
  363. }
  364. // Fast fail if patch does not exist, this assumes data is cruppted.
  365. if !com.IsFile(patchPath) {
  366. log.Trace("PullRequest[%d].testPatch: ignored cruppted data", pr.ID)
  367. return nil
  368. }
  369. repoWorkingPool.CheckIn(com.ToStr(pr.BaseRepoID))
  370. defer repoWorkingPool.CheckOut(com.ToStr(pr.BaseRepoID))
  371. log.Trace("PullRequest[%d].testPatch (patchPath): %s", pr.ID, patchPath)
  372. // Delete old temp local copy before we create a new temp local copy
  373. RemoveAllWithNotice("Deleting old local copy", pr.BaseRepo.LocalCopyPath())
  374. if err := pr.BaseRepo.UpdateLocalCopyBranch(pr.BaseBranch); err != nil {
  375. return fmt.Errorf("UpdateLocalCopy: %v", err)
  376. }
  377. pr.Status = PullRequestStatusChecking
  378. _, stderr, err := process.ExecDir(-1, pr.BaseRepo.LocalCopyPath(),
  379. fmt.Sprintf("testPatch (git apply --check): %d", pr.BaseRepo.ID),
  380. "git", "apply", "--check", patchPath)
  381. if err != nil {
  382. for i := range patchConflicts {
  383. if strings.Contains(stderr, patchConflicts[i]) {
  384. log.Trace("PullRequest[%d].testPatch (apply): has conflict", pr.ID)
  385. fmt.Println(stderr)
  386. pr.Status = PullRequestStatusConflict
  387. return nil
  388. }
  389. }
  390. return fmt.Errorf("git apply --check: %v - %s", err, stderr)
  391. }
  392. return nil
  393. }
  394. // NewPullRequest creates new pull request with labels for repository.
  395. func NewPullRequest(repo *Repository, pull *Issue, labelIDs []int64, uuids []string, pr *PullRequest, patch []byte) (err error) {
  396. sess := x.NewSession()
  397. defer sessionRelease(sess)
  398. if err = sess.Begin(); err != nil {
  399. return err
  400. }
  401. if err = newIssue(sess, NewIssueOptions{
  402. Repo: repo,
  403. Issue: pull,
  404. LableIDs: labelIDs,
  405. Attachments: uuids,
  406. IsPull: true,
  407. }); err != nil {
  408. return fmt.Errorf("newIssue: %v", err)
  409. }
  410. pr.Index = pull.Index
  411. if err = repo.SavePatch(pr.Index, patch); err != nil {
  412. return fmt.Errorf("SavePatch: %v", err)
  413. }
  414. pr.BaseRepo = repo
  415. if err = pr.testPatch(); err != nil {
  416. return fmt.Errorf("testPatch: %v", err)
  417. }
  418. // No conflict appears after test means mergeable.
  419. if pr.Status == PullRequestStatusChecking {
  420. pr.Status = PullRequestStatusMergeable
  421. }
  422. pr.IssueID = pull.ID
  423. if _, err = sess.Insert(pr); err != nil {
  424. return fmt.Errorf("insert pull repo: %v", err)
  425. }
  426. if err = sess.Commit(); err != nil {
  427. return fmt.Errorf("Commit: %v", err)
  428. }
  429. if err = NotifyWatchers(&Action{
  430. ActUserID: pull.Poster.ID,
  431. ActUserName: pull.Poster.Name,
  432. OpType: ActionCreatePullRequest,
  433. Content: fmt.Sprintf("%d|%s", pull.Index, pull.Title),
  434. RepoID: repo.ID,
  435. RepoUserName: repo.Owner.Name,
  436. RepoName: repo.Name,
  437. IsPrivate: repo.IsPrivate,
  438. }); err != nil {
  439. log.Error(4, "NotifyWatchers: %v", err)
  440. } else if err = pull.MailParticipants(); err != nil {
  441. log.Error(4, "MailParticipants: %v", err)
  442. }
  443. pr.Issue = pull
  444. pull.PullRequest = pr
  445. if err = PrepareWebhooks(repo, HookEventPullRequest, &api.PullRequestPayload{
  446. Action: api.HookIssueOpened,
  447. Index: pull.Index,
  448. PullRequest: pr.APIFormat(),
  449. Repository: repo.APIFormat(AccessModeNone),
  450. Sender: pull.Poster.APIFormat(),
  451. }); err != nil {
  452. log.Error(4, "PrepareWebhooks: %v", err)
  453. }
  454. go HookQueue.Add(repo.ID)
  455. return nil
  456. }
  457. // PullRequestsOptions holds the options for PRs
  458. type PullRequestsOptions struct {
  459. Page int
  460. State string
  461. SortType string
  462. Labels []string
  463. MilestoneID int64
  464. }
  465. func listPullRequestStatement(baseRepoID int64, opts *PullRequestsOptions) *xorm.Session {
  466. sess := x.Where("pull_request.base_repo_id=?", baseRepoID)
  467. sess.Join("INNER", "issue", "pull_request.issue_id = issue.id")
  468. switch opts.State {
  469. case "closed", "open":
  470. sess.And("issue.is_closed=?", opts.State == "closed")
  471. }
  472. return sess
  473. }
  474. // PullRequests returns all pull requests for a base Repo by the given conditions
  475. func PullRequests(baseRepoID int64, opts *PullRequestsOptions) ([]*PullRequest, int64, error) {
  476. if opts.Page <= 0 {
  477. opts.Page = 1
  478. }
  479. countSession := listPullRequestStatement(baseRepoID, opts)
  480. maxResults, err := countSession.Count(new(PullRequest))
  481. if err != nil {
  482. log.Error(4, "Count PRs", err)
  483. return nil, maxResults, err
  484. }
  485. prs := make([]*PullRequest, 0, ItemsPerPage)
  486. findSession := listPullRequestStatement(baseRepoID, opts)
  487. findSession.Limit(ItemsPerPage, (opts.Page-1)*ItemsPerPage)
  488. return prs, maxResults, findSession.Find(&prs)
  489. }
  490. // GetUnmergedPullRequest returnss a pull request that is open and has not been merged
  491. // by given head/base and repo/branch.
  492. func GetUnmergedPullRequest(headRepoID, baseRepoID int64, headBranch, baseBranch string) (*PullRequest, error) {
  493. pr := new(PullRequest)
  494. has, err := x.
  495. Where("head_repo_id=? AND head_branch=? AND base_repo_id=? AND base_branch=? AND has_merged=? AND issue.is_closed=?",
  496. headRepoID, headBranch, baseRepoID, baseBranch, false, false).
  497. Join("INNER", "issue", "issue.id=pull_request.issue_id").
  498. Get(pr)
  499. if err != nil {
  500. return nil, err
  501. } else if !has {
  502. return nil, ErrPullRequestNotExist{0, 0, headRepoID, baseRepoID, headBranch, baseBranch}
  503. }
  504. return pr, nil
  505. }
  506. // GetUnmergedPullRequestsByHeadInfo returnss all pull requests that are open and has not been merged
  507. // by given head information (repo and branch).
  508. func GetUnmergedPullRequestsByHeadInfo(repoID int64, branch string) ([]*PullRequest, error) {
  509. prs := make([]*PullRequest, 0, 2)
  510. return prs, x.
  511. Where("head_repo_id = ? AND head_branch = ? AND has_merged = ? AND issue.is_closed = ?",
  512. repoID, branch, false, false).
  513. Join("INNER", "issue", "issue.id = pull_request.issue_id").
  514. Find(&prs)
  515. }
  516. // GetUnmergedPullRequestsByBaseInfo returnss all pull requests that are open and has not been merged
  517. // by given base information (repo and branch).
  518. func GetUnmergedPullRequestsByBaseInfo(repoID int64, branch string) ([]*PullRequest, error) {
  519. prs := make([]*PullRequest, 0, 2)
  520. return prs, x.
  521. Where("base_repo_id=? AND base_branch=? AND has_merged=? AND issue.is_closed=?",
  522. repoID, branch, false, false).
  523. Join("INNER", "issue", "issue.id=pull_request.issue_id").
  524. Find(&prs)
  525. }
  526. // GetPullRequestByIndex returns a pull request by the given index
  527. func GetPullRequestByIndex(repoID int64, index int64) (*PullRequest, error) {
  528. pr := &PullRequest{
  529. BaseRepoID: repoID,
  530. Index: index,
  531. }
  532. has, err := x.Get(pr)
  533. if err != nil {
  534. return nil, err
  535. } else if !has {
  536. return nil, ErrPullRequestNotExist{0, repoID, index, 0, "", ""}
  537. }
  538. if err = pr.LoadAttributes(); err != nil {
  539. return nil, err
  540. }
  541. if err = pr.LoadIssue(); err != nil {
  542. return nil, err
  543. }
  544. return pr, nil
  545. }
  546. func getPullRequestByID(e Engine, id int64) (*PullRequest, error) {
  547. pr := new(PullRequest)
  548. has, err := e.Id(id).Get(pr)
  549. if err != nil {
  550. return nil, err
  551. } else if !has {
  552. return nil, ErrPullRequestNotExist{id, 0, 0, 0, "", ""}
  553. }
  554. return pr, pr.loadAttributes(e)
  555. }
  556. // GetPullRequestByID returns a pull request by given ID.
  557. func GetPullRequestByID(id int64) (*PullRequest, error) {
  558. return getPullRequestByID(x, id)
  559. }
  560. func getPullRequestByIssueID(e Engine, issueID int64) (*PullRequest, error) {
  561. pr := &PullRequest{
  562. IssueID: issueID,
  563. }
  564. has, err := e.Get(pr)
  565. if err != nil {
  566. return nil, err
  567. } else if !has {
  568. return nil, ErrPullRequestNotExist{0, issueID, 0, 0, "", ""}
  569. }
  570. return pr, pr.loadAttributes(e)
  571. }
  572. // GetPullRequestByIssueID returns pull request by given issue ID.
  573. func GetPullRequestByIssueID(issueID int64) (*PullRequest, error) {
  574. return getPullRequestByIssueID(x, issueID)
  575. }
  576. // Update updates all fields of pull request.
  577. func (pr *PullRequest) Update() error {
  578. _, err := x.Id(pr.ID).AllCols().Update(pr)
  579. return err
  580. }
  581. // UpdateCols updates specific fields of pull request.
  582. func (pr *PullRequest) UpdateCols(cols ...string) error {
  583. _, err := x.Id(pr.ID).Cols(cols...).Update(pr)
  584. return err
  585. }
  586. // UpdatePatch generates and saves a new patch.
  587. func (pr *PullRequest) UpdatePatch() (err error) {
  588. if err = pr.GetHeadRepo(); err != nil {
  589. return fmt.Errorf("GetHeadRepo: %v", err)
  590. } else if pr.HeadRepo == nil {
  591. log.Trace("PullRequest[%d].UpdatePatch: ignored cruppted data", pr.ID)
  592. return nil
  593. }
  594. if err = pr.GetBaseRepo(); err != nil {
  595. return fmt.Errorf("GetBaseRepo: %v", err)
  596. }
  597. headGitRepo, err := git.OpenRepository(pr.HeadRepo.RepoPath())
  598. if err != nil {
  599. return fmt.Errorf("OpenRepository: %v", err)
  600. }
  601. // Add a temporary remote.
  602. tmpRemote := com.ToStr(time.Now().UnixNano())
  603. if err = headGitRepo.AddRemote(tmpRemote, RepoPath(pr.BaseRepo.MustOwner().Name, pr.BaseRepo.Name), true); err != nil {
  604. return fmt.Errorf("AddRemote: %v", err)
  605. }
  606. defer func() {
  607. headGitRepo.RemoveRemote(tmpRemote)
  608. }()
  609. remoteBranch := "remotes/" + tmpRemote + "/" + pr.BaseBranch
  610. pr.MergeBase, err = headGitRepo.GetMergeBase(remoteBranch, pr.HeadBranch)
  611. if err != nil {
  612. return fmt.Errorf("GetMergeBase: %v", err)
  613. } else if err = pr.Update(); err != nil {
  614. return fmt.Errorf("Update: %v", err)
  615. }
  616. patch, err := headGitRepo.GetPatch(pr.MergeBase, pr.HeadBranch)
  617. if err != nil {
  618. return fmt.Errorf("GetPatch: %v", err)
  619. }
  620. if err = pr.BaseRepo.SavePatch(pr.Index, patch); err != nil {
  621. return fmt.Errorf("BaseRepo.SavePatch: %v", err)
  622. }
  623. return nil
  624. }
  625. // PushToBaseRepo pushes commits from branches of head repository to
  626. // corresponding branches of base repository.
  627. // FIXME: Only push branches that are actually updates?
  628. func (pr *PullRequest) PushToBaseRepo() (err error) {
  629. log.Trace("PushToBaseRepo[%d]: pushing commits to base repo 'refs/pull/%d/head'", pr.BaseRepoID, pr.Index)
  630. headRepoPath := pr.HeadRepo.RepoPath()
  631. headGitRepo, err := git.OpenRepository(headRepoPath)
  632. if err != nil {
  633. return fmt.Errorf("OpenRepository: %v", err)
  634. }
  635. tmpRemoteName := fmt.Sprintf("tmp-pull-%d", pr.ID)
  636. if err = headGitRepo.AddRemote(tmpRemoteName, pr.BaseRepo.RepoPath(), false); err != nil {
  637. return fmt.Errorf("headGitRepo.AddRemote: %v", err)
  638. }
  639. // Make sure to remove the remote even if the push fails
  640. defer headGitRepo.RemoveRemote(tmpRemoteName)
  641. headFile := fmt.Sprintf("refs/pull/%d/head", pr.Index)
  642. // Remove head in case there is a conflict.
  643. file := path.Join(pr.BaseRepo.RepoPath(), headFile)
  644. _ = os.Remove(file)
  645. if err = git.Push(headRepoPath, tmpRemoteName, fmt.Sprintf("%s:%s", pr.HeadBranch, headFile)); err != nil {
  646. return fmt.Errorf("Push: %v", err)
  647. }
  648. return nil
  649. }
  650. // AddToTaskQueue adds itself to pull request test task queue.
  651. func (pr *PullRequest) AddToTaskQueue() {
  652. go pullRequestQueue.AddFunc(pr.ID, func() {
  653. pr.Status = PullRequestStatusChecking
  654. if err := pr.UpdateCols("status"); err != nil {
  655. log.Error(5, "AddToTaskQueue.UpdateCols[%d].(add to queue): %v", pr.ID, err)
  656. }
  657. })
  658. }
  659. // PullRequestList defines a list of pull requests
  660. type PullRequestList []*PullRequest
  661. func (prs PullRequestList) loadAttributes(e Engine) error {
  662. if len(prs) == 0 {
  663. return nil
  664. }
  665. // Load issues.
  666. issueIDs := make([]int64, 0, len(prs))
  667. for i := range prs {
  668. issueIDs = append(issueIDs, prs[i].IssueID)
  669. }
  670. issues := make([]*Issue, 0, len(issueIDs))
  671. if err := e.
  672. Where("id > 0").
  673. In("id", issueIDs).
  674. Find(&issues); err != nil {
  675. return fmt.Errorf("find issues: %v", err)
  676. }
  677. set := make(map[int64]*Issue)
  678. for i := range issues {
  679. set[issues[i].ID] = issues[i]
  680. }
  681. for i := range prs {
  682. prs[i].Issue = set[prs[i].IssueID]
  683. }
  684. return nil
  685. }
  686. // LoadAttributes load all the prs attributes
  687. func (prs PullRequestList) LoadAttributes() error {
  688. return prs.loadAttributes(x)
  689. }
  690. func addHeadRepoTasks(prs []*PullRequest) {
  691. for _, pr := range prs {
  692. log.Trace("addHeadRepoTasks[%d]: composing new test task", pr.ID)
  693. if err := pr.UpdatePatch(); err != nil {
  694. log.Error(4, "UpdatePatch: %v", err)
  695. continue
  696. } else if err := pr.PushToBaseRepo(); err != nil {
  697. log.Error(4, "PushToBaseRepo: %v", err)
  698. continue
  699. }
  700. pr.AddToTaskQueue()
  701. }
  702. }
  703. // AddTestPullRequestTask adds new test tasks by given head/base repository and head/base branch,
  704. // and generate new patch for testing as needed.
  705. func AddTestPullRequestTask(doer *User, repoID int64, branch string, isSync bool) {
  706. log.Trace("AddTestPullRequestTask [head_repo_id: %d, head_branch: %s]: finding pull requests", repoID, branch)
  707. prs, err := GetUnmergedPullRequestsByHeadInfo(repoID, branch)
  708. if err != nil {
  709. log.Error(4, "Find pull requests [head_repo_id: %d, head_branch: %s]: %v", repoID, branch, err)
  710. return
  711. }
  712. if isSync {
  713. if err = PullRequestList(prs).LoadAttributes(); err != nil {
  714. log.Error(4, "PullRequestList.LoadAttributes: %v", err)
  715. }
  716. if err == nil {
  717. for _, pr := range prs {
  718. pr.Issue.PullRequest = pr
  719. if err = pr.Issue.LoadAttributes(); err != nil {
  720. log.Error(4, "LoadAttributes: %v", err)
  721. continue
  722. }
  723. if err = PrepareWebhooks(pr.Issue.Repo, HookEventPullRequest, &api.PullRequestPayload{
  724. Action: api.HookIssueSynchronized,
  725. Index: pr.Issue.Index,
  726. PullRequest: pr.Issue.PullRequest.APIFormat(),
  727. Repository: pr.Issue.Repo.APIFormat(AccessModeNone),
  728. Sender: doer.APIFormat(),
  729. }); err != nil {
  730. log.Error(4, "PrepareWebhooks [pull_id: %v]: %v", pr.ID, err)
  731. continue
  732. }
  733. go HookQueue.Add(pr.Issue.Repo.ID)
  734. }
  735. }
  736. }
  737. addHeadRepoTasks(prs)
  738. log.Trace("AddTestPullRequestTask [base_repo_id: %d, base_branch: %s]: finding pull requests", repoID, branch)
  739. prs, err = GetUnmergedPullRequestsByBaseInfo(repoID, branch)
  740. if err != nil {
  741. log.Error(4, "Find pull requests [base_repo_id: %d, base_branch: %s]: %v", repoID, branch, err)
  742. return
  743. }
  744. for _, pr := range prs {
  745. pr.AddToTaskQueue()
  746. }
  747. }
  748. // ChangeUsernameInPullRequests changes the name of head_user_name
  749. func ChangeUsernameInPullRequests(oldUserName, newUserName string) error {
  750. pr := PullRequest{
  751. HeadUserName: strings.ToLower(newUserName),
  752. }
  753. _, err := x.
  754. Cols("head_user_name").
  755. Where("head_user_name = ?", strings.ToLower(oldUserName)).
  756. Update(pr)
  757. return err
  758. }
  759. // checkAndUpdateStatus checks if pull request is possible to levaing checking status,
  760. // and set to be either conflict or mergeable.
  761. func (pr *PullRequest) checkAndUpdateStatus() {
  762. // Status is not changed to conflict means mergeable.
  763. if pr.Status == PullRequestStatusChecking {
  764. pr.Status = PullRequestStatusMergeable
  765. }
  766. // Make sure there is no waiting test to process before levaing the checking status.
  767. if !pullRequestQueue.Exist(pr.ID) {
  768. if err := pr.UpdateCols("status"); err != nil {
  769. log.Error(4, "Update[%d]: %v", pr.ID, err)
  770. }
  771. }
  772. }
  773. // TestPullRequests checks and tests untested patches of pull requests.
  774. // TODO: test more pull requests at same time.
  775. func TestPullRequests() {
  776. prs := make([]*PullRequest, 0, 10)
  777. x.Iterate(PullRequest{
  778. Status: PullRequestStatusChecking,
  779. },
  780. func(idx int, bean interface{}) error {
  781. pr := bean.(*PullRequest)
  782. if err := pr.GetBaseRepo(); err != nil {
  783. log.Error(3, "GetBaseRepo: %v", err)
  784. return nil
  785. }
  786. if err := pr.testPatch(); err != nil {
  787. log.Error(3, "testPatch: %v", err)
  788. return nil
  789. }
  790. prs = append(prs, pr)
  791. return nil
  792. })
  793. // Update pull request status.
  794. for _, pr := range prs {
  795. pr.checkAndUpdateStatus()
  796. }
  797. // Start listening on new test requests.
  798. for prID := range pullRequestQueue.Queue() {
  799. log.Trace("TestPullRequests[%v]: processing test task", prID)
  800. pullRequestQueue.Remove(prID)
  801. pr, err := GetPullRequestByID(com.StrTo(prID).MustInt64())
  802. if err != nil {
  803. log.Error(4, "GetPullRequestByID[%s]: %v", prID, err)
  804. continue
  805. } else if err = pr.testPatch(); err != nil {
  806. log.Error(4, "testPatch[%d]: %v", pr.ID, err)
  807. continue
  808. }
  809. pr.checkAndUpdateStatus()
  810. }
  811. }
  812. // InitTestPullRequests runs the task to test all the checking status pull requests
  813. func InitTestPullRequests() {
  814. go TestPullRequests()
  815. }