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