pull.go 19 KB

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