pull.go 24 KB

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