pull.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635
  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, pr.Issue.Repo, 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. "error:",
  220. }
  221. // testPatch checks if patch can be merged to base repository without conflit.
  222. // FIXME: make a mechanism to clean up stable local copies.
  223. func (pr *PullRequest) testPatch() (err error) {
  224. if pr.BaseRepo == nil {
  225. pr.BaseRepo, err = GetRepositoryByID(pr.BaseRepoID)
  226. if err != nil {
  227. return fmt.Errorf("GetRepositoryByID: %v", err)
  228. }
  229. }
  230. patchPath, err := pr.BaseRepo.PatchPath(pr.Index)
  231. if err != nil {
  232. return fmt.Errorf("BaseRepo.PatchPath: %v", err)
  233. }
  234. // Fast fail if patch does not exist, this assumes data is cruppted.
  235. if !com.IsFile(patchPath) {
  236. log.Trace("PullRequest[%d].testPatch: ignored cruppted data", pr.ID)
  237. return nil
  238. }
  239. log.Trace("PullRequest[%d].testPatch (patchPath): %s", pr.ID, patchPath)
  240. if err := pr.BaseRepo.UpdateLocalCopy(); err != nil {
  241. return fmt.Errorf("UpdateLocalCopy: %v", err)
  242. }
  243. // Checkout base branch.
  244. _, stderr, err := process.ExecDir(-1, pr.BaseRepo.LocalCopyPath(),
  245. fmt.Sprintf("PullRequest.Merge (git checkout): %v", pr.BaseRepo.ID),
  246. "git", "checkout", pr.BaseBranch)
  247. if err != nil {
  248. return fmt.Errorf("git checkout: %s", stderr)
  249. }
  250. pr.Status = PULL_REQUEST_STATUS_CHECKING
  251. _, stderr, err = process.ExecDir(-1, pr.BaseRepo.LocalCopyPath(),
  252. fmt.Sprintf("testPatch (git apply --check): %d", pr.BaseRepo.ID),
  253. "git", "apply", "--check", patchPath)
  254. if err != nil {
  255. for i := range patchConflicts {
  256. if strings.Contains(stderr, patchConflicts[i]) {
  257. log.Trace("PullRequest[%d].testPatch (apply): has conflit", pr.ID)
  258. fmt.Println(stderr)
  259. pr.Status = PULL_REQUEST_STATUS_CONFLICT
  260. return nil
  261. }
  262. }
  263. return fmt.Errorf("git apply --check: %v - %s", err, stderr)
  264. }
  265. return nil
  266. }
  267. // NewPullRequest creates new pull request with labels for repository.
  268. func NewPullRequest(repo *Repository, pull *Issue, labelIDs []int64, uuids []string, pr *PullRequest, patch []byte) (err error) {
  269. sess := x.NewSession()
  270. defer sessionRelease(sess)
  271. if err = sess.Begin(); err != nil {
  272. return err
  273. }
  274. if err = newIssue(sess, repo, pull, labelIDs, uuids, true); err != nil {
  275. return fmt.Errorf("newIssue: %v", err)
  276. }
  277. // Notify watchers.
  278. act := &Action{
  279. ActUserID: pull.Poster.Id,
  280. ActUserName: pull.Poster.Name,
  281. ActEmail: pull.Poster.Email,
  282. OpType: ACTION_CREATE_PULL_REQUEST,
  283. Content: fmt.Sprintf("%d|%s", pull.Index, pull.Name),
  284. RepoID: repo.ID,
  285. RepoUserName: repo.Owner.Name,
  286. RepoName: repo.Name,
  287. IsPrivate: repo.IsPrivate,
  288. }
  289. if err = notifyWatchers(sess, act); err != nil {
  290. return err
  291. }
  292. pr.Index = pull.Index
  293. if err = repo.SavePatch(pr.Index, patch); err != nil {
  294. return fmt.Errorf("SavePatch: %v", err)
  295. }
  296. pr.BaseRepo = repo
  297. if err = pr.testPatch(); err != nil {
  298. return fmt.Errorf("testPatch: %v", err)
  299. }
  300. if pr.Status == PULL_REQUEST_STATUS_CHECKING {
  301. pr.Status = PULL_REQUEST_STATUS_MERGEABLE
  302. }
  303. pr.IssueID = pull.ID
  304. if _, err = sess.Insert(pr); err != nil {
  305. return fmt.Errorf("insert pull repo: %v", err)
  306. }
  307. return sess.Commit()
  308. }
  309. // GetUnmergedPullRequest returnss a pull request that is open and has not been merged
  310. // by given head/base and repo/branch.
  311. func GetUnmergedPullRequest(headRepoID, baseRepoID int64, headBranch, baseBranch string) (*PullRequest, error) {
  312. pr := new(PullRequest)
  313. has, err := x.Where("head_repo_id=? AND head_branch=? AND base_repo_id=? AND base_branch=? AND has_merged=? AND issue.is_closed=?",
  314. headRepoID, headBranch, baseRepoID, baseBranch, false, false).
  315. Join("INNER", "issue", "issue.id=pull_request.issue_id").Get(pr)
  316. if err != nil {
  317. return nil, err
  318. } else if !has {
  319. return nil, ErrPullRequestNotExist{0, 0, headRepoID, baseRepoID, headBranch, baseBranch}
  320. }
  321. return pr, nil
  322. }
  323. // GetUnmergedPullRequestsByHeadInfo returnss all pull requests that are open and has not been merged
  324. // by given head information (repo and branch).
  325. func GetUnmergedPullRequestsByHeadInfo(repoID int64, branch string) ([]*PullRequest, error) {
  326. prs := make([]*PullRequest, 0, 2)
  327. return prs, x.Where("head_repo_id=? AND head_branch=? AND has_merged=? AND issue.is_closed=?",
  328. repoID, branch, false, false).
  329. Join("INNER", "issue", "issue.id=pull_request.issue_id").Find(&prs)
  330. }
  331. // GetUnmergedPullRequestsByBaseInfo returnss all pull requests that are open and has not been merged
  332. // by given base information (repo and branch).
  333. func GetUnmergedPullRequestsByBaseInfo(repoID int64, branch string) ([]*PullRequest, error) {
  334. prs := make([]*PullRequest, 0, 2)
  335. return prs, x.Where("base_repo_id=? AND base_branch=? AND has_merged=? AND issue.is_closed=?",
  336. repoID, branch, false, false).
  337. Join("INNER", "issue", "issue.id=pull_request.issue_id").Find(&prs)
  338. }
  339. // GetPullRequestByID returns a pull request by given ID.
  340. func GetPullRequestByID(id int64) (*PullRequest, error) {
  341. pr := new(PullRequest)
  342. has, err := x.Id(id).Get(pr)
  343. if err != nil {
  344. return nil, err
  345. } else if !has {
  346. return nil, ErrPullRequestNotExist{id, 0, 0, 0, "", ""}
  347. }
  348. return pr, nil
  349. }
  350. // GetPullRequestByIssueID returns pull request by given issue ID.
  351. func GetPullRequestByIssueID(issueID int64) (*PullRequest, error) {
  352. pr := &PullRequest{
  353. IssueID: issueID,
  354. }
  355. has, err := x.Get(pr)
  356. if err != nil {
  357. return nil, err
  358. } else if !has {
  359. return nil, ErrPullRequestNotExist{0, issueID, 0, 0, "", ""}
  360. }
  361. return pr, nil
  362. }
  363. // Update updates all fields of pull request.
  364. func (pr *PullRequest) Update() error {
  365. _, err := x.Id(pr.ID).AllCols().Update(pr)
  366. return err
  367. }
  368. // Update updates specific fields of pull request.
  369. func (pr *PullRequest) UpdateCols(cols ...string) error {
  370. _, err := x.Id(pr.ID).Cols(cols...).Update(pr)
  371. return err
  372. }
  373. var PullRequestQueue = NewUniqueQueue(setting.Repository.PullRequestQueueLength)
  374. // UpdatePatch generates and saves a new patch.
  375. func (pr *PullRequest) UpdatePatch() (err error) {
  376. if err = pr.GetHeadRepo(); err != nil {
  377. return fmt.Errorf("GetHeadRepo: %v", err)
  378. } else if pr.HeadRepo == nil {
  379. log.Trace("PullRequest[%d].UpdatePatch: ignored cruppted data", pr.ID)
  380. return nil
  381. }
  382. if err = pr.GetBaseRepo(); err != nil {
  383. return fmt.Errorf("GetBaseRepo: %v", err)
  384. }
  385. headGitRepo, err := git.OpenRepository(pr.HeadRepo.RepoPath())
  386. if err != nil {
  387. return fmt.Errorf("OpenRepository: %v", err)
  388. }
  389. // Add a temporary remote.
  390. tmpRemote := com.ToStr(time.Now().UnixNano())
  391. if err = headGitRepo.AddRemote(tmpRemote, RepoPath(pr.BaseRepo.MustOwner().Name, pr.BaseRepo.Name), true); err != nil {
  392. return fmt.Errorf("AddRemote: %v", err)
  393. }
  394. defer func() {
  395. headGitRepo.RemoveRemote(tmpRemote)
  396. }()
  397. remoteBranch := "remotes/" + tmpRemote + "/" + pr.BaseBranch
  398. pr.MergeBase, err = headGitRepo.GetMergeBase(remoteBranch, pr.HeadBranch)
  399. if err != nil {
  400. return fmt.Errorf("GetMergeBase: %v", err)
  401. } else if err = pr.Update(); err != nil {
  402. return fmt.Errorf("Update: %v", err)
  403. }
  404. patch, err := headGitRepo.GetPatch(pr.MergeBase, pr.HeadBranch)
  405. if err != nil {
  406. return fmt.Errorf("GetPatch: %v", err)
  407. }
  408. if err = pr.BaseRepo.SavePatch(pr.Index, patch); err != nil {
  409. return fmt.Errorf("BaseRepo.SavePatch: %v", err)
  410. }
  411. return nil
  412. }
  413. // PushToBaseRepo pushes commits from branches of head repository to
  414. // corresponding branches of base repository.
  415. // FIXME: Only push branches that are actually updates?
  416. func (pr *PullRequest) PushToBaseRepo() (err error) {
  417. log.Trace("PushToBaseRepo[%d]: pushing commits to base repo 'refs/pull/%d/head'", pr.BaseRepoID, pr.Index)
  418. headRepoPath := pr.HeadRepo.RepoPath()
  419. headGitRepo, err := git.OpenRepository(headRepoPath)
  420. if err != nil {
  421. return fmt.Errorf("OpenRepository: %v", err)
  422. }
  423. tmpRemoteName := fmt.Sprintf("tmp-pull-%d", pr.ID)
  424. if err = headGitRepo.AddRemote(tmpRemoteName, pr.BaseRepo.RepoPath(), false); err != nil {
  425. return fmt.Errorf("headGitRepo.AddRemote: %v", err)
  426. }
  427. // Make sure to remove the remote even if the push fails
  428. defer headGitRepo.RemoveRemote(tmpRemoteName)
  429. headFile := fmt.Sprintf("refs/pull/%d/head", pr.Index)
  430. // Remove head in case there is a conflict.
  431. os.Remove(path.Join(pr.BaseRepo.RepoPath(), headFile))
  432. if err = git.Push(headRepoPath, tmpRemoteName, fmt.Sprintf("%s:%s", pr.HeadBranch, headFile)); err != nil {
  433. return fmt.Errorf("Push: %v", err)
  434. }
  435. return nil
  436. }
  437. // AddToTaskQueue adds itself to pull request test task queue.
  438. func (pr *PullRequest) AddToTaskQueue() {
  439. go PullRequestQueue.AddFunc(pr.ID, func() {
  440. pr.Status = PULL_REQUEST_STATUS_CHECKING
  441. if err := pr.UpdateCols("status"); err != nil {
  442. log.Error(5, "AddToTaskQueue.UpdateCols[%d].(add to queue): %v", pr.ID, err)
  443. }
  444. })
  445. }
  446. func addHeadRepoTasks(prs []*PullRequest) {
  447. for _, pr := range prs {
  448. log.Trace("addHeadRepoTasks[%d]: composing new test task", pr.ID)
  449. if err := pr.UpdatePatch(); err != nil {
  450. log.Error(4, "UpdatePatch: %v", err)
  451. continue
  452. } else if err := pr.PushToBaseRepo(); err != nil {
  453. log.Error(4, "PushToBaseRepo: %v", err)
  454. continue
  455. }
  456. pr.AddToTaskQueue()
  457. }
  458. }
  459. // AddTestPullRequestTask adds new test tasks by given head/base repository and head/base branch,
  460. // and generate new patch for testing as needed.
  461. func AddTestPullRequestTask(repoID int64, branch string) {
  462. log.Trace("AddTestPullRequestTask[head_repo_id: %d, head_branch: %s]: finding pull requests", repoID, branch)
  463. prs, err := GetUnmergedPullRequestsByHeadInfo(repoID, branch)
  464. if err != nil {
  465. log.Error(4, "Find pull requests[head_repo_id: %d, head_branch: %s]: %v", repoID, branch, err)
  466. return
  467. }
  468. addHeadRepoTasks(prs)
  469. log.Trace("AddTestPullRequestTask[base_repo_id: %d, base_branch: %s]: finding pull requests", repoID, branch)
  470. prs, err = GetUnmergedPullRequestsByBaseInfo(repoID, branch)
  471. if err != nil {
  472. log.Error(4, "Find pull requests[base_repo_id: %d, base_branch: %s]: %v", repoID, branch, err)
  473. return
  474. }
  475. for _, pr := range prs {
  476. pr.AddToTaskQueue()
  477. }
  478. }
  479. func ChangeUsernameInPullRequests(oldUserName, newUserName string) error {
  480. pr := PullRequest{
  481. HeadUserName: strings.ToLower(newUserName),
  482. }
  483. _, err := x.Cols("head_user_name").Where("head_user_name = ?", strings.ToLower(oldUserName)).Update(pr)
  484. return err
  485. }
  486. // checkAndUpdateStatus checks if pull request is possible to levaing checking status,
  487. // and set to be either conflict or mergeable.
  488. func (pr *PullRequest) checkAndUpdateStatus() {
  489. // Status is not changed to conflict means mergeable.
  490. if pr.Status == PULL_REQUEST_STATUS_CHECKING {
  491. pr.Status = PULL_REQUEST_STATUS_MERGEABLE
  492. }
  493. // Make sure there is no waiting test to process before levaing the checking status.
  494. if !PullRequestQueue.Exist(pr.ID) {
  495. if err := pr.UpdateCols("status"); err != nil {
  496. log.Error(4, "Update[%d]: %v", pr.ID, err)
  497. }
  498. }
  499. }
  500. // TestPullRequests checks and tests untested patches of pull requests.
  501. // TODO: test more pull requests at same time.
  502. func TestPullRequests() {
  503. prs := make([]*PullRequest, 0, 10)
  504. x.Iterate(PullRequest{
  505. Status: PULL_REQUEST_STATUS_CHECKING,
  506. },
  507. func(idx int, bean interface{}) error {
  508. pr := bean.(*PullRequest)
  509. if err := pr.GetBaseRepo(); err != nil {
  510. log.Error(3, "GetBaseRepo: %v", err)
  511. return nil
  512. }
  513. if err := pr.testPatch(); err != nil {
  514. log.Error(3, "testPatch: %v", err)
  515. return nil
  516. }
  517. prs = append(prs, pr)
  518. return nil
  519. })
  520. // Update pull request status.
  521. for _, pr := range prs {
  522. pr.checkAndUpdateStatus()
  523. }
  524. // Start listening on new test requests.
  525. for prID := range PullRequestQueue.Queue() {
  526. log.Trace("TestPullRequests[%v]: processing test task", prID)
  527. PullRequestQueue.Remove(prID)
  528. pr, err := GetPullRequestByID(com.StrTo(prID).MustInt64())
  529. if err != nil {
  530. log.Error(4, "GetPullRequestByID[%d]: %v", prID, err)
  531. continue
  532. } else if err = pr.testPatch(); err != nil {
  533. log.Error(4, "testPatch[%d]: %v", pr.ID, err)
  534. continue
  535. }
  536. pr.checkAndUpdateStatus()
  537. }
  538. }
  539. func InitTestPullRequests() {
  540. go TestPullRequests()
  541. }