pull.go 19 KB

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