pull.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640
  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.UTC().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. if err = notifyWatchers(sess, act); err != nil {
  294. return err
  295. }
  296. pr.Index = pull.Index
  297. if err = repo.SavePatch(pr.Index, patch); err != nil {
  298. return fmt.Errorf("SavePatch: %v", err)
  299. }
  300. pr.BaseRepo = repo
  301. if err = pr.testPatch(); err != nil {
  302. return fmt.Errorf("testPatch: %v", err)
  303. }
  304. if pr.Status == PULL_REQUEST_STATUS_CHECKING {
  305. pr.Status = PULL_REQUEST_STATUS_MERGEABLE
  306. }
  307. pr.IssueID = pull.ID
  308. if _, err = sess.Insert(pr); err != nil {
  309. return fmt.Errorf("insert pull repo: %v", err)
  310. }
  311. return sess.Commit()
  312. }
  313. // GetUnmergedPullRequest returnss a pull request that is open and has not been merged
  314. // by given head/base and repo/branch.
  315. func GetUnmergedPullRequest(headRepoID, baseRepoID int64, headBranch, baseBranch string) (*PullRequest, error) {
  316. pr := new(PullRequest)
  317. has, err := x.Where("head_repo_id=? AND head_branch=? AND base_repo_id=? AND base_branch=? AND has_merged=? AND issue.is_closed=?",
  318. headRepoID, headBranch, baseRepoID, baseBranch, false, false).
  319. Join("INNER", "issue", "issue.id=pull_request.issue_id").Get(pr)
  320. if err != nil {
  321. return nil, err
  322. } else if !has {
  323. return nil, ErrPullRequestNotExist{0, 0, headRepoID, baseRepoID, headBranch, baseBranch}
  324. }
  325. return pr, nil
  326. }
  327. // GetUnmergedPullRequestsByHeadInfo returnss all pull requests that are open and has not been merged
  328. // by given head information (repo and branch).
  329. func GetUnmergedPullRequestsByHeadInfo(repoID int64, branch string) ([]*PullRequest, error) {
  330. prs := make([]*PullRequest, 0, 2)
  331. return prs, x.Where("head_repo_id=? AND head_branch=? AND has_merged=? AND issue.is_closed=?",
  332. repoID, branch, false, false).
  333. Join("INNER", "issue", "issue.id=pull_request.issue_id").Find(&prs)
  334. }
  335. // GetUnmergedPullRequestsByBaseInfo returnss all pull requests that are open and has not been merged
  336. // by given base information (repo and branch).
  337. func GetUnmergedPullRequestsByBaseInfo(repoID int64, branch string) ([]*PullRequest, error) {
  338. prs := make([]*PullRequest, 0, 2)
  339. return prs, x.Where("base_repo_id=? AND base_branch=? AND has_merged=? AND issue.is_closed=?",
  340. repoID, branch, false, false).
  341. Join("INNER", "issue", "issue.id=pull_request.issue_id").Find(&prs)
  342. }
  343. // GetPullRequestByID returns a pull request by given ID.
  344. func GetPullRequestByID(id int64) (*PullRequest, error) {
  345. pr := new(PullRequest)
  346. has, err := x.Id(id).Get(pr)
  347. if err != nil {
  348. return nil, err
  349. } else if !has {
  350. return nil, ErrPullRequestNotExist{id, 0, 0, 0, "", ""}
  351. }
  352. return pr, nil
  353. }
  354. // GetPullRequestByIssueID returns pull request by given issue ID.
  355. func GetPullRequestByIssueID(issueID int64) (*PullRequest, error) {
  356. pr := &PullRequest{
  357. IssueID: issueID,
  358. }
  359. has, err := x.Get(pr)
  360. if err != nil {
  361. return nil, err
  362. } else if !has {
  363. return nil, ErrPullRequestNotExist{0, issueID, 0, 0, "", ""}
  364. }
  365. return pr, nil
  366. }
  367. // Update updates all fields of pull request.
  368. func (pr *PullRequest) Update() error {
  369. _, err := x.Id(pr.ID).AllCols().Update(pr)
  370. return err
  371. }
  372. // Update updates specific fields of pull request.
  373. func (pr *PullRequest) UpdateCols(cols ...string) error {
  374. _, err := x.Id(pr.ID).Cols(cols...).Update(pr)
  375. return err
  376. }
  377. var PullRequestQueue = NewUniqueQueue(setting.Repository.PullRequestQueueLength)
  378. // UpdatePatch generates and saves a new patch.
  379. func (pr *PullRequest) UpdatePatch() (err error) {
  380. if err = pr.GetHeadRepo(); err != nil {
  381. return fmt.Errorf("GetHeadRepo: %v", err)
  382. } else if pr.HeadRepo == nil {
  383. log.Trace("PullRequest[%d].UpdatePatch: ignored cruppted data", pr.ID)
  384. return nil
  385. }
  386. if err = pr.GetBaseRepo(); err != nil {
  387. return fmt.Errorf("GetBaseRepo: %v", err)
  388. }
  389. headGitRepo, err := git.OpenRepository(pr.HeadRepo.RepoPath())
  390. if err != nil {
  391. return fmt.Errorf("OpenRepository: %v", err)
  392. }
  393. // Add a temporary remote.
  394. tmpRemote := com.ToStr(time.Now().UnixNano())
  395. if err = headGitRepo.AddRemote(tmpRemote, RepoPath(pr.BaseRepo.MustOwner().Name, pr.BaseRepo.Name), true); err != nil {
  396. return fmt.Errorf("AddRemote: %v", err)
  397. }
  398. defer func() {
  399. headGitRepo.RemoveRemote(tmpRemote)
  400. }()
  401. remoteBranch := "remotes/" + tmpRemote + "/" + pr.BaseBranch
  402. pr.MergeBase, err = headGitRepo.GetMergeBase(remoteBranch, pr.HeadBranch)
  403. if err != nil {
  404. return fmt.Errorf("GetMergeBase: %v", err)
  405. } else if err = pr.Update(); err != nil {
  406. return fmt.Errorf("Update: %v", err)
  407. }
  408. patch, err := headGitRepo.GetPatch(pr.MergeBase, pr.HeadBranch)
  409. if err != nil {
  410. return fmt.Errorf("GetPatch: %v", err)
  411. }
  412. if err = pr.BaseRepo.SavePatch(pr.Index, patch); err != nil {
  413. return fmt.Errorf("BaseRepo.SavePatch: %v", err)
  414. }
  415. return nil
  416. }
  417. // PushToBaseRepo pushes commits from branches of head repository to
  418. // corresponding branches of base repository.
  419. // FIXME: Only push branches that are actually updates?
  420. func (pr *PullRequest) PushToBaseRepo() (err error) {
  421. log.Trace("PushToBaseRepo[%d]: pushing commits to base repo 'refs/pull/%d/head'", pr.BaseRepoID, pr.Index)
  422. headRepoPath := pr.HeadRepo.RepoPath()
  423. headGitRepo, err := git.OpenRepository(headRepoPath)
  424. if err != nil {
  425. return fmt.Errorf("OpenRepository: %v", err)
  426. }
  427. tmpRemoteName := fmt.Sprintf("tmp-pull-%d", pr.ID)
  428. if err = headGitRepo.AddRemote(tmpRemoteName, pr.BaseRepo.RepoPath(), false); err != nil {
  429. return fmt.Errorf("headGitRepo.AddRemote: %v", err)
  430. }
  431. // Make sure to remove the remote even if the push fails
  432. defer headGitRepo.RemoveRemote(tmpRemoteName)
  433. headFile := fmt.Sprintf("refs/pull/%d/head", pr.Index)
  434. // Remove head in case there is a conflict.
  435. os.Remove(path.Join(pr.BaseRepo.RepoPath(), headFile))
  436. if err = git.Push(headRepoPath, tmpRemoteName, fmt.Sprintf("%s:%s", pr.HeadBranch, headFile)); err != nil {
  437. return fmt.Errorf("Push: %v", err)
  438. }
  439. return nil
  440. }
  441. // AddToTaskQueue adds itself to pull request test task queue.
  442. func (pr *PullRequest) AddToTaskQueue() {
  443. go PullRequestQueue.AddFunc(pr.ID, func() {
  444. pr.Status = PULL_REQUEST_STATUS_CHECKING
  445. if err := pr.UpdateCols("status"); err != nil {
  446. log.Error(5, "AddToTaskQueue.UpdateCols[%d].(add to queue): %v", pr.ID, err)
  447. }
  448. })
  449. }
  450. func addHeadRepoTasks(prs []*PullRequest) {
  451. for _, pr := range prs {
  452. log.Trace("addHeadRepoTasks[%d]: composing new test task", pr.ID)
  453. if err := pr.UpdatePatch(); err != nil {
  454. log.Error(4, "UpdatePatch: %v", err)
  455. continue
  456. } else if err := pr.PushToBaseRepo(); err != nil {
  457. log.Error(4, "PushToBaseRepo: %v", err)
  458. continue
  459. }
  460. pr.AddToTaskQueue()
  461. }
  462. }
  463. // AddTestPullRequestTask adds new test tasks by given head/base repository and head/base branch,
  464. // and generate new patch for testing as needed.
  465. func AddTestPullRequestTask(repoID int64, branch string) {
  466. log.Trace("AddTestPullRequestTask[head_repo_id: %d, head_branch: %s]: finding pull requests", repoID, branch)
  467. prs, err := GetUnmergedPullRequestsByHeadInfo(repoID, branch)
  468. if err != nil {
  469. log.Error(4, "Find pull requests[head_repo_id: %d, head_branch: %s]: %v", repoID, branch, err)
  470. return
  471. }
  472. addHeadRepoTasks(prs)
  473. log.Trace("AddTestPullRequestTask[base_repo_id: %d, base_branch: %s]: finding pull requests", repoID, branch)
  474. prs, err = GetUnmergedPullRequestsByBaseInfo(repoID, branch)
  475. if err != nil {
  476. log.Error(4, "Find pull requests[base_repo_id: %d, base_branch: %s]: %v", repoID, branch, err)
  477. return
  478. }
  479. for _, pr := range prs {
  480. pr.AddToTaskQueue()
  481. }
  482. }
  483. func ChangeUsernameInPullRequests(oldUserName, newUserName string) error {
  484. pr := PullRequest{
  485. HeadUserName: strings.ToLower(newUserName),
  486. }
  487. _, err := x.Cols("head_user_name").Where("head_user_name = ?", strings.ToLower(oldUserName)).Update(pr)
  488. return err
  489. }
  490. // checkAndUpdateStatus checks if pull request is possible to levaing checking status,
  491. // and set to be either conflict or mergeable.
  492. func (pr *PullRequest) checkAndUpdateStatus() {
  493. // Status is not changed to conflict means mergeable.
  494. if pr.Status == PULL_REQUEST_STATUS_CHECKING {
  495. pr.Status = PULL_REQUEST_STATUS_MERGEABLE
  496. }
  497. // Make sure there is no waiting test to process before levaing the checking status.
  498. if !PullRequestQueue.Exist(pr.ID) {
  499. if err := pr.UpdateCols("status"); err != nil {
  500. log.Error(4, "Update[%d]: %v", pr.ID, err)
  501. }
  502. }
  503. }
  504. // TestPullRequests checks and tests untested patches of pull requests.
  505. // TODO: test more pull requests at same time.
  506. func TestPullRequests() {
  507. prs := make([]*PullRequest, 0, 10)
  508. x.Iterate(PullRequest{
  509. Status: PULL_REQUEST_STATUS_CHECKING,
  510. },
  511. func(idx int, bean interface{}) error {
  512. pr := bean.(*PullRequest)
  513. if err := pr.GetBaseRepo(); err != nil {
  514. log.Error(3, "GetBaseRepo: %v", err)
  515. return nil
  516. }
  517. if err := pr.testPatch(); err != nil {
  518. log.Error(3, "testPatch: %v", err)
  519. return nil
  520. }
  521. prs = append(prs, pr)
  522. return nil
  523. })
  524. // Update pull request status.
  525. for _, pr := range prs {
  526. pr.checkAndUpdateStatus()
  527. }
  528. // Start listening on new test requests.
  529. for prID := range PullRequestQueue.Queue() {
  530. log.Trace("TestPullRequests[%v]: processing test task", prID)
  531. PullRequestQueue.Remove(prID)
  532. pr, err := GetPullRequestByID(com.StrTo(prID).MustInt64())
  533. if err != nil {
  534. log.Error(4, "GetPullRequestByID[%d]: %v", prID, err)
  535. continue
  536. } else if err = pr.testPatch(); err != nil {
  537. log.Error(4, "testPatch[%d]: %v", pr.ID, err)
  538. continue
  539. }
  540. pr.checkAndUpdateStatus()
  541. }
  542. }
  543. func InitTestPullRequests() {
  544. go TestPullRequests()
  545. }