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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600
  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. "github.com/Unknwon/com"
  12. "github.com/go-xorm/xorm"
  13. "github.com/gogits/git-module"
  14. api "github.com/gogits/go-gogs-client"
  15. "github.com/gogits/gogs/modules/log"
  16. "github.com/gogits/gogs/modules/process"
  17. "github.com/gogits/gogs/modules/setting"
  18. )
  19. type PullRequestType int
  20. const (
  21. PULL_REQUEST_GOGS PullRequestType = iota
  22. PLLL_ERQUEST_GIT
  23. )
  24. type PullRequestStatus int
  25. const (
  26. PULL_REQUEST_STATUS_CONFLICT PullRequestStatus = iota
  27. PULL_REQUEST_STATUS_CHECKING
  28. PULL_REQUEST_STATUS_MERGEABLE
  29. )
  30. // PullRequest represents relation between pull request and repositories.
  31. type PullRequest struct {
  32. ID int64 `xorm:"pk autoincr"`
  33. Type PullRequestType
  34. Status PullRequestStatus
  35. IssueID int64 `xorm:"INDEX"`
  36. Issue *Issue `xorm:"-"`
  37. Index int64
  38. HeadRepoID int64
  39. HeadRepo *Repository `xorm:"-"`
  40. BaseRepoID int64
  41. BaseRepo *Repository `xorm:"-"`
  42. HeadUserName string
  43. HeadBranch string
  44. BaseBranch string
  45. MergeBase string `xorm:"VARCHAR(40)"`
  46. HasMerged bool
  47. MergedCommitID string `xorm:"VARCHAR(40)"`
  48. Merged time.Time
  49. MergerID int64
  50. Merger *User `xorm:"-"`
  51. }
  52. // Note: don't try to get Pull because will end up recursive querying.
  53. func (pr *PullRequest) AfterSet(colName string, _ xorm.Cell) {
  54. switch colName {
  55. case "merged":
  56. if !pr.HasMerged {
  57. return
  58. }
  59. pr.Merged = regulateTimeZone(pr.Merged)
  60. }
  61. }
  62. func (pr *PullRequest) getHeadRepo(e Engine) (err error) {
  63. pr.HeadRepo, err = getRepositoryByID(e, pr.HeadRepoID)
  64. if err != nil && !IsErrRepoNotExist(err) {
  65. return fmt.Errorf("getRepositoryByID(head): %v", err)
  66. }
  67. return nil
  68. }
  69. func (pr *PullRequest) GetHeadRepo() (err error) {
  70. return pr.getHeadRepo(x)
  71. }
  72. func (pr *PullRequest) GetBaseRepo() (err error) {
  73. if pr.BaseRepo != nil {
  74. return nil
  75. }
  76. pr.BaseRepo, err = GetRepositoryByID(pr.BaseRepoID)
  77. if err != nil {
  78. return fmt.Errorf("GetRepositoryByID(base): %v", err)
  79. }
  80. return nil
  81. }
  82. func (pr *PullRequest) GetMerger() (err error) {
  83. if !pr.HasMerged || pr.Merger != nil {
  84. return nil
  85. }
  86. pr.Merger, err = GetUserByID(pr.MergerID)
  87. if IsErrUserNotExist(err) {
  88. pr.MergerID = -1
  89. pr.Merger = NewFakeUser()
  90. } else if err != nil {
  91. return fmt.Errorf("GetUserByID: %v", err)
  92. }
  93. return nil
  94. }
  95. // IsChecking returns true if this pull request is still checking conflict.
  96. func (pr *PullRequest) IsChecking() bool {
  97. return pr.Status == PULL_REQUEST_STATUS_CHECKING
  98. }
  99. // CanAutoMerge returns true if this pull request can be merged automatically.
  100. func (pr *PullRequest) CanAutoMerge() bool {
  101. return pr.Status == PULL_REQUEST_STATUS_MERGEABLE
  102. }
  103. // Merge merges pull request to base repository.
  104. func (pr *PullRequest) Merge(doer *User, baseGitRepo *git.Repository) (err error) {
  105. if err = pr.GetHeadRepo(); err != nil {
  106. return fmt.Errorf("GetHeadRepo: %v", err)
  107. } else if err = pr.GetBaseRepo(); err != nil {
  108. return fmt.Errorf("GetBaseRepo: %v", err)
  109. }
  110. sess := x.NewSession()
  111. defer sessionRelease(sess)
  112. if err = sess.Begin(); err != nil {
  113. return err
  114. }
  115. if err = pr.Issue.changeStatus(sess, doer, true); err != nil {
  116. return fmt.Errorf("Issue.changeStatus: %v", err)
  117. }
  118. headRepoPath := RepoPath(pr.HeadUserName, pr.HeadRepo.Name)
  119. headGitRepo, err := git.OpenRepository(headRepoPath)
  120. if err != nil {
  121. return fmt.Errorf("OpenRepository: %v", err)
  122. }
  123. pr.MergedCommitID, err = headGitRepo.GetBranchCommitID(pr.HeadBranch)
  124. if err != nil {
  125. return fmt.Errorf("GetBranchCommitID: %v", err)
  126. }
  127. if err = mergePullRequestAction(sess, doer, pr.Issue.Repo, pr.Issue); err != nil {
  128. return fmt.Errorf("mergePullRequestAction: %v", err)
  129. }
  130. pr.HasMerged = true
  131. pr.Merged = time.Now()
  132. pr.MergerID = doer.Id
  133. if _, err = sess.Id(pr.ID).AllCols().Update(pr); err != nil {
  134. return fmt.Errorf("update pull request: %v", err)
  135. }
  136. // Clone base repo.
  137. tmpBasePath := path.Join(setting.AppDataPath, "tmp/repos", com.ToStr(time.Now().Nanosecond())+".git")
  138. os.MkdirAll(path.Dir(tmpBasePath), os.ModePerm)
  139. defer os.RemoveAll(path.Dir(tmpBasePath))
  140. var stderr string
  141. if _, stderr, err = process.ExecTimeout(5*time.Minute,
  142. fmt.Sprintf("PullRequest.Merge (git clone): %s", tmpBasePath),
  143. "git", "clone", baseGitRepo.Path, tmpBasePath); err != nil {
  144. return fmt.Errorf("git clone: %s", stderr)
  145. }
  146. // Check out base branch.
  147. if _, stderr, err = process.ExecDir(-1, tmpBasePath,
  148. fmt.Sprintf("PullRequest.Merge (git checkout): %s", tmpBasePath),
  149. "git", "checkout", pr.BaseBranch); err != nil {
  150. return fmt.Errorf("git checkout: %s", stderr)
  151. }
  152. // Add head repo remote.
  153. if _, stderr, err = process.ExecDir(-1, tmpBasePath,
  154. fmt.Sprintf("PullRequest.Merge (git remote add): %s", tmpBasePath),
  155. "git", "remote", "add", "head_repo", headRepoPath); err != nil {
  156. return fmt.Errorf("git remote add [%s -> %s]: %s", headRepoPath, tmpBasePath, stderr)
  157. }
  158. // Merge commits.
  159. if _, stderr, err = process.ExecDir(-1, tmpBasePath,
  160. fmt.Sprintf("PullRequest.Merge (git fetch): %s", tmpBasePath),
  161. "git", "fetch", "head_repo"); err != nil {
  162. return fmt.Errorf("git fetch [%s -> %s]: %s", headRepoPath, tmpBasePath, stderr)
  163. }
  164. if _, stderr, err = process.ExecDir(-1, tmpBasePath,
  165. fmt.Sprintf("PullRequest.Merge (git merge --no-ff --no-commit): %s", tmpBasePath),
  166. "git", "merge", "--no-ff", "--no-commit", "head_repo/"+pr.HeadBranch); err != nil {
  167. return fmt.Errorf("git merge --no-ff --no-commit [%s]: %v - %s", tmpBasePath, err, stderr)
  168. }
  169. sig := doer.NewGitSig()
  170. if _, stderr, err = process.ExecDir(-1, tmpBasePath,
  171. fmt.Sprintf("PullRequest.Merge (git merge): %s", tmpBasePath),
  172. "git", "commit", fmt.Sprintf("--author='%s <%s>'", sig.Name, sig.Email),
  173. "-m", fmt.Sprintf("Merge branch '%s' of %s/%s into %s", pr.HeadBranch, pr.HeadUserName, pr.HeadRepo.Name, pr.BaseBranch)); err != nil {
  174. return fmt.Errorf("git commit [%s]: %v - %s", tmpBasePath, err, stderr)
  175. }
  176. // Push back to upstream.
  177. if _, stderr, err = process.ExecDir(-1, tmpBasePath,
  178. fmt.Sprintf("PullRequest.Merge (git push): %s", tmpBasePath),
  179. "git", "push", baseGitRepo.Path, pr.BaseBranch); err != nil {
  180. return fmt.Errorf("git push: %s", stderr)
  181. }
  182. if err = sess.Commit(); err != nil {
  183. return fmt.Errorf("Commit: %v", err)
  184. }
  185. // Compose commit repository action
  186. l, err := headGitRepo.CommitsBetweenIDs(pr.MergedCommitID, pr.MergeBase)
  187. if err != nil {
  188. return fmt.Errorf("CommitsBetween: %v", err)
  189. }
  190. p := &api.PushPayload{
  191. Ref: "refs/heads/" + pr.BaseBranch,
  192. Before: pr.MergeBase,
  193. After: pr.MergedCommitID,
  194. CompareUrl: setting.AppUrl + pr.BaseRepo.ComposeCompareURL(pr.MergeBase, pr.MergedCommitID),
  195. Commits: ListToPushCommits(l).ToApiPayloadCommits(pr.BaseRepo.FullRepoLink()),
  196. Repo: pr.BaseRepo.ComposePayload(),
  197. Pusher: &api.PayloadAuthor{
  198. Name: pr.HeadRepo.MustOwner().DisplayName(),
  199. Email: pr.HeadRepo.MustOwner().Email,
  200. UserName: pr.HeadRepo.MustOwner().Name,
  201. },
  202. Sender: &api.PayloadUser{
  203. UserName: doer.Name,
  204. ID: doer.Id,
  205. AvatarUrl: setting.AppUrl + doer.RelAvatarLink(),
  206. },
  207. }
  208. if err = PrepareWebhooks(pr.BaseRepo, HOOK_EVENT_PUSH, p); err != nil {
  209. return fmt.Errorf("PrepareWebhooks: %v", err)
  210. }
  211. go HookQueue.Add(pr.BaseRepo.ID)
  212. return nil
  213. }
  214. // patchConflicts is a list of conflit description from Git.
  215. var patchConflicts = []string{
  216. "patch does not apply",
  217. "already exists in working directory",
  218. "unrecognized input",
  219. }
  220. // testPatch checks if patch can be merged to base repository without conflit.
  221. // FIXME: make a mechanism to clean up stable local copies.
  222. func (pr *PullRequest) testPatch() (err error) {
  223. if pr.BaseRepo == nil {
  224. pr.BaseRepo, err = GetRepositoryByID(pr.BaseRepoID)
  225. if err != nil {
  226. return fmt.Errorf("GetRepositoryByID: %v", err)
  227. }
  228. }
  229. patchPath, err := pr.BaseRepo.PatchPath(pr.Index)
  230. if err != nil {
  231. return fmt.Errorf("BaseRepo.PatchPath: %v", err)
  232. }
  233. // Fast fail if patch does not exist, this assumes data is cruppted.
  234. if !com.IsFile(patchPath) {
  235. log.Trace("PullRequest[%d].testPatch: ignored cruppted data", pr.ID)
  236. return nil
  237. }
  238. log.Trace("PullRequest[%d].testPatch(patchPath): %s", pr.ID, patchPath)
  239. if err := pr.BaseRepo.UpdateLocalCopy(); err != nil {
  240. return fmt.Errorf("UpdateLocalCopy: %v", err)
  241. }
  242. // Checkout base branch.
  243. _, stderr, err := process.ExecDir(-1, pr.BaseRepo.LocalCopyPath(),
  244. fmt.Sprintf("PullRequest.Merge(git checkout): %v", pr.BaseRepo.ID),
  245. "git", "checkout", pr.BaseBranch)
  246. if err != nil {
  247. return fmt.Errorf("git checkout: %s", stderr)
  248. }
  249. pr.Status = PULL_REQUEST_STATUS_CHECKING
  250. _, stderr, err = process.ExecDir(-1, pr.BaseRepo.LocalCopyPath(),
  251. fmt.Sprintf("testPatch(git apply --check): %d", pr.BaseRepo.ID),
  252. "git", "apply", "--check", patchPath)
  253. if err != nil {
  254. for i := range patchConflicts {
  255. if strings.Contains(stderr, patchConflicts[i]) {
  256. log.Trace("PullRequest[%d].testPatch(apply): has conflit", pr.ID)
  257. fmt.Println(stderr)
  258. pr.Status = PULL_REQUEST_STATUS_CONFLICT
  259. return nil
  260. }
  261. }
  262. return fmt.Errorf("git apply --check: %v - %s", err, stderr)
  263. }
  264. return nil
  265. }
  266. // NewPullRequest creates new pull request with labels for repository.
  267. func NewPullRequest(repo *Repository, pull *Issue, labelIDs []int64, uuids []string, pr *PullRequest, patch []byte) (err error) {
  268. sess := x.NewSession()
  269. defer sessionRelease(sess)
  270. if err = sess.Begin(); err != nil {
  271. return err
  272. }
  273. if err = newIssue(sess, repo, pull, labelIDs, uuids, true); err != nil {
  274. return fmt.Errorf("newIssue: %v", err)
  275. }
  276. // Notify watchers.
  277. act := &Action{
  278. ActUserID: pull.Poster.Id,
  279. ActUserName: pull.Poster.Name,
  280. ActEmail: pull.Poster.Email,
  281. OpType: CREATE_PULL_REQUEST,
  282. Content: fmt.Sprintf("%d|%s", pull.Index, pull.Name),
  283. RepoID: repo.ID,
  284. RepoUserName: repo.Owner.Name,
  285. RepoName: repo.Name,
  286. IsPrivate: repo.IsPrivate,
  287. }
  288. if err = notifyWatchers(sess, act); err != nil {
  289. return err
  290. }
  291. pr.Index = pull.Index
  292. if err = repo.SavePatch(pr.Index, patch); err != nil {
  293. return fmt.Errorf("SavePatch: %v", err)
  294. }
  295. pr.BaseRepo = repo
  296. if err = pr.testPatch(); err != nil {
  297. return fmt.Errorf("testPatch: %v", err)
  298. }
  299. if pr.Status == PULL_REQUEST_STATUS_CHECKING {
  300. pr.Status = PULL_REQUEST_STATUS_MERGEABLE
  301. }
  302. pr.IssueID = pull.ID
  303. if _, err = sess.Insert(pr); err != nil {
  304. return fmt.Errorf("insert pull repo: %v", err)
  305. }
  306. return sess.Commit()
  307. }
  308. // GetUnmergedPullRequest returnss a pull request that is open and has not been merged
  309. // by given head/base and repo/branch.
  310. func GetUnmergedPullRequest(headRepoID, baseRepoID int64, headBranch, baseBranch string) (*PullRequest, error) {
  311. pr := new(PullRequest)
  312. has, err := x.Where("head_repo_id=? AND head_branch=? AND base_repo_id=? AND base_branch=? AND has_merged=? AND issue.is_closed=?",
  313. headRepoID, headBranch, baseRepoID, baseBranch, false, false).
  314. Join("INNER", "issue", "issue.id=pull_request.issue_id").Get(pr)
  315. if err != nil {
  316. return nil, err
  317. } else if !has {
  318. return nil, ErrPullRequestNotExist{0, 0, headRepoID, baseRepoID, headBranch, baseBranch}
  319. }
  320. return pr, nil
  321. }
  322. // GetUnmergedPullRequestsByHeadInfo returnss all pull requests that are open and has not been merged
  323. // by given head information (repo and branch).
  324. func GetUnmergedPullRequestsByHeadInfo(repoID int64, branch string) ([]*PullRequest, error) {
  325. prs := make([]*PullRequest, 0, 2)
  326. return prs, x.Where("head_repo_id=? AND head_branch=? AND has_merged=? AND issue.is_closed=?",
  327. repoID, branch, false, false).
  328. Join("INNER", "issue", "issue.id=pull_request.issue_id").Find(&prs)
  329. }
  330. // GetUnmergedPullRequestsByBaseInfo returnss all pull requests that are open and has not been merged
  331. // by given base information (repo and branch).
  332. func GetUnmergedPullRequestsByBaseInfo(repoID int64, branch string) ([]*PullRequest, error) {
  333. prs := make([]*PullRequest, 0, 2)
  334. return prs, x.Where("base_repo_id=? AND base_branch=? AND has_merged=? AND issue.is_closed=?",
  335. repoID, branch, false, false).
  336. Join("INNER", "issue", "issue.id=pull_request.issue_id").Find(&prs)
  337. }
  338. // GetPullRequestByID returns a pull request by given ID.
  339. func GetPullRequestByID(id int64) (*PullRequest, error) {
  340. pr := new(PullRequest)
  341. has, err := x.Id(id).Get(pr)
  342. if err != nil {
  343. return nil, err
  344. } else if !has {
  345. return nil, ErrPullRequestNotExist{id, 0, 0, 0, "", ""}
  346. }
  347. return pr, nil
  348. }
  349. // GetPullRequestByIssueID returns pull request by given issue ID.
  350. func GetPullRequestByIssueID(issueID int64) (*PullRequest, error) {
  351. pr := &PullRequest{
  352. IssueID: issueID,
  353. }
  354. has, err := x.Get(pr)
  355. if err != nil {
  356. return nil, err
  357. } else if !has {
  358. return nil, ErrPullRequestNotExist{0, issueID, 0, 0, "", ""}
  359. }
  360. return pr, nil
  361. }
  362. // Update updates all fields of pull request.
  363. func (pr *PullRequest) Update() error {
  364. _, err := x.Id(pr.ID).AllCols().Update(pr)
  365. return err
  366. }
  367. // Update updates specific fields of pull request.
  368. func (pr *PullRequest) UpdateCols(cols ...string) error {
  369. _, err := x.Id(pr.ID).Cols(cols...).Update(pr)
  370. return err
  371. }
  372. var PullRequestQueue = NewUniqueQueue(setting.Repository.PullRequestQueueLength)
  373. // UpdatePatch generates and saves a new patch.
  374. func (pr *PullRequest) UpdatePatch() (err error) {
  375. if err = pr.GetHeadRepo(); err != nil {
  376. return fmt.Errorf("GetHeadRepo: %v", err)
  377. } else if pr.HeadRepo == nil {
  378. log.Trace("PullRequest[%d].UpdatePatch: ignored cruppted data", pr.ID)
  379. return nil
  380. }
  381. if err = pr.GetBaseRepo(); err != nil {
  382. return fmt.Errorf("GetBaseRepo: %v", err)
  383. }
  384. headGitRepo, err := git.OpenRepository(pr.HeadRepo.RepoPath())
  385. if err != nil {
  386. return fmt.Errorf("OpenRepository: %v", err)
  387. }
  388. // Add a temporary remote.
  389. tmpRemote := com.ToStr(time.Now().UnixNano())
  390. if err = headGitRepo.AddRemote(tmpRemote, RepoPath(pr.BaseRepo.MustOwner().Name, pr.BaseRepo.Name), true); err != nil {
  391. return fmt.Errorf("AddRemote: %v", err)
  392. }
  393. defer func() {
  394. headGitRepo.RemoveRemote(tmpRemote)
  395. }()
  396. remoteBranch := "remotes/" + tmpRemote + "/" + pr.BaseBranch
  397. pr.MergeBase, err = headGitRepo.GetMergeBase(remoteBranch, pr.HeadBranch)
  398. if err != nil {
  399. return fmt.Errorf("GetMergeBase: %v", err)
  400. } else if err = pr.Update(); err != nil {
  401. return fmt.Errorf("Update: %v", err)
  402. }
  403. patch, err := headGitRepo.GetPatch(pr.MergeBase, pr.HeadBranch)
  404. if err != nil {
  405. return fmt.Errorf("GetPatch: %v", err)
  406. }
  407. if err = pr.BaseRepo.SavePatch(pr.Index, patch); err != nil {
  408. return fmt.Errorf("BaseRepo.SavePatch: %v", err)
  409. }
  410. return nil
  411. }
  412. // AddToTaskQueue adds itself to pull request test task queue.
  413. func (pr *PullRequest) AddToTaskQueue() {
  414. go PullRequestQueue.AddFunc(pr.ID, func() {
  415. pr.Status = PULL_REQUEST_STATUS_CHECKING
  416. if err := pr.UpdateCols("status"); err != nil {
  417. log.Error(5, "AddToTaskQueue.UpdateCols[%d].(add to queue): %v", pr.ID, err)
  418. }
  419. })
  420. }
  421. func addHeadRepoTasks(prs []*PullRequest) {
  422. for _, pr := range prs {
  423. log.Trace("addHeadRepoTasks[%d]: composing new test task", pr.ID)
  424. if err := pr.UpdatePatch(); err != nil {
  425. log.Error(4, "UpdatePatch: %v", err)
  426. continue
  427. }
  428. pr.AddToTaskQueue()
  429. }
  430. }
  431. // AddTestPullRequestTask adds new test tasks by given head/base repository and head/base branch,
  432. // and generate new patch for testing as needed.
  433. func AddTestPullRequestTask(repoID int64, branch string) {
  434. log.Trace("AddTestPullRequestTask[head_repo_id: %d, head_branch: %s]: finding pull requests", repoID, branch)
  435. prs, err := GetUnmergedPullRequestsByHeadInfo(repoID, branch)
  436. if err != nil {
  437. log.Error(4, "Find pull requests[head_repo_id: %d, head_branch: %s]: %v", repoID, branch, err)
  438. return
  439. }
  440. addHeadRepoTasks(prs)
  441. log.Trace("AddTestPullRequestTask[base_repo_id: %d, base_branch: %s]: finding pull requests", repoID, branch)
  442. prs, err = GetUnmergedPullRequestsByBaseInfo(repoID, branch)
  443. if err != nil {
  444. log.Error(4, "Find pull requests[base_repo_id: %d, base_branch: %s]: %v", repoID, branch, err)
  445. return
  446. }
  447. for _, pr := range prs {
  448. pr.AddToTaskQueue()
  449. }
  450. }
  451. func ChangeUsernameInPullRequests(oldUserName, newUserName string) (error) {
  452. pr := PullRequest{
  453. HeadUserName : newUserName,
  454. }
  455. _, err := x.Cols("head_user_name").Where("head_user_name = ?", oldUserName).Update(pr)
  456. return err
  457. }
  458. // checkAndUpdateStatus checks if pull request is possible to levaing checking status,
  459. // and set to be either conflict or mergeable.
  460. func (pr *PullRequest) checkAndUpdateStatus() {
  461. // Status is not changed to conflict means mergeable.
  462. if pr.Status == PULL_REQUEST_STATUS_CHECKING {
  463. pr.Status = PULL_REQUEST_STATUS_MERGEABLE
  464. }
  465. // Make sure there is no waiting test to process before levaing the checking status.
  466. if !PullRequestQueue.Exist(pr.ID) {
  467. if err := pr.UpdateCols("status"); err != nil {
  468. log.Error(4, "Update[%d]: %v", pr.ID, err)
  469. }
  470. }
  471. }
  472. // TestPullRequests checks and tests untested patches of pull requests.
  473. // TODO: test more pull requests at same time.
  474. func TestPullRequests() {
  475. prs := make([]*PullRequest, 0, 10)
  476. x.Iterate(PullRequest{
  477. Status: PULL_REQUEST_STATUS_CHECKING,
  478. },
  479. func(idx int, bean interface{}) error {
  480. pr := bean.(*PullRequest)
  481. if err := pr.GetBaseRepo(); err != nil {
  482. log.Error(3, "GetBaseRepo: %v", err)
  483. return nil
  484. }
  485. if err := pr.testPatch(); err != nil {
  486. log.Error(3, "testPatch: %v", err)
  487. return nil
  488. }
  489. prs = append(prs, pr)
  490. return nil
  491. })
  492. // Update pull request status.
  493. for _, pr := range prs {
  494. pr.checkAndUpdateStatus()
  495. }
  496. // Start listening on new test requests.
  497. for prID := range PullRequestQueue.Queue() {
  498. log.Trace("TestPullRequests[%v]: processing test task", prID)
  499. PullRequestQueue.Remove(prID)
  500. pr, err := GetPullRequestByID(com.StrTo(prID).MustInt64())
  501. if err != nil {
  502. log.Error(4, "GetPullRequestByID[%d]: %v", prID, err)
  503. continue
  504. } else if err = pr.testPatch(); err != nil {
  505. log.Error(4, "testPatch[%d]: %v", pr.ID, err)
  506. continue
  507. }
  508. pr.checkAndUpdateStatus()
  509. }
  510. }
  511. func InitTestPullRequests() {
  512. go TestPullRequests()
  513. }