You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

pull.go 20 kB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638
  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. "strconv"
  19. )
  20. type PullRequestType int
  21. const (
  22. PULL_REQUEST_GOGS PullRequestType = iota
  23. PLLL_ERQUEST_GIT
  24. )
  25. type PullRequestStatus int
  26. const (
  27. PULL_REQUEST_STATUS_CONFLICT PullRequestStatus = iota
  28. PULL_REQUEST_STATUS_CHECKING
  29. PULL_REQUEST_STATUS_MERGEABLE
  30. )
  31. // PullRequest represents relation between pull request and repositories.
  32. type PullRequest struct {
  33. ID int64 `xorm:"pk autoincr"`
  34. Type PullRequestType
  35. Status PullRequestStatus
  36. IssueID int64 `xorm:"INDEX"`
  37. Issue *Issue `xorm:"-"`
  38. Index int64
  39. HeadRepoID int64
  40. HeadRepo *Repository `xorm:"-"`
  41. BaseRepoID int64
  42. BaseRepo *Repository `xorm:"-"`
  43. HeadUserName string
  44. HeadBranch string
  45. BaseBranch string
  46. MergeBase string `xorm:"VARCHAR(40)"`
  47. HasMerged bool
  48. MergedCommitID string `xorm:"VARCHAR(40)"`
  49. Merged time.Time
  50. MergerID int64
  51. Merger *User `xorm:"-"`
  52. }
  53. // Note: don't try to get Pull because will end up recursive querying.
  54. func (pr *PullRequest) AfterSet(colName string, _ xorm.Cell) {
  55. switch colName {
  56. case "merged":
  57. if !pr.HasMerged {
  58. return
  59. }
  60. pr.Merged = regulateTimeZone(pr.Merged)
  61. }
  62. }
  63. func (pr *PullRequest) getHeadRepo(e Engine) (err error) {
  64. pr.HeadRepo, err = getRepositoryByID(e, pr.HeadRepoID)
  65. if err != nil && !IsErrRepoNotExist(err) {
  66. return fmt.Errorf("getRepositoryByID(head): %v", err)
  67. }
  68. return nil
  69. }
  70. func (pr *PullRequest) GetHeadRepo() (err error) {
  71. return pr.getHeadRepo(x)
  72. }
  73. func (pr *PullRequest) GetBaseRepo() (err error) {
  74. if pr.BaseRepo != nil {
  75. return nil
  76. }
  77. pr.BaseRepo, err = GetRepositoryByID(pr.BaseRepoID)
  78. if err != nil {
  79. return fmt.Errorf("GetRepositoryByID(base): %v", err)
  80. }
  81. return nil
  82. }
  83. func (pr *PullRequest) GetMerger() (err error) {
  84. if !pr.HasMerged || pr.Merger != nil {
  85. return nil
  86. }
  87. pr.Merger, err = GetUserByID(pr.MergerID)
  88. if IsErrUserNotExist(err) {
  89. pr.MergerID = -1
  90. pr.Merger = NewFakeUser()
  91. } else if err != nil {
  92. return fmt.Errorf("GetUserByID: %v", err)
  93. }
  94. return nil
  95. }
  96. // IsChecking returns true if this pull request is still checking conflict.
  97. func (pr *PullRequest) IsChecking() bool {
  98. return pr.Status == PULL_REQUEST_STATUS_CHECKING
  99. }
  100. // CanAutoMerge returns true if this pull request can be merged automatically.
  101. func (pr *PullRequest) CanAutoMerge() bool {
  102. return pr.Status == PULL_REQUEST_STATUS_MERGEABLE
  103. }
  104. // Merge merges pull request to base repository.
  105. func (pr *PullRequest) Merge(doer *User, baseGitRepo *git.Repository) (err error) {
  106. if err = pr.GetHeadRepo(); err != nil {
  107. return fmt.Errorf("GetHeadRepo: %v", err)
  108. } else if err = pr.GetBaseRepo(); err != nil {
  109. return fmt.Errorf("GetBaseRepo: %v", err)
  110. }
  111. sess := x.NewSession()
  112. defer sessionRelease(sess)
  113. if err = sess.Begin(); err != nil {
  114. return err
  115. }
  116. if err = pr.Issue.changeStatus(sess, doer, true); err != nil {
  117. return fmt.Errorf("Issue.changeStatus: %v", err)
  118. }
  119. headRepoPath := RepoPath(pr.HeadUserName, pr.HeadRepo.Name)
  120. headGitRepo, err := git.OpenRepository(headRepoPath)
  121. if err != nil {
  122. return fmt.Errorf("OpenRepository: %v", err)
  123. }
  124. pr.MergedCommitID, err = headGitRepo.GetBranchCommitID(pr.HeadBranch)
  125. if err != nil {
  126. return fmt.Errorf("GetBranchCommitID: %v", err)
  127. }
  128. if err = mergePullRequestAction(sess, doer, pr.Issue.Repo, pr.Issue); err != nil {
  129. return fmt.Errorf("mergePullRequestAction: %v", err)
  130. }
  131. pr.HasMerged = true
  132. pr.Merged = time.Now()
  133. pr.MergerID = doer.Id
  134. if _, err = sess.Id(pr.ID).AllCols().Update(pr); err != nil {
  135. return fmt.Errorf("update pull request: %v", err)
  136. }
  137. // Clone base repo.
  138. tmpBasePath := path.Join(setting.AppDataPath, "tmp/repos", com.ToStr(time.Now().Nanosecond())+".git")
  139. os.MkdirAll(path.Dir(tmpBasePath), os.ModePerm)
  140. defer os.RemoveAll(path.Dir(tmpBasePath))
  141. var stderr string
  142. if _, stderr, err = process.ExecTimeout(5*time.Minute,
  143. fmt.Sprintf("PullRequest.Merge (git clone): %s", tmpBasePath),
  144. "git", "clone", baseGitRepo.Path, tmpBasePath); err != nil {
  145. return fmt.Errorf("git clone: %s", stderr)
  146. }
  147. // Check out base branch.
  148. if _, stderr, err = process.ExecDir(-1, tmpBasePath,
  149. fmt.Sprintf("PullRequest.Merge (git checkout): %s", tmpBasePath),
  150. "git", "checkout", pr.BaseBranch); err != nil {
  151. return fmt.Errorf("git checkout: %s", stderr)
  152. }
  153. // Add head repo remote.
  154. if _, stderr, err = process.ExecDir(-1, tmpBasePath,
  155. fmt.Sprintf("PullRequest.Merge (git remote add): %s", tmpBasePath),
  156. "git", "remote", "add", "head_repo", headRepoPath); err != nil {
  157. return fmt.Errorf("git remote add [%s -> %s]: %s", headRepoPath, tmpBasePath, stderr)
  158. }
  159. // Merge commits.
  160. if _, stderr, err = process.ExecDir(-1, tmpBasePath,
  161. fmt.Sprintf("PullRequest.Merge (git fetch): %s", tmpBasePath),
  162. "git", "fetch", "head_repo"); err != nil {
  163. return fmt.Errorf("git fetch [%s -> %s]: %s", headRepoPath, tmpBasePath, stderr)
  164. }
  165. if _, stderr, err = process.ExecDir(-1, tmpBasePath,
  166. fmt.Sprintf("PullRequest.Merge (git merge --no-ff --no-commit): %s", tmpBasePath),
  167. "git", "merge", "--no-ff", "--no-commit", "head_repo/"+pr.HeadBranch); err != nil {
  168. return fmt.Errorf("git merge --no-ff --no-commit [%s]: %v - %s", tmpBasePath, err, stderr)
  169. }
  170. sig := doer.NewGitSig()
  171. if _, stderr, err = process.ExecDir(-1, tmpBasePath,
  172. fmt.Sprintf("PullRequest.Merge (git merge): %s", tmpBasePath),
  173. "git", "commit", fmt.Sprintf("--author='%s <%s>'", sig.Name, sig.Email),
  174. "-m", fmt.Sprintf("Merge branch '%s' of %s/%s into %s", pr.HeadBranch, pr.HeadUserName, pr.HeadRepo.Name, pr.BaseBranch)); err != nil {
  175. return fmt.Errorf("git commit [%s]: %v - %s", tmpBasePath, err, stderr)
  176. }
  177. // Push back to upstream.
  178. if _, stderr, err = process.ExecDir(-1, tmpBasePath,
  179. fmt.Sprintf("PullRequest.Merge (git push): %s", tmpBasePath),
  180. "git", "push", baseGitRepo.Path, pr.BaseBranch); err != nil {
  181. return fmt.Errorf("git push: %s", stderr)
  182. }
  183. if err = sess.Commit(); err != nil {
  184. return fmt.Errorf("Commit: %v", err)
  185. }
  186. // Compose commit repository action
  187. l, err := headGitRepo.CommitsBetweenIDs(pr.MergedCommitID, pr.MergeBase)
  188. if err != nil {
  189. return fmt.Errorf("CommitsBetween: %v", err)
  190. }
  191. p := &api.PushPayload{
  192. Ref: "refs/heads/" + pr.BaseBranch,
  193. Before: pr.MergeBase,
  194. After: pr.MergedCommitID,
  195. CompareUrl: setting.AppUrl + pr.BaseRepo.ComposeCompareURL(pr.MergeBase, pr.MergedCommitID),
  196. Commits: ListToPushCommits(l).ToApiPayloadCommits(pr.BaseRepo.FullRepoLink()),
  197. Repo: pr.BaseRepo.ComposePayload(),
  198. Pusher: &api.PayloadAuthor{
  199. Name: pr.HeadRepo.MustOwner().DisplayName(),
  200. Email: pr.HeadRepo.MustOwner().Email,
  201. UserName: pr.HeadRepo.MustOwner().Name,
  202. },
  203. Sender: &api.PayloadUser{
  204. UserName: doer.Name,
  205. ID: doer.Id,
  206. AvatarUrl: setting.AppUrl + doer.RelAvatarLink(),
  207. },
  208. }
  209. if err = PrepareWebhooks(pr.BaseRepo, HOOK_EVENT_PUSH, p); err != nil {
  210. return fmt.Errorf("PrepareWebhooks: %v", err)
  211. }
  212. go HookQueue.Add(pr.BaseRepo.ID)
  213. return nil
  214. }
  215. // patchConflicts is a list of conflit description from Git.
  216. var patchConflicts = []string{
  217. "patch does not apply",
  218. "already exists in working directory",
  219. "unrecognized input",
  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: 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. func (pr *PullRequest) PushToBaseRepo() (err error) {
  414. log.Trace("PushToBase[%d]: pushing commits to base repo refs/pull/%d/head", pr.ID, pr.ID)
  415. branch := pr.HeadBranch
  416. if err = pr.BaseRepo.GetOwner(); err != nil {
  417. return fmt.Errorf("Could not get base repo owner data: %v", err)
  418. } else if err = pr.HeadRepo.GetOwner(); err != nil {
  419. return fmt.Errorf("Could not get head repo owner data: %v", err)
  420. }
  421. headRepoPath := RepoPath(pr.HeadRepo.Owner.Name, pr.HeadRepo.Name)
  422. prIdStr := strconv.FormatInt(pr.ID, 10)
  423. tmpRemoteName := "tmp-pull-" + branch + "-" + prIdStr
  424. repo, err := git.OpenRepository(headRepoPath)
  425. if err != nil {
  426. return fmt.Errorf("Unable to open head repository: %v", err)
  427. }
  428. if err = repo.AddRemote(tmpRemoteName, RepoPath(pr.BaseRepo.Owner.Name, pr.BaseRepo.Name), false); err != nil {
  429. return fmt.Errorf("Unable to add remote to head repository: %v", err)
  430. }
  431. // Make sure to remove the remote even if the push fails
  432. defer repo.RemoveRemote(tmpRemoteName)
  433. pushRef := branch+":"+"refs/pull/"+prIdStr+"/head"
  434. if err = git.Push(headRepoPath, tmpRemoteName, pushRef); err != nil {
  435. return fmt.Errorf("Error pushing: %v", err)
  436. }
  437. return nil
  438. }
  439. // AddToTaskQueue adds itself to pull request test task queue.
  440. func (pr *PullRequest) AddToTaskQueue() {
  441. go PullRequestQueue.AddFunc(pr.ID, func() {
  442. pr.Status = PULL_REQUEST_STATUS_CHECKING
  443. if err := pr.UpdateCols("status"); err != nil {
  444. log.Error(5, "AddToTaskQueue.UpdateCols[%d].(add to queue): %v", pr.ID, err)
  445. }
  446. })
  447. }
  448. func addHeadRepoTasks(prs []*PullRequest) {
  449. for _, pr := range prs {
  450. log.Trace("addHeadRepoTasks[%d]: composing new test task", pr.ID)
  451. if err := pr.UpdatePatch(); err != nil {
  452. log.Error(4, "UpdatePatch: %v", err)
  453. continue
  454. } else if err := pr.PushToBaseRepo(); err != nil {
  455. log.Error(4, "PushToBaseRepo: %v", err)
  456. continue
  457. }
  458. pr.AddToTaskQueue()
  459. }
  460. }
  461. // AddTestPullRequestTask adds new test tasks by given head/base repository and head/base branch,
  462. // and generate new patch for testing as needed.
  463. func AddTestPullRequestTask(repoID int64, branch string) {
  464. log.Trace("AddTestPullRequestTask[head_repo_id: %d, head_branch: %s]: finding pull requests", repoID, branch)
  465. prs, err := GetUnmergedPullRequestsByHeadInfo(repoID, branch)
  466. if err != nil {
  467. log.Error(4, "Find pull requests[head_repo_id: %d, head_branch: %s]: %v", repoID, branch, err)
  468. return
  469. }
  470. addHeadRepoTasks(prs)
  471. log.Trace("AddTestPullRequestTask[base_repo_id: %d, base_branch: %s]: finding pull requests", repoID, branch)
  472. prs, err = GetUnmergedPullRequestsByBaseInfo(repoID, branch)
  473. if err != nil {
  474. log.Error(4, "Find pull requests[base_repo_id: %d, base_branch: %s]: %v", repoID, branch, err)
  475. return
  476. }
  477. for _, pr := range prs {
  478. pr.AddToTaskQueue()
  479. }
  480. }
  481. func ChangeUsernameInPullRequests(oldUserName, newUserName string) error {
  482. pr := PullRequest{
  483. HeadUserName: strings.ToLower(newUserName),
  484. }
  485. _, err := x.Cols("head_user_name").Where("head_user_name = ?", strings.ToLower(oldUserName)).Update(pr)
  486. return err
  487. }
  488. // checkAndUpdateStatus checks if pull request is possible to levaing checking status,
  489. // and set to be either conflict or mergeable.
  490. func (pr *PullRequest) checkAndUpdateStatus() {
  491. // Status is not changed to conflict means mergeable.
  492. if pr.Status == PULL_REQUEST_STATUS_CHECKING {
  493. pr.Status = PULL_REQUEST_STATUS_MERGEABLE
  494. }
  495. // Make sure there is no waiting test to process before levaing the checking status.
  496. if !PullRequestQueue.Exist(pr.ID) {
  497. if err := pr.UpdateCols("status"); err != nil {
  498. log.Error(4, "Update[%d]: %v", pr.ID, err)
  499. }
  500. }
  501. }
  502. // TestPullRequests checks and tests untested patches of pull requests.
  503. // TODO: test more pull requests at same time.
  504. func TestPullRequests() {
  505. prs := make([]*PullRequest, 0, 10)
  506. x.Iterate(PullRequest{
  507. Status: PULL_REQUEST_STATUS_CHECKING,
  508. },
  509. func(idx int, bean interface{}) error {
  510. pr := bean.(*PullRequest)
  511. if err := pr.GetBaseRepo(); err != nil {
  512. log.Error(3, "GetBaseRepo: %v", err)
  513. return nil
  514. }
  515. if err := pr.testPatch(); err != nil {
  516. log.Error(3, "testPatch: %v", err)
  517. return nil
  518. }
  519. prs = append(prs, pr)
  520. return nil
  521. })
  522. // Update pull request status.
  523. for _, pr := range prs {
  524. pr.checkAndUpdateStatus()
  525. }
  526. // Start listening on new test requests.
  527. for prID := range PullRequestQueue.Queue() {
  528. log.Trace("TestPullRequests[%v]: processing test task", prID)
  529. PullRequestQueue.Remove(prID)
  530. pr, err := GetPullRequestByID(com.StrTo(prID).MustInt64())
  531. if err != nil {
  532. log.Error(4, "GetPullRequestByID[%d]: %v", prID, err)
  533. continue
  534. } else if err = pr.testPatch(); err != nil {
  535. log.Error(4, "testPatch[%d]: %v", pr.ID, err)
  536. continue
  537. }
  538. pr.checkAndUpdateStatus()
  539. }
  540. }
  541. func InitTestPullRequests() {
  542. go TestPullRequests()
  543. }