pull.go 23 KB

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