pull.go 23 KB

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