pull.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795
  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. // patchConflicts is a list of conflit description from Git.
  282. var patchConflicts = []string{
  283. "fatal:",
  284. "error:",
  285. }
  286. // testPatch checks if patch can be merged to base repository without conflit.
  287. // FIXME: make a mechanism to clean up stable local copies.
  288. func (pr *PullRequest) testPatch() (err error) {
  289. if pr.BaseRepo == nil {
  290. pr.BaseRepo, err = GetRepositoryByID(pr.BaseRepoID)
  291. if err != nil {
  292. return fmt.Errorf("GetRepositoryByID: %v", err)
  293. }
  294. }
  295. patchPath, err := pr.BaseRepo.PatchPath(pr.Index)
  296. if err != nil {
  297. return fmt.Errorf("BaseRepo.PatchPath: %v", err)
  298. }
  299. // Fast fail if patch does not exist, this assumes data is cruppted.
  300. if !com.IsFile(patchPath) {
  301. log.Trace("PullRequest[%d].testPatch: ignored cruppted data", pr.ID)
  302. return nil
  303. }
  304. repoWorkingPool.CheckIn(com.ToStr(pr.BaseRepoID))
  305. defer repoWorkingPool.CheckOut(com.ToStr(pr.BaseRepoID))
  306. log.Trace("PullRequest[%d].testPatch (patchPath): %s", pr.ID, patchPath)
  307. if err := pr.BaseRepo.UpdateLocalCopyBranch(pr.BaseBranch); err != nil {
  308. return fmt.Errorf("UpdateLocalCopy [%d]: %v", pr.BaseRepoID, err)
  309. }
  310. pr.Status = PULL_REQUEST_STATUS_CHECKING
  311. _, stderr, err := process.ExecDir(-1, pr.BaseRepo.LocalCopyPath(),
  312. fmt.Sprintf("testPatch (git apply --check): %d", pr.BaseRepo.ID),
  313. "git", "apply", "--check", patchPath)
  314. if err != nil {
  315. for i := range patchConflicts {
  316. if strings.Contains(stderr, patchConflicts[i]) {
  317. log.Trace("PullRequest[%d].testPatch (apply): has conflit\n%s", pr.ID, stderr)
  318. pr.Status = PULL_REQUEST_STATUS_CONFLICT
  319. return nil
  320. }
  321. }
  322. return fmt.Errorf("git apply --check: %v - %s", err, stderr)
  323. }
  324. return nil
  325. }
  326. // NewPullRequest creates new pull request with labels for repository.
  327. func NewPullRequest(repo *Repository, pull *Issue, labelIDs []int64, uuids []string, pr *PullRequest, patch []byte) (err error) {
  328. sess := x.NewSession()
  329. defer sessionRelease(sess)
  330. if err = sess.Begin(); err != nil {
  331. return err
  332. }
  333. if err = newIssue(sess, NewIssueOptions{
  334. Repo: repo,
  335. Issue: pull,
  336. LableIDs: labelIDs,
  337. Attachments: uuids,
  338. IsPull: true,
  339. }); err != nil {
  340. return fmt.Errorf("newIssue: %v", err)
  341. }
  342. pr.Index = pull.Index
  343. if err = repo.SavePatch(pr.Index, patch); err != nil {
  344. return fmt.Errorf("SavePatch: %v", err)
  345. }
  346. pr.BaseRepo = repo
  347. if err = pr.testPatch(); err != nil {
  348. return fmt.Errorf("testPatch: %v", err)
  349. }
  350. // No conflict appears after test means mergeable.
  351. if pr.Status == PULL_REQUEST_STATUS_CHECKING {
  352. pr.Status = PULL_REQUEST_STATUS_MERGEABLE
  353. }
  354. pr.IssueID = pull.ID
  355. if _, err = sess.Insert(pr); err != nil {
  356. return fmt.Errorf("insert pull repo: %v", err)
  357. }
  358. if err = sess.Commit(); err != nil {
  359. return fmt.Errorf("Commit: %v", err)
  360. }
  361. if err = NotifyWatchers(&Action{
  362. ActUserID: pull.Poster.ID,
  363. ActUserName: pull.Poster.Name,
  364. OpType: ACTION_CREATE_PULL_REQUEST,
  365. Content: fmt.Sprintf("%d|%s", pull.Index, pull.Title),
  366. RepoID: repo.ID,
  367. RepoUserName: repo.Owner.Name,
  368. RepoName: repo.Name,
  369. IsPrivate: repo.IsPrivate,
  370. }); err != nil {
  371. log.Error(2, "NotifyWatchers: %v", err)
  372. }
  373. if err = pull.MailParticipants(); err != nil {
  374. log.Error(2, "MailParticipants: %v", err)
  375. }
  376. pr.Issue = pull
  377. pull.PullRequest = pr
  378. if err = PrepareWebhooks(repo, HOOK_EVENT_PULL_REQUEST, &api.PullRequestPayload{
  379. Action: api.HOOK_ISSUE_OPENED,
  380. Index: pull.Index,
  381. PullRequest: pr.APIFormat(),
  382. Repository: repo.APIFormat(nil),
  383. Sender: pull.Poster.APIFormat(),
  384. }); err != nil {
  385. log.Error(2, "PrepareWebhooks: %v", err)
  386. }
  387. return nil
  388. }
  389. // GetUnmergedPullRequest returnss a pull request that is open and has not been merged
  390. // by given head/base and repo/branch.
  391. func GetUnmergedPullRequest(headRepoID, baseRepoID int64, headBranch, baseBranch string) (*PullRequest, error) {
  392. pr := new(PullRequest)
  393. has, err := x.Where("head_repo_id=? AND head_branch=? AND base_repo_id=? AND base_branch=? AND has_merged=? AND issue.is_closed=?",
  394. headRepoID, headBranch, baseRepoID, baseBranch, false, false).
  395. Join("INNER", "issue", "issue.id=pull_request.issue_id").Get(pr)
  396. if err != nil {
  397. return nil, err
  398. } else if !has {
  399. return nil, ErrPullRequestNotExist{0, 0, headRepoID, baseRepoID, headBranch, baseBranch}
  400. }
  401. return pr, nil
  402. }
  403. // GetUnmergedPullRequestsByHeadInfo returnss all pull requests that are open and has not been merged
  404. // by given head information (repo and branch).
  405. func GetUnmergedPullRequestsByHeadInfo(repoID int64, branch string) ([]*PullRequest, error) {
  406. prs := make([]*PullRequest, 0, 2)
  407. return prs, x.Where("head_repo_id = ? AND head_branch = ? AND has_merged = ? AND issue.is_closed = ?",
  408. repoID, branch, false, false).
  409. Join("INNER", "issue", "issue.id = pull_request.issue_id").Find(&prs)
  410. }
  411. // GetUnmergedPullRequestsByBaseInfo returnss all pull requests that are open and has not been merged
  412. // by given base information (repo and branch).
  413. func GetUnmergedPullRequestsByBaseInfo(repoID int64, branch string) ([]*PullRequest, error) {
  414. prs := make([]*PullRequest, 0, 2)
  415. return prs, x.Where("base_repo_id=? AND base_branch=? AND has_merged=? AND issue.is_closed=?",
  416. repoID, branch, false, false).
  417. Join("INNER", "issue", "issue.id=pull_request.issue_id").Find(&prs)
  418. }
  419. func getPullRequestByID(e Engine, id int64) (*PullRequest, error) {
  420. pr := new(PullRequest)
  421. has, err := e.Id(id).Get(pr)
  422. if err != nil {
  423. return nil, err
  424. } else if !has {
  425. return nil, ErrPullRequestNotExist{id, 0, 0, 0, "", ""}
  426. }
  427. return pr, pr.loadAttributes(e)
  428. }
  429. // GetPullRequestByID returns a pull request by given ID.
  430. func GetPullRequestByID(id int64) (*PullRequest, error) {
  431. return getPullRequestByID(x, id)
  432. }
  433. func getPullRequestByIssueID(e Engine, issueID int64) (*PullRequest, error) {
  434. pr := &PullRequest{
  435. IssueID: issueID,
  436. }
  437. has, err := e.Get(pr)
  438. if err != nil {
  439. return nil, err
  440. } else if !has {
  441. return nil, ErrPullRequestNotExist{0, issueID, 0, 0, "", ""}
  442. }
  443. return pr, pr.loadAttributes(e)
  444. }
  445. // GetPullRequestByIssueID returns pull request by given issue ID.
  446. func GetPullRequestByIssueID(issueID int64) (*PullRequest, error) {
  447. return getPullRequestByIssueID(x, issueID)
  448. }
  449. // Update updates all fields of pull request.
  450. func (pr *PullRequest) Update() error {
  451. _, err := x.Id(pr.ID).AllCols().Update(pr)
  452. return err
  453. }
  454. // Update updates specific fields of pull request.
  455. func (pr *PullRequest) UpdateCols(cols ...string) error {
  456. _, err := x.Id(pr.ID).Cols(cols...).Update(pr)
  457. return err
  458. }
  459. // UpdatePatch generates and saves a new patch.
  460. func (pr *PullRequest) UpdatePatch() (err error) {
  461. if pr.HeadRepo == nil {
  462. log.Trace("PullRequest[%d].UpdatePatch: ignored cruppted data", pr.ID)
  463. return nil
  464. }
  465. headGitRepo, err := git.OpenRepository(pr.HeadRepo.RepoPath())
  466. if err != nil {
  467. return fmt.Errorf("OpenRepository: %v", err)
  468. }
  469. // Add a temporary remote.
  470. tmpRemote := com.ToStr(time.Now().UnixNano())
  471. if err = headGitRepo.AddRemote(tmpRemote, RepoPath(pr.BaseRepo.MustOwner().Name, pr.BaseRepo.Name), true); err != nil {
  472. return fmt.Errorf("AddRemote: %v", err)
  473. }
  474. defer func() {
  475. headGitRepo.RemoveRemote(tmpRemote)
  476. }()
  477. remoteBranch := "remotes/" + tmpRemote + "/" + pr.BaseBranch
  478. pr.MergeBase, err = headGitRepo.GetMergeBase(remoteBranch, pr.HeadBranch)
  479. if err != nil {
  480. return fmt.Errorf("GetMergeBase: %v", err)
  481. } else if err = pr.Update(); err != nil {
  482. return fmt.Errorf("Update: %v", err)
  483. }
  484. patch, err := headGitRepo.GetPatch(pr.MergeBase, pr.HeadBranch)
  485. if err != nil {
  486. return fmt.Errorf("GetPatch: %v", err)
  487. }
  488. if err = pr.BaseRepo.SavePatch(pr.Index, patch); err != nil {
  489. return fmt.Errorf("BaseRepo.SavePatch: %v", err)
  490. }
  491. return nil
  492. }
  493. // PushToBaseRepo pushes commits from branches of head repository to
  494. // corresponding branches of base repository.
  495. // FIXME: Only push branches that are actually updates?
  496. func (pr *PullRequest) PushToBaseRepo() (err error) {
  497. log.Trace("PushToBaseRepo[%d]: pushing commits to base repo 'refs/pull/%d/head'", pr.BaseRepoID, pr.Index)
  498. headRepoPath := pr.HeadRepo.RepoPath()
  499. headGitRepo, err := git.OpenRepository(headRepoPath)
  500. if err != nil {
  501. return fmt.Errorf("OpenRepository: %v", err)
  502. }
  503. tmpRemoteName := fmt.Sprintf("tmp-pull-%d", pr.ID)
  504. if err = headGitRepo.AddRemote(tmpRemoteName, pr.BaseRepo.RepoPath(), false); err != nil {
  505. return fmt.Errorf("headGitRepo.AddRemote: %v", err)
  506. }
  507. // Make sure to remove the remote even if the push fails
  508. defer headGitRepo.RemoveRemote(tmpRemoteName)
  509. headFile := fmt.Sprintf("refs/pull/%d/head", pr.Index)
  510. // Remove head in case there is a conflict.
  511. os.Remove(path.Join(pr.BaseRepo.RepoPath(), headFile))
  512. if err = git.Push(headRepoPath, tmpRemoteName, fmt.Sprintf("%s:%s", pr.HeadBranch, headFile)); err != nil {
  513. return fmt.Errorf("Push: %v", err)
  514. }
  515. return nil
  516. }
  517. // AddToTaskQueue adds itself to pull request test task queue.
  518. func (pr *PullRequest) AddToTaskQueue() {
  519. go PullRequestQueue.AddFunc(pr.ID, func() {
  520. pr.Status = PULL_REQUEST_STATUS_CHECKING
  521. if err := pr.UpdateCols("status"); err != nil {
  522. log.Error(5, "AddToTaskQueue.UpdateCols[%d].(add to queue): %v", pr.ID, err)
  523. }
  524. })
  525. }
  526. type PullRequestList []*PullRequest
  527. func (prs PullRequestList) loadAttributes(e Engine) (err error) {
  528. if len(prs) == 0 {
  529. return nil
  530. }
  531. // Load issues
  532. issueIDs := make([]int64, 0, len(prs))
  533. for i := range prs {
  534. issueIDs = append(issueIDs, prs[i].IssueID)
  535. }
  536. issues := make([]*Issue, 0, len(issueIDs))
  537. if err = e.Where("id > 0").In("id", issueIDs).Find(&issues); err != nil {
  538. return fmt.Errorf("find issues: %v", err)
  539. }
  540. set := make(map[int64]*Issue)
  541. for i := range issues {
  542. set[issues[i].ID] = issues[i]
  543. }
  544. for i := range prs {
  545. prs[i].Issue = set[prs[i].IssueID]
  546. }
  547. // Load attributes
  548. for i := range prs {
  549. if err = prs[i].loadAttributes(e); err != nil {
  550. return fmt.Errorf("loadAttributes [%d]: %v", prs[i].ID, err)
  551. }
  552. }
  553. return nil
  554. }
  555. func (prs PullRequestList) LoadAttributes() error {
  556. return prs.loadAttributes(x)
  557. }
  558. func addHeadRepoTasks(prs []*PullRequest) {
  559. for _, pr := range prs {
  560. log.Trace("addHeadRepoTasks[%d]: composing new test task", pr.ID)
  561. if err := pr.UpdatePatch(); err != nil {
  562. log.Error(4, "UpdatePatch: %v", err)
  563. continue
  564. } else if err := pr.PushToBaseRepo(); err != nil {
  565. log.Error(4, "PushToBaseRepo: %v", err)
  566. continue
  567. }
  568. pr.AddToTaskQueue()
  569. }
  570. }
  571. // AddTestPullRequestTask adds new test tasks by given head/base repository and head/base branch,
  572. // and generate new patch for testing as needed.
  573. func AddTestPullRequestTask(doer *User, repoID int64, branch string, isSync bool) {
  574. log.Trace("AddTestPullRequestTask [head_repo_id: %d, head_branch: %s]: finding pull requests", repoID, branch)
  575. prs, err := GetUnmergedPullRequestsByHeadInfo(repoID, branch)
  576. if err != nil {
  577. log.Error(4, "Find pull requests [head_repo_id: %d, head_branch: %s]: %v", repoID, branch, err)
  578. return
  579. }
  580. if isSync {
  581. if err = PullRequestList(prs).LoadAttributes(); err != nil {
  582. log.Error(4, "PullRequestList.LoadAttributes: %v", err)
  583. }
  584. if err == nil {
  585. for _, pr := range prs {
  586. pr.Issue.PullRequest = pr
  587. if err = pr.Issue.LoadAttributes(); err != nil {
  588. log.Error(4, "LoadAttributes: %v", err)
  589. continue
  590. }
  591. if err = PrepareWebhooks(pr.Issue.Repo, HOOK_EVENT_PULL_REQUEST, &api.PullRequestPayload{
  592. Action: api.HOOK_ISSUE_SYNCHRONIZED,
  593. Index: pr.Issue.Index,
  594. PullRequest: pr.Issue.PullRequest.APIFormat(),
  595. Repository: pr.Issue.Repo.APIFormat(nil),
  596. Sender: doer.APIFormat(),
  597. }); err != nil {
  598. log.Error(4, "PrepareWebhooks [pull_id: %v]: %v", pr.ID, err)
  599. continue
  600. }
  601. go HookQueue.Add(pr.Issue.Repo.ID)
  602. }
  603. }
  604. }
  605. addHeadRepoTasks(prs)
  606. log.Trace("AddTestPullRequestTask [base_repo_id: %d, base_branch: %s]: finding pull requests", repoID, branch)
  607. prs, err = GetUnmergedPullRequestsByBaseInfo(repoID, branch)
  608. if err != nil {
  609. log.Error(4, "Find pull requests [base_repo_id: %d, base_branch: %s]: %v", repoID, branch, err)
  610. return
  611. }
  612. for _, pr := range prs {
  613. pr.AddToTaskQueue()
  614. }
  615. }
  616. func ChangeUsernameInPullRequests(oldUserName, newUserName string) error {
  617. pr := PullRequest{
  618. HeadUserName: strings.ToLower(newUserName),
  619. }
  620. _, err := x.Cols("head_user_name").Where("head_user_name = ?", strings.ToLower(oldUserName)).Update(pr)
  621. return err
  622. }
  623. // checkAndUpdateStatus checks if pull request is possible to levaing checking status,
  624. // and set to be either conflict or mergeable.
  625. func (pr *PullRequest) checkAndUpdateStatus() {
  626. // Status is not changed to conflict means mergeable.
  627. if pr.Status == PULL_REQUEST_STATUS_CHECKING {
  628. pr.Status = PULL_REQUEST_STATUS_MERGEABLE
  629. }
  630. // Make sure there is no waiting test to process before levaing the checking status.
  631. if !PullRequestQueue.Exist(pr.ID) {
  632. if err := pr.UpdateCols("status"); err != nil {
  633. log.Error(4, "Update[%d]: %v", pr.ID, err)
  634. }
  635. }
  636. }
  637. // TestPullRequests checks and tests untested patches of pull requests.
  638. // TODO: test more pull requests at same time.
  639. func TestPullRequests() {
  640. prs := make([]*PullRequest, 0, 10)
  641. x.Iterate(PullRequest{
  642. Status: PULL_REQUEST_STATUS_CHECKING,
  643. },
  644. func(idx int, bean interface{}) error {
  645. pr := bean.(*PullRequest)
  646. if err := pr.LoadAttributes(); err != nil {
  647. log.Error(3, "LoadAttributes: %v", err)
  648. return nil
  649. }
  650. if err := pr.testPatch(); err != nil {
  651. log.Error(3, "testPatch: %v", err)
  652. return nil
  653. }
  654. prs = append(prs, pr)
  655. return nil
  656. })
  657. // Update pull request status.
  658. for _, pr := range prs {
  659. pr.checkAndUpdateStatus()
  660. }
  661. // Start listening on new test requests.
  662. for prID := range PullRequestQueue.Queue() {
  663. log.Trace("TestPullRequests[%v]: processing test task", prID)
  664. PullRequestQueue.Remove(prID)
  665. pr, err := GetPullRequestByID(com.StrTo(prID).MustInt64())
  666. if err != nil {
  667. log.Error(4, "GetPullRequestByID[%s]: %v", prID, err)
  668. continue
  669. } else if err = pr.testPatch(); err != nil {
  670. log.Error(4, "testPatch[%d]: %v", pr.ID, err)
  671. continue
  672. }
  673. pr.checkAndUpdateStatus()
  674. }
  675. }
  676. func InitTestPullRequests() {
  677. go TestPullRequests()
  678. }