Fork to maintain patches against the official gitea for https://code.ceondo.com https://github.com/go-gitea/gitea

pull.go 23KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809
  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. "code.gitea.io/git"
  12. "code.gitea.io/gitea/modules/log"
  13. "code.gitea.io/gitea/modules/process"
  14. "code.gitea.io/gitea/modules/setting"
  15. "code.gitea.io/gitea/modules/sync"
  16. api "code.gitea.io/sdk/gitea"
  17. "github.com/Unknwon/com"
  18. "github.com/go-xorm/xorm"
  19. )
  20. var PullRequestQueue = sync.NewUniqueQueue(setting.Repository.PullRequestQueueLength)
  21. type PullRequestType int
  22. const (
  23. PullRequestGitea PullRequestType = iota
  24. PullRequestGit
  25. )
  26. type PullRequestStatus int
  27. const (
  28. PullRequestStatusConflict PullRequestStatus = iota
  29. PullRequestStatusChecking
  30. PullRequestStatusMergeable
  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. // Optional - Merger
  94. func (pr *PullRequest) APIFormat() *api.PullRequest {
  95. apiIssue := pr.Issue.APIFormat()
  96. apiPullRequest := &api.PullRequest{
  97. ID: pr.ID,
  98. Index: pr.Index,
  99. Poster: apiIssue.Poster,
  100. Title: apiIssue.Title,
  101. Body: apiIssue.Body,
  102. Labels: apiIssue.Labels,
  103. Milestone: apiIssue.Milestone,
  104. Assignee: apiIssue.Assignee,
  105. State: apiIssue.State,
  106. Comments: apiIssue.Comments,
  107. HTMLURL: pr.Issue.HTMLURL(),
  108. HasMerged: pr.HasMerged,
  109. }
  110. if pr.Status != PullRequestStatusChecking {
  111. mergeable := pr.Status != PullRequestStatusConflict
  112. apiPullRequest.Mergeable = &mergeable
  113. }
  114. if pr.HasMerged {
  115. apiPullRequest.Merged = &pr.Merged
  116. apiPullRequest.MergedCommitID = &pr.MergedCommitID
  117. apiPullRequest.MergedBy = pr.Merger.APIFormat()
  118. }
  119. return apiPullRequest
  120. }
  121. func (pr *PullRequest) getHeadRepo(e Engine) (err error) {
  122. pr.HeadRepo, err = getRepositoryByID(e, pr.HeadRepoID)
  123. if err != nil && !IsErrRepoNotExist(err) {
  124. return fmt.Errorf("getRepositoryByID(head): %v", err)
  125. }
  126. return nil
  127. }
  128. func (pr *PullRequest) GetHeadRepo() error {
  129. return pr.getHeadRepo(x)
  130. }
  131. func (pr *PullRequest) GetBaseRepo() (err error) {
  132. if pr.BaseRepo != nil {
  133. return nil
  134. }
  135. pr.BaseRepo, err = GetRepositoryByID(pr.BaseRepoID)
  136. if err != nil {
  137. return fmt.Errorf("GetRepositoryByID(base): %v", err)
  138. }
  139. return nil
  140. }
  141. // IsChecking returns true if this pull request is still checking conflict.
  142. func (pr *PullRequest) IsChecking() bool {
  143. return pr.Status == PullRequestStatusChecking
  144. }
  145. // CanAutoMerge returns true if this pull request can be merged automatically.
  146. func (pr *PullRequest) CanAutoMerge() bool {
  147. return pr.Status == PullRequestStatusMergeable
  148. }
  149. // Merge merges pull request to base repository.
  150. // FIXME: add repoWorkingPull make sure two merges does not happen at same time.
  151. func (pr *PullRequest) Merge(doer *User, baseGitRepo *git.Repository) (err error) {
  152. if err = pr.GetHeadRepo(); err != nil {
  153. return fmt.Errorf("GetHeadRepo: %v", err)
  154. } else if err = pr.GetBaseRepo(); err != nil {
  155. return fmt.Errorf("GetBaseRepo: %v", err)
  156. }
  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, HookEventPullRequest, &api.PullRequestPayload{
  242. Action: api.HookIssueClosed,
  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, HookEventPush, 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. "patch does not apply",
  284. "already exists in working directory",
  285. "unrecognized input",
  286. "error:",
  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: %v", err)
  311. }
  312. pr.Status = PullRequestStatusChecking
  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. for i := range patchConflicts {
  318. if strings.Contains(stderr, patchConflicts[i]) {
  319. log.Trace("PullRequest[%d].testPatch (apply): has conflit", pr.ID)
  320. fmt.Println(stderr)
  321. pr.Status = PullRequestStatusConflict
  322. return nil
  323. }
  324. }
  325. return fmt.Errorf("git apply --check: %v - %s", err, stderr)
  326. }
  327. return nil
  328. }
  329. // NewPullRequest creates new pull request with labels for repository.
  330. func NewPullRequest(repo *Repository, pull *Issue, labelIDs []int64, uuids []string, pr *PullRequest, patch []byte) (err error) {
  331. sess := x.NewSession()
  332. defer sessionRelease(sess)
  333. if err = sess.Begin(); err != nil {
  334. return err
  335. }
  336. if err = newIssue(sess, NewIssueOptions{
  337. Repo: repo,
  338. Issue: pull,
  339. LableIDs: labelIDs,
  340. Attachments: uuids,
  341. IsPull: true,
  342. }); err != nil {
  343. return fmt.Errorf("newIssue: %v", err)
  344. }
  345. pr.Index = pull.Index
  346. if err = repo.SavePatch(pr.Index, patch); err != nil {
  347. return fmt.Errorf("SavePatch: %v", err)
  348. }
  349. pr.BaseRepo = repo
  350. if err = pr.testPatch(); err != nil {
  351. return fmt.Errorf("testPatch: %v", err)
  352. }
  353. // No conflict appears after test means mergeable.
  354. if pr.Status == PullRequestStatusChecking {
  355. pr.Status = PullRequestStatusMergeable
  356. }
  357. pr.IssueID = pull.ID
  358. if _, err = sess.Insert(pr); err != nil {
  359. return fmt.Errorf("insert pull repo: %v", err)
  360. }
  361. if err = sess.Commit(); err != nil {
  362. return fmt.Errorf("Commit: %v", err)
  363. }
  364. if err = NotifyWatchers(&Action{
  365. ActUserID: pull.Poster.ID,
  366. ActUserName: pull.Poster.Name,
  367. OpType: ActionCreatePullRequest,
  368. Content: fmt.Sprintf("%d|%s", pull.Index, pull.Title),
  369. RepoID: repo.ID,
  370. RepoUserName: repo.Owner.Name,
  371. RepoName: repo.Name,
  372. IsPrivate: repo.IsPrivate,
  373. }); err != nil {
  374. log.Error(4, "NotifyWatchers: %v", err)
  375. } else if err = pull.MailParticipants(); err != nil {
  376. log.Error(4, "MailParticipants: %v", err)
  377. }
  378. pr.Issue = pull
  379. pull.PullRequest = pr
  380. if err = PrepareWebhooks(repo, HookEventPullRequest, &api.PullRequestPayload{
  381. Action: api.HookIssueOpened,
  382. Index: pull.Index,
  383. PullRequest: pr.APIFormat(),
  384. Repository: repo.APIFormat(nil),
  385. Sender: pull.Poster.APIFormat(),
  386. }); err != nil {
  387. log.Error(4, "PrepareWebhooks: %v", err)
  388. }
  389. go HookQueue.Add(repo.ID)
  390. return nil
  391. }
  392. // GetUnmergedPullRequest returnss a pull request that is open and has not been merged
  393. // by given head/base and repo/branch.
  394. func GetUnmergedPullRequest(headRepoID, baseRepoID int64, headBranch, baseBranch string) (*PullRequest, error) {
  395. pr := new(PullRequest)
  396. has, err := x.
  397. Where("head_repo_id=? AND head_branch=? AND base_repo_id=? AND base_branch=? AND has_merged=? AND issue.is_closed=?",
  398. headRepoID, headBranch, baseRepoID, baseBranch, false, false).
  399. Join("INNER", "issue", "issue.id=pull_request.issue_id").
  400. Get(pr)
  401. if err != nil {
  402. return nil, err
  403. } else if !has {
  404. return nil, ErrPullRequestNotExist{0, 0, headRepoID, baseRepoID, headBranch, baseBranch}
  405. }
  406. return pr, nil
  407. }
  408. // GetUnmergedPullRequestsByHeadInfo returnss all pull requests that are open and has not been merged
  409. // by given head information (repo and branch).
  410. func GetUnmergedPullRequestsByHeadInfo(repoID int64, branch string) ([]*PullRequest, error) {
  411. prs := make([]*PullRequest, 0, 2)
  412. return prs, x.
  413. Where("head_repo_id = ? AND head_branch = ? AND has_merged = ? AND issue.is_closed = ?",
  414. repoID, branch, false, false).
  415. Join("INNER", "issue", "issue.id = pull_request.issue_id").
  416. Find(&prs)
  417. }
  418. // GetUnmergedPullRequestsByBaseInfo returnss all pull requests that are open and has not been merged
  419. // by given base information (repo and branch).
  420. func GetUnmergedPullRequestsByBaseInfo(repoID int64, branch string) ([]*PullRequest, error) {
  421. prs := make([]*PullRequest, 0, 2)
  422. return prs, x.
  423. Where("base_repo_id=? AND base_branch=? AND has_merged=? AND issue.is_closed=?",
  424. repoID, branch, false, false).
  425. Join("INNER", "issue", "issue.id=pull_request.issue_id").
  426. 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 = PullRequestStatusChecking
  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.
  552. Where("id > 0").
  553. In("id", issueIDs).
  554. Find(&issues); err != nil {
  555. return fmt.Errorf("find issues: %v", err)
  556. }
  557. set := make(map[int64]*Issue)
  558. for i := range issues {
  559. set[issues[i].ID] = issues[i]
  560. }
  561. for i := range prs {
  562. prs[i].Issue = set[prs[i].IssueID]
  563. }
  564. return nil
  565. }
  566. func (prs PullRequestList) LoadAttributes() error {
  567. return prs.loadAttributes(x)
  568. }
  569. func addHeadRepoTasks(prs []*PullRequest) {
  570. for _, pr := range prs {
  571. log.Trace("addHeadRepoTasks[%d]: composing new test task", pr.ID)
  572. if err := pr.UpdatePatch(); err != nil {
  573. log.Error(4, "UpdatePatch: %v", err)
  574. continue
  575. } else if err := pr.PushToBaseRepo(); err != nil {
  576. log.Error(4, "PushToBaseRepo: %v", err)
  577. continue
  578. }
  579. pr.AddToTaskQueue()
  580. }
  581. }
  582. // AddTestPullRequestTask adds new test tasks by given head/base repository and head/base branch,
  583. // and generate new patch for testing as needed.
  584. func AddTestPullRequestTask(doer *User, repoID int64, branch string, isSync bool) {
  585. log.Trace("AddTestPullRequestTask [head_repo_id: %d, head_branch: %s]: finding pull requests", repoID, branch)
  586. prs, err := GetUnmergedPullRequestsByHeadInfo(repoID, branch)
  587. if err != nil {
  588. log.Error(4, "Find pull requests [head_repo_id: %d, head_branch: %s]: %v", repoID, branch, err)
  589. return
  590. }
  591. if isSync {
  592. if err = PullRequestList(prs).LoadAttributes(); err != nil {
  593. log.Error(4, "PullRequestList.LoadAttributes: %v", err)
  594. }
  595. if err == nil {
  596. for _, pr := range prs {
  597. pr.Issue.PullRequest = pr
  598. if err = pr.Issue.LoadAttributes(); err != nil {
  599. log.Error(4, "LoadAttributes: %v", err)
  600. continue
  601. }
  602. if err = PrepareWebhooks(pr.Issue.Repo, HookEventPullRequest, &api.PullRequestPayload{
  603. Action: api.HookIssueSynchronized,
  604. Index: pr.Issue.Index,
  605. PullRequest: pr.Issue.PullRequest.APIFormat(),
  606. Repository: pr.Issue.Repo.APIFormat(nil),
  607. Sender: doer.APIFormat(),
  608. }); err != nil {
  609. log.Error(4, "PrepareWebhooks [pull_id: %v]: %v", pr.ID, err)
  610. continue
  611. }
  612. go HookQueue.Add(pr.Issue.Repo.ID)
  613. }
  614. }
  615. }
  616. addHeadRepoTasks(prs)
  617. log.Trace("AddTestPullRequestTask [base_repo_id: %d, base_branch: %s]: finding pull requests", repoID, branch)
  618. prs, err = GetUnmergedPullRequestsByBaseInfo(repoID, branch)
  619. if err != nil {
  620. log.Error(4, "Find pull requests [base_repo_id: %d, base_branch: %s]: %v", repoID, branch, err)
  621. return
  622. }
  623. for _, pr := range prs {
  624. pr.AddToTaskQueue()
  625. }
  626. }
  627. func ChangeUsernameInPullRequests(oldUserName, newUserName string) error {
  628. pr := PullRequest{
  629. HeadUserName: strings.ToLower(newUserName),
  630. }
  631. _, err := x.
  632. Cols("head_user_name").
  633. Where("head_user_name = ?", strings.ToLower(oldUserName)).
  634. Update(pr)
  635. return err
  636. }
  637. // checkAndUpdateStatus checks if pull request is possible to levaing checking status,
  638. // and set to be either conflict or mergeable.
  639. func (pr *PullRequest) checkAndUpdateStatus() {
  640. // Status is not changed to conflict means mergeable.
  641. if pr.Status == PullRequestStatusChecking {
  642. pr.Status = PullRequestStatusMergeable
  643. }
  644. // Make sure there is no waiting test to process before levaing the checking status.
  645. if !PullRequestQueue.Exist(pr.ID) {
  646. if err := pr.UpdateCols("status"); err != nil {
  647. log.Error(4, "Update[%d]: %v", pr.ID, err)
  648. }
  649. }
  650. }
  651. // TestPullRequests checks and tests untested patches of pull requests.
  652. // TODO: test more pull requests at same time.
  653. func TestPullRequests() {
  654. prs := make([]*PullRequest, 0, 10)
  655. x.Iterate(PullRequest{
  656. Status: PullRequestStatusChecking,
  657. },
  658. func(idx int, bean interface{}) error {
  659. pr := bean.(*PullRequest)
  660. if err := pr.GetBaseRepo(); err != nil {
  661. log.Error(3, "GetBaseRepo: %v", err)
  662. return nil
  663. }
  664. if err := pr.testPatch(); err != nil {
  665. log.Error(3, "testPatch: %v", err)
  666. return nil
  667. }
  668. prs = append(prs, pr)
  669. return nil
  670. })
  671. // Update pull request status.
  672. for _, pr := range prs {
  673. pr.checkAndUpdateStatus()
  674. }
  675. // Start listening on new test requests.
  676. for prID := range PullRequestQueue.Queue() {
  677. log.Trace("TestPullRequests[%v]: processing test task", prID)
  678. PullRequestQueue.Remove(prID)
  679. pr, err := GetPullRequestByID(com.StrTo(prID).MustInt64())
  680. if err != nil {
  681. log.Error(4, "GetPullRequestByID[%d]: %v", prID, err)
  682. continue
  683. } else if err = pr.testPatch(); err != nil {
  684. log.Error(4, "testPatch[%d]: %v", pr.ID, err)
  685. continue
  686. }
  687. pr.checkAndUpdateStatus()
  688. }
  689. }
  690. func InitTestPullRequests() {
  691. go TestPullRequests()
  692. }