pull.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783
  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. log "gopkg.in/clog.v1"
  14. "github.com/gogits/git-module"
  15. api "github.com/gogits/go-gogs-client"
  16. "github.com/gogits/gogs/modules/process"
  17. "github.com/gogits/gogs/modules/setting"
  18. "github.com/gogits/gogs/modules/sync"
  19. )
  20. var PullRequestQueue = sync.NewUniqueQueue(setting.Repository.PullRequestQueueLength)
  21. type PullRequestType int
  22. const (
  23. PULL_REQUEST_GOGS PullRequestType = iota
  24. PLLL_ERQUEST_GIT
  25. )
  26. type PullRequestStatus int
  27. const (
  28. PULL_REQUEST_STATUS_CONFLICT PullRequestStatus = iota
  29. PULL_REQUEST_STATUS_CHECKING
  30. PULL_REQUEST_STATUS_MERGEABLE
  31. )
  32. // PullRequest represents relation between pull request and repositories.
  33. type PullRequest struct {
  34. ID int64 `xorm:"pk autoincr"`
  35. Type PullRequestType
  36. Status PullRequestStatus
  37. IssueID int64 `xorm:"INDEX"`
  38. Issue *Issue `xorm:"-"`
  39. Index int64
  40. HeadRepoID int64
  41. HeadRepo *Repository `xorm:"-"`
  42. BaseRepoID int64
  43. BaseRepo *Repository `xorm:"-"`
  44. HeadUserName string
  45. HeadBranch string
  46. BaseBranch string
  47. MergeBase string `xorm:"VARCHAR(40)"`
  48. HasMerged bool
  49. MergedCommitID string `xorm:"VARCHAR(40)"`
  50. MergerID int64
  51. Merger *User `xorm:"-"`
  52. Merged time.Time `xorm:"-"`
  53. MergedUnix int64
  54. }
  55. func (pr *PullRequest) BeforeUpdate() {
  56. pr.MergedUnix = pr.Merged.Unix()
  57. }
  58. // Note: don't try to get Issue because will end up recursive querying.
  59. func (pr *PullRequest) AfterSet(colName string, _ xorm.Cell) {
  60. switch colName {
  61. case "merged_unix":
  62. if !pr.HasMerged {
  63. return
  64. }
  65. pr.Merged = time.Unix(pr.MergedUnix, 0).Local()
  66. }
  67. }
  68. // Note: don't try to get Issue because will end up recursive querying.
  69. func (pr *PullRequest) loadAttributes(e Engine) (err error) {
  70. if pr.HeadRepo == nil {
  71. pr.HeadRepo, err = getRepositoryByID(e, pr.HeadRepoID)
  72. if err != nil && !IsErrRepoNotExist(err) {
  73. return fmt.Errorf("getRepositoryByID.(HeadRepo) [%d]: %v", pr.HeadRepoID, err)
  74. }
  75. }
  76. if pr.BaseRepo == nil {
  77. pr.BaseRepo, err = getRepositoryByID(e, pr.BaseRepoID)
  78. if err != nil {
  79. return fmt.Errorf("getRepositoryByID.(BaseRepo) [%d]: %v", pr.BaseRepoID, err)
  80. }
  81. }
  82. if pr.HasMerged && pr.Merger == nil {
  83. pr.Merger, err = getUserByID(e, pr.MergerID)
  84. if IsErrUserNotExist(err) {
  85. pr.MergerID = -1
  86. pr.Merger = NewGhostUser()
  87. } else if err != nil {
  88. return fmt.Errorf("getUserByID [%d]: %v", pr.MergerID, err)
  89. }
  90. }
  91. return nil
  92. }
  93. func (pr *PullRequest) LoadAttributes() error {
  94. return pr.loadAttributes(x)
  95. }
  96. func (pr *PullRequest) LoadIssue() (err error) {
  97. if pr.Issue != nil {
  98. return nil
  99. }
  100. pr.Issue, err = GetIssueByID(pr.IssueID)
  101. return err
  102. }
  103. // This method assumes following fields have been assigned with valid values:
  104. // Required - Issue, BaseRepo
  105. // Optional - HeadRepo, Merger
  106. func (pr *PullRequest) APIFormat() *api.PullRequest {
  107. // In case of head repo has been deleted.
  108. var apiHeadRepo *api.Repository
  109. if pr.HeadRepo == nil {
  110. apiHeadRepo = &api.Repository{
  111. Name: "deleted",
  112. }
  113. } else {
  114. apiHeadRepo = pr.HeadRepo.APIFormat(nil)
  115. }
  116. apiIssue := pr.Issue.APIFormat()
  117. apiPullRequest := &api.PullRequest{
  118. ID: pr.ID,
  119. Index: pr.Index,
  120. Poster: apiIssue.Poster,
  121. Title: apiIssue.Title,
  122. Body: apiIssue.Body,
  123. Labels: apiIssue.Labels,
  124. Milestone: apiIssue.Milestone,
  125. Assignee: apiIssue.Assignee,
  126. State: apiIssue.State,
  127. Comments: apiIssue.Comments,
  128. HeadBranch: pr.HeadBranch,
  129. HeadRepo: apiHeadRepo,
  130. BaseBranch: pr.BaseBranch,
  131. BaseRepo: pr.BaseRepo.APIFormat(nil),
  132. HTMLURL: pr.Issue.HTMLURL(),
  133. HasMerged: pr.HasMerged,
  134. }
  135. if pr.Status != PULL_REQUEST_STATUS_CHECKING {
  136. mergeable := pr.Status != PULL_REQUEST_STATUS_CONFLICT
  137. apiPullRequest.Mergeable = &mergeable
  138. }
  139. if pr.HasMerged {
  140. apiPullRequest.Merged = &pr.Merged
  141. apiPullRequest.MergedCommitID = &pr.MergedCommitID
  142. apiPullRequest.MergedBy = pr.Merger.APIFormat()
  143. }
  144. return apiPullRequest
  145. }
  146. // IsChecking returns true if this pull request is still checking conflict.
  147. func (pr *PullRequest) IsChecking() bool {
  148. return pr.Status == PULL_REQUEST_STATUS_CHECKING
  149. }
  150. // CanAutoMerge returns true if this pull request can be merged automatically.
  151. func (pr *PullRequest) CanAutoMerge() bool {
  152. return pr.Status == PULL_REQUEST_STATUS_MERGEABLE
  153. }
  154. // Merge merges pull request to base repository.
  155. // FIXME: add repoWorkingPull make sure two merges does not happen at same time.
  156. func (pr *PullRequest) Merge(doer *User, baseGitRepo *git.Repository) (err error) {
  157. defer func() {
  158. go HookQueue.Add(pr.BaseRepo.ID)
  159. go AddTestPullRequestTask(doer, pr.BaseRepo.ID, pr.BaseBranch, false)
  160. }()
  161. sess := x.NewSession()
  162. defer sessionRelease(sess)
  163. if err = sess.Begin(); err != nil {
  164. return err
  165. }
  166. if err = pr.Issue.changeStatus(sess, doer, pr.Issue.Repo, true); err != nil {
  167. return fmt.Errorf("Issue.changeStatus: %v", err)
  168. }
  169. headRepoPath := RepoPath(pr.HeadUserName, pr.HeadRepo.Name)
  170. headGitRepo, err := git.OpenRepository(headRepoPath)
  171. if err != nil {
  172. return fmt.Errorf("OpenRepository: %v", err)
  173. }
  174. // Clone base repo.
  175. tmpBasePath := path.Join(setting.AppDataPath, "tmp/repos", com.ToStr(time.Now().Nanosecond())+".git")
  176. os.MkdirAll(path.Dir(tmpBasePath), os.ModePerm)
  177. defer os.RemoveAll(path.Dir(tmpBasePath))
  178. var stderr string
  179. if _, stderr, err = process.ExecTimeout(5*time.Minute,
  180. fmt.Sprintf("PullRequest.Merge (git clone): %s", tmpBasePath),
  181. "git", "clone", baseGitRepo.Path, tmpBasePath); err != nil {
  182. return fmt.Errorf("git clone: %s", stderr)
  183. }
  184. // Check out base branch.
  185. if _, stderr, err = process.ExecDir(-1, tmpBasePath,
  186. fmt.Sprintf("PullRequest.Merge (git checkout): %s", tmpBasePath),
  187. "git", "checkout", pr.BaseBranch); err != nil {
  188. return fmt.Errorf("git checkout: %s", stderr)
  189. }
  190. // Add head repo remote.
  191. if _, stderr, err = process.ExecDir(-1, tmpBasePath,
  192. fmt.Sprintf("PullRequest.Merge (git remote add): %s", tmpBasePath),
  193. "git", "remote", "add", "head_repo", headRepoPath); err != nil {
  194. return fmt.Errorf("git remote add [%s -> %s]: %s", headRepoPath, tmpBasePath, stderr)
  195. }
  196. // Merge commits.
  197. if _, stderr, err = process.ExecDir(-1, tmpBasePath,
  198. fmt.Sprintf("PullRequest.Merge (git fetch): %s", tmpBasePath),
  199. "git", "fetch", "head_repo"); err != nil {
  200. return fmt.Errorf("git fetch [%s -> %s]: %s", headRepoPath, tmpBasePath, stderr)
  201. }
  202. if _, stderr, err = process.ExecDir(-1, tmpBasePath,
  203. fmt.Sprintf("PullRequest.Merge (git merge --no-ff --no-commit): %s", tmpBasePath),
  204. "git", "merge", "--no-ff", "--no-commit", "head_repo/"+pr.HeadBranch); err != nil {
  205. return fmt.Errorf("git merge --no-ff --no-commit [%s]: %v - %s", tmpBasePath, err, stderr)
  206. }
  207. sig := doer.NewGitSig()
  208. if _, stderr, err = process.ExecDir(-1, tmpBasePath,
  209. fmt.Sprintf("PullRequest.Merge (git merge): %s", tmpBasePath),
  210. "git", "commit", fmt.Sprintf("--author='%s <%s>'", sig.Name, sig.Email),
  211. "-m", fmt.Sprintf("Merge branch '%s' of %s/%s into %s", pr.HeadBranch, pr.HeadUserName, pr.HeadRepo.Name, pr.BaseBranch)); err != nil {
  212. return fmt.Errorf("git commit [%s]: %v - %s", tmpBasePath, err, stderr)
  213. }
  214. // Push back to upstream.
  215. if _, stderr, err = process.ExecDir(-1, tmpBasePath,
  216. fmt.Sprintf("PullRequest.Merge (git push): %s", tmpBasePath),
  217. "git", "push", baseGitRepo.Path, pr.BaseBranch); err != nil {
  218. return fmt.Errorf("git push: %s", stderr)
  219. }
  220. pr.MergedCommitID, err = headGitRepo.GetBranchCommitID(pr.HeadBranch)
  221. if err != nil {
  222. return fmt.Errorf("GetBranchCommit: %v", err)
  223. }
  224. pr.HasMerged = true
  225. pr.Merged = time.Now()
  226. pr.MergerID = doer.ID
  227. if _, err = sess.Id(pr.ID).AllCols().Update(pr); err != nil {
  228. return fmt.Errorf("update pull request: %v", err)
  229. }
  230. if err = sess.Commit(); err != nil {
  231. return fmt.Errorf("Commit: %v", err)
  232. }
  233. if err = MergePullRequestAction(doer, pr.Issue.Repo, pr.Issue); err != nil {
  234. log.Error(4, "MergePullRequestAction [%d]: %v", pr.ID, err)
  235. }
  236. // Reload pull request information.
  237. if err = pr.LoadAttributes(); err != nil {
  238. log.Error(4, "LoadAttributes: %v", err)
  239. return nil
  240. }
  241. if err = PrepareWebhooks(pr.Issue.Repo, HOOK_EVENT_PULL_REQUEST, &api.PullRequestPayload{
  242. Action: api.HOOK_ISSUE_CLOSED,
  243. Index: pr.Index,
  244. PullRequest: pr.APIFormat(),
  245. Repository: pr.Issue.Repo.APIFormat(nil),
  246. Sender: doer.APIFormat(),
  247. }); err != nil {
  248. log.Error(4, "PrepareWebhooks: %v", err)
  249. return nil
  250. }
  251. l, err := headGitRepo.CommitsBetweenIDs(pr.MergedCommitID, pr.MergeBase)
  252. if err != nil {
  253. log.Error(4, "CommitsBetweenIDs: %v", err)
  254. return nil
  255. }
  256. // TODO: when squash commits, no need to append merge commit.
  257. // It is possible that head branch is not fully sync with base branch for merge commits,
  258. // so we need to get latest head commit and append merge commit manully
  259. // to avoid strange diff commits produced.
  260. mergeCommit, err := baseGitRepo.GetBranchCommit(pr.BaseBranch)
  261. if err != nil {
  262. log.Error(4, "GetBranchCommit: %v", err)
  263. return nil
  264. }
  265. l.PushFront(mergeCommit)
  266. p := &api.PushPayload{
  267. Ref: git.BRANCH_PREFIX + pr.BaseBranch,
  268. Before: pr.MergeBase,
  269. After: pr.MergedCommitID,
  270. CompareURL: setting.AppUrl + pr.BaseRepo.ComposeCompareURL(pr.MergeBase, pr.MergedCommitID),
  271. Commits: ListToPushCommits(l).ToApiPayloadCommits(pr.BaseRepo.HTMLURL()),
  272. Repo: pr.BaseRepo.APIFormat(nil),
  273. Pusher: pr.HeadRepo.MustOwner().APIFormat(),
  274. Sender: doer.APIFormat(),
  275. }
  276. if err = PrepareWebhooks(pr.BaseRepo, HOOK_EVENT_PUSH, p); err != nil {
  277. return fmt.Errorf("PrepareWebhooks: %v", err)
  278. }
  279. return nil
  280. }
  281. // testPatch checks if patch can be merged to base repository without conflit.
  282. // FIXME: make a mechanism to clean up stable local copies.
  283. func (pr *PullRequest) testPatch() (err error) {
  284. if pr.BaseRepo == nil {
  285. pr.BaseRepo, err = GetRepositoryByID(pr.BaseRepoID)
  286. if err != nil {
  287. return fmt.Errorf("GetRepositoryByID: %v", err)
  288. }
  289. }
  290. patchPath, err := pr.BaseRepo.PatchPath(pr.Index)
  291. if err != nil {
  292. return fmt.Errorf("BaseRepo.PatchPath: %v", err)
  293. }
  294. // Fast fail if patch does not exist, this assumes data is cruppted.
  295. if !com.IsFile(patchPath) {
  296. log.Trace("PullRequest[%d].testPatch: ignored cruppted data", pr.ID)
  297. return nil
  298. }
  299. repoWorkingPool.CheckIn(com.ToStr(pr.BaseRepoID))
  300. defer repoWorkingPool.CheckOut(com.ToStr(pr.BaseRepoID))
  301. log.Trace("PullRequest[%d].testPatch (patchPath): %s", pr.ID, patchPath)
  302. if err := pr.BaseRepo.UpdateLocalCopyBranch(pr.BaseBranch); err != nil {
  303. return fmt.Errorf("UpdateLocalCopy [%d]: %v", pr.BaseRepoID, err)
  304. }
  305. pr.Status = PULL_REQUEST_STATUS_CHECKING
  306. _, stderr, err := process.ExecDir(-1, pr.BaseRepo.LocalCopyPath(),
  307. fmt.Sprintf("testPatch (git apply --check): %d", pr.BaseRepo.ID),
  308. "git", "apply", "--check", patchPath)
  309. if err != nil {
  310. log.Trace("PullRequest[%d].testPatch (apply): has conflit\n%s", pr.ID, stderr)
  311. pr.Status = PULL_REQUEST_STATUS_CONFLICT
  312. return nil
  313. }
  314. return nil
  315. }
  316. // NewPullRequest creates new pull request with labels for repository.
  317. func NewPullRequest(repo *Repository, pull *Issue, labelIDs []int64, uuids []string, pr *PullRequest, patch []byte) (err error) {
  318. sess := x.NewSession()
  319. defer sessionRelease(sess)
  320. if err = sess.Begin(); err != nil {
  321. return err
  322. }
  323. if err = newIssue(sess, NewIssueOptions{
  324. Repo: repo,
  325. Issue: pull,
  326. LableIDs: labelIDs,
  327. Attachments: uuids,
  328. IsPull: true,
  329. }); err != nil {
  330. return fmt.Errorf("newIssue: %v", err)
  331. }
  332. pr.Index = pull.Index
  333. if err = repo.SavePatch(pr.Index, patch); err != nil {
  334. return fmt.Errorf("SavePatch: %v", err)
  335. }
  336. pr.BaseRepo = repo
  337. if err = pr.testPatch(); err != nil {
  338. return fmt.Errorf("testPatch: %v", err)
  339. }
  340. // No conflict appears after test means mergeable.
  341. if pr.Status == PULL_REQUEST_STATUS_CHECKING {
  342. pr.Status = PULL_REQUEST_STATUS_MERGEABLE
  343. }
  344. pr.IssueID = pull.ID
  345. if _, err = sess.Insert(pr); err != nil {
  346. return fmt.Errorf("insert pull repo: %v", err)
  347. }
  348. if err = sess.Commit(); err != nil {
  349. return fmt.Errorf("Commit: %v", err)
  350. }
  351. if err = NotifyWatchers(&Action{
  352. ActUserID: pull.Poster.ID,
  353. ActUserName: pull.Poster.Name,
  354. OpType: ACTION_CREATE_PULL_REQUEST,
  355. Content: fmt.Sprintf("%d|%s", pull.Index, pull.Title),
  356. RepoID: repo.ID,
  357. RepoUserName: repo.Owner.Name,
  358. RepoName: repo.Name,
  359. IsPrivate: repo.IsPrivate,
  360. }); err != nil {
  361. log.Error(2, "NotifyWatchers: %v", err)
  362. }
  363. if err = pull.MailParticipants(); err != nil {
  364. log.Error(2, "MailParticipants: %v", err)
  365. }
  366. pr.Issue = pull
  367. pull.PullRequest = pr
  368. if err = PrepareWebhooks(repo, HOOK_EVENT_PULL_REQUEST, &api.PullRequestPayload{
  369. Action: api.HOOK_ISSUE_OPENED,
  370. Index: pull.Index,
  371. PullRequest: pr.APIFormat(),
  372. Repository: repo.APIFormat(nil),
  373. Sender: pull.Poster.APIFormat(),
  374. }); err != nil {
  375. log.Error(2, "PrepareWebhooks: %v", err)
  376. }
  377. return nil
  378. }
  379. // GetUnmergedPullRequest returnss a pull request that is open and has not been merged
  380. // by given head/base and repo/branch.
  381. func GetUnmergedPullRequest(headRepoID, baseRepoID int64, headBranch, baseBranch string) (*PullRequest, error) {
  382. pr := new(PullRequest)
  383. has, err := x.Where("head_repo_id=? AND head_branch=? AND base_repo_id=? AND base_branch=? AND has_merged=? AND issue.is_closed=?",
  384. headRepoID, headBranch, baseRepoID, baseBranch, false, false).
  385. Join("INNER", "issue", "issue.id=pull_request.issue_id").Get(pr)
  386. if err != nil {
  387. return nil, err
  388. } else if !has {
  389. return nil, ErrPullRequestNotExist{0, 0, headRepoID, baseRepoID, headBranch, baseBranch}
  390. }
  391. return pr, nil
  392. }
  393. // GetUnmergedPullRequestsByHeadInfo returnss all pull requests that are open and has not been merged
  394. // by given head information (repo and branch).
  395. func GetUnmergedPullRequestsByHeadInfo(repoID int64, branch string) ([]*PullRequest, error) {
  396. prs := make([]*PullRequest, 0, 2)
  397. return prs, x.Where("head_repo_id = ? AND head_branch = ? AND has_merged = ? AND issue.is_closed = ?",
  398. repoID, branch, false, false).
  399. Join("INNER", "issue", "issue.id = pull_request.issue_id").Find(&prs)
  400. }
  401. // GetUnmergedPullRequestsByBaseInfo returnss all pull requests that are open and has not been merged
  402. // by given base information (repo and branch).
  403. func GetUnmergedPullRequestsByBaseInfo(repoID int64, branch string) ([]*PullRequest, error) {
  404. prs := make([]*PullRequest, 0, 2)
  405. return prs, x.Where("base_repo_id=? AND base_branch=? AND has_merged=? AND issue.is_closed=?",
  406. repoID, branch, false, false).
  407. Join("INNER", "issue", "issue.id=pull_request.issue_id").Find(&prs)
  408. }
  409. func getPullRequestByID(e Engine, id int64) (*PullRequest, error) {
  410. pr := new(PullRequest)
  411. has, err := e.Id(id).Get(pr)
  412. if err != nil {
  413. return nil, err
  414. } else if !has {
  415. return nil, ErrPullRequestNotExist{id, 0, 0, 0, "", ""}
  416. }
  417. return pr, pr.loadAttributes(e)
  418. }
  419. // GetPullRequestByID returns a pull request by given ID.
  420. func GetPullRequestByID(id int64) (*PullRequest, error) {
  421. return getPullRequestByID(x, id)
  422. }
  423. func getPullRequestByIssueID(e Engine, issueID int64) (*PullRequest, error) {
  424. pr := &PullRequest{
  425. IssueID: issueID,
  426. }
  427. has, err := e.Get(pr)
  428. if err != nil {
  429. return nil, err
  430. } else if !has {
  431. return nil, ErrPullRequestNotExist{0, issueID, 0, 0, "", ""}
  432. }
  433. return pr, pr.loadAttributes(e)
  434. }
  435. // GetPullRequestByIssueID returns pull request by given issue ID.
  436. func GetPullRequestByIssueID(issueID int64) (*PullRequest, error) {
  437. return getPullRequestByIssueID(x, issueID)
  438. }
  439. // Update updates all fields of pull request.
  440. func (pr *PullRequest) Update() error {
  441. _, err := x.Id(pr.ID).AllCols().Update(pr)
  442. return err
  443. }
  444. // Update updates specific fields of pull request.
  445. func (pr *PullRequest) UpdateCols(cols ...string) error {
  446. _, err := x.Id(pr.ID).Cols(cols...).Update(pr)
  447. return err
  448. }
  449. // UpdatePatch generates and saves a new patch.
  450. func (pr *PullRequest) UpdatePatch() (err error) {
  451. if pr.HeadRepo == nil {
  452. log.Trace("PullRequest[%d].UpdatePatch: ignored cruppted data", pr.ID)
  453. return nil
  454. }
  455. headGitRepo, err := git.OpenRepository(pr.HeadRepo.RepoPath())
  456. if err != nil {
  457. return fmt.Errorf("OpenRepository: %v", err)
  458. }
  459. // Add a temporary remote.
  460. tmpRemote := com.ToStr(time.Now().UnixNano())
  461. if err = headGitRepo.AddRemote(tmpRemote, RepoPath(pr.BaseRepo.MustOwner().Name, pr.BaseRepo.Name), true); err != nil {
  462. return fmt.Errorf("AddRemote: %v", err)
  463. }
  464. defer func() {
  465. headGitRepo.RemoveRemote(tmpRemote)
  466. }()
  467. remoteBranch := "remotes/" + tmpRemote + "/" + pr.BaseBranch
  468. pr.MergeBase, err = headGitRepo.GetMergeBase(remoteBranch, pr.HeadBranch)
  469. if err != nil {
  470. return fmt.Errorf("GetMergeBase: %v", err)
  471. } else if err = pr.Update(); err != nil {
  472. return fmt.Errorf("Update: %v", err)
  473. }
  474. patch, err := headGitRepo.GetPatch(pr.MergeBase, pr.HeadBranch)
  475. if err != nil {
  476. return fmt.Errorf("GetPatch: %v", err)
  477. }
  478. if err = pr.BaseRepo.SavePatch(pr.Index, patch); err != nil {
  479. return fmt.Errorf("BaseRepo.SavePatch: %v", err)
  480. }
  481. return nil
  482. }
  483. // PushToBaseRepo pushes commits from branches of head repository to
  484. // corresponding branches of base repository.
  485. // FIXME: Only push branches that are actually updates?
  486. func (pr *PullRequest) PushToBaseRepo() (err error) {
  487. log.Trace("PushToBaseRepo[%d]: pushing commits to base repo 'refs/pull/%d/head'", pr.BaseRepoID, pr.Index)
  488. headRepoPath := pr.HeadRepo.RepoPath()
  489. headGitRepo, err := git.OpenRepository(headRepoPath)
  490. if err != nil {
  491. return fmt.Errorf("OpenRepository: %v", err)
  492. }
  493. tmpRemoteName := fmt.Sprintf("tmp-pull-%d", pr.ID)
  494. if err = headGitRepo.AddRemote(tmpRemoteName, pr.BaseRepo.RepoPath(), false); err != nil {
  495. return fmt.Errorf("headGitRepo.AddRemote: %v", err)
  496. }
  497. // Make sure to remove the remote even if the push fails
  498. defer headGitRepo.RemoveRemote(tmpRemoteName)
  499. headFile := fmt.Sprintf("refs/pull/%d/head", pr.Index)
  500. // Remove head in case there is a conflict.
  501. os.Remove(path.Join(pr.BaseRepo.RepoPath(), headFile))
  502. if err = git.Push(headRepoPath, tmpRemoteName, fmt.Sprintf("%s:%s", pr.HeadBranch, headFile)); err != nil {
  503. return fmt.Errorf("Push: %v", err)
  504. }
  505. return nil
  506. }
  507. // AddToTaskQueue adds itself to pull request test task queue.
  508. func (pr *PullRequest) AddToTaskQueue() {
  509. go PullRequestQueue.AddFunc(pr.ID, func() {
  510. pr.Status = PULL_REQUEST_STATUS_CHECKING
  511. if err := pr.UpdateCols("status"); err != nil {
  512. log.Error(5, "AddToTaskQueue.UpdateCols[%d].(add to queue): %v", pr.ID, err)
  513. }
  514. })
  515. }
  516. type PullRequestList []*PullRequest
  517. func (prs PullRequestList) loadAttributes(e Engine) (err error) {
  518. if len(prs) == 0 {
  519. return nil
  520. }
  521. // Load issues
  522. issueIDs := make([]int64, 0, len(prs))
  523. for i := range prs {
  524. issueIDs = append(issueIDs, prs[i].IssueID)
  525. }
  526. issues := make([]*Issue, 0, len(issueIDs))
  527. if err = e.Where("id > 0").In("id", issueIDs).Find(&issues); err != nil {
  528. return fmt.Errorf("find issues: %v", err)
  529. }
  530. set := make(map[int64]*Issue)
  531. for i := range issues {
  532. set[issues[i].ID] = issues[i]
  533. }
  534. for i := range prs {
  535. prs[i].Issue = set[prs[i].IssueID]
  536. }
  537. // Load attributes
  538. for i := range prs {
  539. if err = prs[i].loadAttributes(e); err != nil {
  540. return fmt.Errorf("loadAttributes [%d]: %v", prs[i].ID, err)
  541. }
  542. }
  543. return nil
  544. }
  545. func (prs PullRequestList) LoadAttributes() error {
  546. return prs.loadAttributes(x)
  547. }
  548. func addHeadRepoTasks(prs []*PullRequest) {
  549. for _, pr := range prs {
  550. log.Trace("addHeadRepoTasks[%d]: composing new test task", pr.ID)
  551. if err := pr.UpdatePatch(); err != nil {
  552. log.Error(4, "UpdatePatch: %v", err)
  553. continue
  554. } else if err := pr.PushToBaseRepo(); err != nil {
  555. log.Error(4, "PushToBaseRepo: %v", err)
  556. continue
  557. }
  558. pr.AddToTaskQueue()
  559. }
  560. }
  561. // AddTestPullRequestTask adds new test tasks by given head/base repository and head/base branch,
  562. // and generate new patch for testing as needed.
  563. func AddTestPullRequestTask(doer *User, repoID int64, branch string, isSync bool) {
  564. log.Trace("AddTestPullRequestTask [head_repo_id: %d, head_branch: %s]: finding pull requests", repoID, branch)
  565. prs, err := GetUnmergedPullRequestsByHeadInfo(repoID, branch)
  566. if err != nil {
  567. log.Error(4, "Find pull requests [head_repo_id: %d, head_branch: %s]: %v", repoID, branch, err)
  568. return
  569. }
  570. if isSync {
  571. if err = PullRequestList(prs).LoadAttributes(); err != nil {
  572. log.Error(4, "PullRequestList.LoadAttributes: %v", err)
  573. }
  574. if err == nil {
  575. for _, pr := range prs {
  576. pr.Issue.PullRequest = pr
  577. if err = pr.Issue.LoadAttributes(); err != nil {
  578. log.Error(4, "LoadAttributes: %v", err)
  579. continue
  580. }
  581. if err = PrepareWebhooks(pr.Issue.Repo, HOOK_EVENT_PULL_REQUEST, &api.PullRequestPayload{
  582. Action: api.HOOK_ISSUE_SYNCHRONIZED,
  583. Index: pr.Issue.Index,
  584. PullRequest: pr.Issue.PullRequest.APIFormat(),
  585. Repository: pr.Issue.Repo.APIFormat(nil),
  586. Sender: doer.APIFormat(),
  587. }); err != nil {
  588. log.Error(4, "PrepareWebhooks [pull_id: %v]: %v", pr.ID, err)
  589. continue
  590. }
  591. go HookQueue.Add(pr.Issue.Repo.ID)
  592. }
  593. }
  594. }
  595. addHeadRepoTasks(prs)
  596. log.Trace("AddTestPullRequestTask [base_repo_id: %d, base_branch: %s]: finding pull requests", repoID, branch)
  597. prs, err = GetUnmergedPullRequestsByBaseInfo(repoID, branch)
  598. if err != nil {
  599. log.Error(4, "Find pull requests [base_repo_id: %d, base_branch: %s]: %v", repoID, branch, err)
  600. return
  601. }
  602. for _, pr := range prs {
  603. pr.AddToTaskQueue()
  604. }
  605. }
  606. func ChangeUsernameInPullRequests(oldUserName, newUserName string) error {
  607. pr := PullRequest{
  608. HeadUserName: strings.ToLower(newUserName),
  609. }
  610. _, err := x.Cols("head_user_name").Where("head_user_name = ?", strings.ToLower(oldUserName)).Update(pr)
  611. return err
  612. }
  613. // checkAndUpdateStatus checks if pull request is possible to levaing checking status,
  614. // and set to be either conflict or mergeable.
  615. func (pr *PullRequest) checkAndUpdateStatus() {
  616. // Status is not changed to conflict means mergeable.
  617. if pr.Status == PULL_REQUEST_STATUS_CHECKING {
  618. pr.Status = PULL_REQUEST_STATUS_MERGEABLE
  619. }
  620. // Make sure there is no waiting test to process before levaing the checking status.
  621. if !PullRequestQueue.Exist(pr.ID) {
  622. if err := pr.UpdateCols("status"); err != nil {
  623. log.Error(4, "Update[%d]: %v", pr.ID, err)
  624. }
  625. }
  626. }
  627. // TestPullRequests checks and tests untested patches of pull requests.
  628. // TODO: test more pull requests at same time.
  629. func TestPullRequests() {
  630. prs := make([]*PullRequest, 0, 10)
  631. x.Iterate(PullRequest{
  632. Status: PULL_REQUEST_STATUS_CHECKING,
  633. },
  634. func(idx int, bean interface{}) error {
  635. pr := bean.(*PullRequest)
  636. if err := pr.LoadAttributes(); err != nil {
  637. log.Error(3, "LoadAttributes: %v", err)
  638. return nil
  639. }
  640. if err := pr.testPatch(); err != nil {
  641. log.Error(3, "testPatch: %v", err)
  642. return nil
  643. }
  644. prs = append(prs, pr)
  645. return nil
  646. })
  647. // Update pull request status.
  648. for _, pr := range prs {
  649. pr.checkAndUpdateStatus()
  650. }
  651. // Start listening on new test requests.
  652. for prID := range PullRequestQueue.Queue() {
  653. log.Trace("TestPullRequests[%v]: processing test task", prID)
  654. PullRequestQueue.Remove(prID)
  655. pr, err := GetPullRequestByID(com.StrTo(prID).MustInt64())
  656. if err != nil {
  657. log.Error(4, "GetPullRequestByID[%s]: %v", prID, err)
  658. continue
  659. } else if err = pr.testPatch(); err != nil {
  660. log.Error(4, "testPatch[%d]: %v", pr.ID, err)
  661. continue
  662. }
  663. pr.checkAndUpdateStatus()
  664. }
  665. }
  666. func InitTestPullRequests() {
  667. go TestPullRequests()
  668. }