You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

pull.go 23KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797
  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. OpType: ACTION_CREATE_PULL_REQUEST,
  366. Content: fmt.Sprintf("%d|%s", pull.Index, pull.Title),
  367. RepoID: repo.ID,
  368. RepoUserName: repo.Owner.Name,
  369. RepoName: repo.Name,
  370. IsPrivate: repo.IsPrivate,
  371. }); err != nil {
  372. log.Error(4, "NotifyWatchers: %v", err)
  373. } else if err = pull.MailParticipants(); err != nil {
  374. log.Error(4, "MailParticipants: %v", err)
  375. }
  376. pr.Issue = pull
  377. pull.PullRequest = pr
  378. if err = PrepareWebhooks(repo, HOOK_EVENT_PULL_REQUEST, &api.PullRequestPayload{
  379. Action: api.HOOK_ISSUE_OPENED,
  380. Index: pull.Index,
  381. PullRequest: pr.APIFormat(),
  382. Repository: repo.APIFormat(nil),
  383. Sender: pull.Poster.APIFormat(),
  384. }); err != nil {
  385. log.Error(4, "PrepareWebhooks: %v", err)
  386. }
  387. go HookQueue.Add(repo.ID)
  388. return nil
  389. }
  390. // GetUnmergedPullRequest returnss a pull request that is open and has not been merged
  391. // by given head/base and repo/branch.
  392. func GetUnmergedPullRequest(headRepoID, baseRepoID int64, headBranch, baseBranch string) (*PullRequest, error) {
  393. pr := new(PullRequest)
  394. has, err := x.Where("head_repo_id=? AND head_branch=? AND base_repo_id=? AND base_branch=? AND has_merged=? AND issue.is_closed=?",
  395. headRepoID, headBranch, baseRepoID, baseBranch, false, false).
  396. Join("INNER", "issue", "issue.id=pull_request.issue_id").Get(pr)
  397. if err != nil {
  398. return nil, err
  399. } else if !has {
  400. return nil, ErrPullRequestNotExist{0, 0, headRepoID, baseRepoID, headBranch, baseBranch}
  401. }
  402. return pr, nil
  403. }
  404. // GetUnmergedPullRequestsByHeadInfo returnss all pull requests that are open and has not been merged
  405. // by given head information (repo and branch).
  406. func GetUnmergedPullRequestsByHeadInfo(repoID int64, branch string) ([]*PullRequest, error) {
  407. prs := make([]*PullRequest, 0, 2)
  408. return prs, x.Where("head_repo_id = ? AND head_branch = ? AND has_merged = ? AND issue.is_closed = ?",
  409. repoID, branch, false, false).
  410. Join("INNER", "issue", "issue.id = pull_request.issue_id").Find(&prs)
  411. }
  412. // GetUnmergedPullRequestsByBaseInfo returnss all pull requests that are open and has not been merged
  413. // by given base information (repo and branch).
  414. func GetUnmergedPullRequestsByBaseInfo(repoID int64, branch string) ([]*PullRequest, error) {
  415. prs := make([]*PullRequest, 0, 2)
  416. return prs, x.Where("base_repo_id=? AND base_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. func getPullRequestByID(e Engine, id int64) (*PullRequest, error) {
  421. pr := new(PullRequest)
  422. has, err := e.Id(id).Get(pr)
  423. if err != nil {
  424. return nil, err
  425. } else if !has {
  426. return nil, ErrPullRequestNotExist{id, 0, 0, 0, "", ""}
  427. }
  428. return pr, pr.loadAttributes(e)
  429. }
  430. // GetPullRequestByID returns a pull request by given ID.
  431. func GetPullRequestByID(id int64) (*PullRequest, error) {
  432. return getPullRequestByID(x, id)
  433. }
  434. func getPullRequestByIssueID(e Engine, issueID int64) (*PullRequest, error) {
  435. pr := &PullRequest{
  436. IssueID: issueID,
  437. }
  438. has, err := e.Get(pr)
  439. if err != nil {
  440. return nil, err
  441. } else if !has {
  442. return nil, ErrPullRequestNotExist{0, issueID, 0, 0, "", ""}
  443. }
  444. return pr, pr.loadAttributes(e)
  445. }
  446. // GetPullRequestByIssueID returns pull request by given issue ID.
  447. func GetPullRequestByIssueID(issueID int64) (*PullRequest, error) {
  448. return getPullRequestByIssueID(x, issueID)
  449. }
  450. // Update updates all fields of pull request.
  451. func (pr *PullRequest) Update() error {
  452. _, err := x.Id(pr.ID).AllCols().Update(pr)
  453. return err
  454. }
  455. // Update updates specific fields of pull request.
  456. func (pr *PullRequest) UpdateCols(cols ...string) error {
  457. _, err := x.Id(pr.ID).Cols(cols...).Update(pr)
  458. return err
  459. }
  460. var PullRequestQueue = NewUniqueQueue(setting.Repository.PullRequestQueueLength)
  461. // UpdatePatch generates and saves a new patch.
  462. func (pr *PullRequest) UpdatePatch() (err error) {
  463. if err = pr.GetHeadRepo(); err != nil {
  464. return fmt.Errorf("GetHeadRepo: %v", err)
  465. } else if pr.HeadRepo == nil {
  466. log.Trace("PullRequest[%d].UpdatePatch: ignored cruppted data", pr.ID)
  467. return nil
  468. }
  469. if err = pr.GetBaseRepo(); err != nil {
  470. return fmt.Errorf("GetBaseRepo: %v", err)
  471. }
  472. headGitRepo, err := git.OpenRepository(pr.HeadRepo.RepoPath())
  473. if err != nil {
  474. return fmt.Errorf("OpenRepository: %v", err)
  475. }
  476. // Add a temporary remote.
  477. tmpRemote := com.ToStr(time.Now().UnixNano())
  478. if err = headGitRepo.AddRemote(tmpRemote, RepoPath(pr.BaseRepo.MustOwner().Name, pr.BaseRepo.Name), true); err != nil {
  479. return fmt.Errorf("AddRemote: %v", err)
  480. }
  481. defer func() {
  482. headGitRepo.RemoveRemote(tmpRemote)
  483. }()
  484. remoteBranch := "remotes/" + tmpRemote + "/" + pr.BaseBranch
  485. pr.MergeBase, err = headGitRepo.GetMergeBase(remoteBranch, pr.HeadBranch)
  486. if err != nil {
  487. return fmt.Errorf("GetMergeBase: %v", err)
  488. } else if err = pr.Update(); err != nil {
  489. return fmt.Errorf("Update: %v", err)
  490. }
  491. patch, err := headGitRepo.GetPatch(pr.MergeBase, pr.HeadBranch)
  492. if err != nil {
  493. return fmt.Errorf("GetPatch: %v", err)
  494. }
  495. if err = pr.BaseRepo.SavePatch(pr.Index, patch); err != nil {
  496. return fmt.Errorf("BaseRepo.SavePatch: %v", err)
  497. }
  498. return nil
  499. }
  500. // PushToBaseRepo pushes commits from branches of head repository to
  501. // corresponding branches of base repository.
  502. // FIXME: Only push branches that are actually updates?
  503. func (pr *PullRequest) PushToBaseRepo() (err error) {
  504. log.Trace("PushToBaseRepo[%d]: pushing commits to base repo 'refs/pull/%d/head'", pr.BaseRepoID, pr.Index)
  505. headRepoPath := pr.HeadRepo.RepoPath()
  506. headGitRepo, err := git.OpenRepository(headRepoPath)
  507. if err != nil {
  508. return fmt.Errorf("OpenRepository: %v", err)
  509. }
  510. tmpRemoteName := fmt.Sprintf("tmp-pull-%d", pr.ID)
  511. if err = headGitRepo.AddRemote(tmpRemoteName, pr.BaseRepo.RepoPath(), false); err != nil {
  512. return fmt.Errorf("headGitRepo.AddRemote: %v", err)
  513. }
  514. // Make sure to remove the remote even if the push fails
  515. defer headGitRepo.RemoveRemote(tmpRemoteName)
  516. headFile := fmt.Sprintf("refs/pull/%d/head", pr.Index)
  517. // Remove head in case there is a conflict.
  518. os.Remove(path.Join(pr.BaseRepo.RepoPath(), headFile))
  519. if err = git.Push(headRepoPath, tmpRemoteName, fmt.Sprintf("%s:%s", pr.HeadBranch, headFile)); err != nil {
  520. return fmt.Errorf("Push: %v", err)
  521. }
  522. return nil
  523. }
  524. // AddToTaskQueue adds itself to pull request test task queue.
  525. func (pr *PullRequest) AddToTaskQueue() {
  526. go PullRequestQueue.AddFunc(pr.ID, func() {
  527. pr.Status = PULL_REQUEST_STATUS_CHECKING
  528. if err := pr.UpdateCols("status"); err != nil {
  529. log.Error(5, "AddToTaskQueue.UpdateCols[%d].(add to queue): %v", pr.ID, err)
  530. }
  531. })
  532. }
  533. type PullRequestList []*PullRequest
  534. func (prs PullRequestList) loadAttributes(e Engine) error {
  535. if len(prs) == 0 {
  536. return nil
  537. }
  538. // Load issues.
  539. issueIDs := make([]int64, 0, len(prs))
  540. for i := range prs {
  541. issueIDs = append(issueIDs, prs[i].IssueID)
  542. }
  543. issues := make([]*Issue, 0, len(issueIDs))
  544. if err := e.Where("id > 0").In("id", issueIDs).Find(&issues); err != nil {
  545. return fmt.Errorf("find issues: %v", err)
  546. }
  547. set := make(map[int64]*Issue)
  548. for i := range issues {
  549. set[issues[i].ID] = issues[i]
  550. }
  551. for i := range prs {
  552. prs[i].Issue = set[prs[i].IssueID]
  553. }
  554. return nil
  555. }
  556. func (prs PullRequestList) LoadAttributes() error {
  557. return prs.loadAttributes(x)
  558. }
  559. func addHeadRepoTasks(prs []*PullRequest) {
  560. for _, pr := range prs {
  561. log.Trace("addHeadRepoTasks[%d]: composing new test task", pr.ID)
  562. if err := pr.UpdatePatch(); err != nil {
  563. log.Error(4, "UpdatePatch: %v", err)
  564. continue
  565. } else if err := pr.PushToBaseRepo(); err != nil {
  566. log.Error(4, "PushToBaseRepo: %v", err)
  567. continue
  568. }
  569. pr.AddToTaskQueue()
  570. }
  571. }
  572. // AddTestPullRequestTask adds new test tasks by given head/base repository and head/base branch,
  573. // and generate new patch for testing as needed.
  574. func AddTestPullRequestTask(doer *User, repoID int64, branch string, isSync bool) {
  575. log.Trace("AddTestPullRequestTask [head_repo_id: %d, head_branch: %s]: finding pull requests", repoID, branch)
  576. prs, err := GetUnmergedPullRequestsByHeadInfo(repoID, branch)
  577. if err != nil {
  578. log.Error(4, "Find pull requests [head_repo_id: %d, head_branch: %s]: %v", repoID, branch, err)
  579. return
  580. }
  581. if isSync {
  582. if err = PullRequestList(prs).LoadAttributes(); err != nil {
  583. log.Error(4, "PullRequestList.LoadAttributes: %v", err)
  584. }
  585. if err == nil {
  586. for _, pr := range prs {
  587. pr.Issue.PullRequest = pr
  588. if err = pr.Issue.LoadAttributes(); err != nil {
  589. log.Error(4, "LoadAttributes: %v", err)
  590. continue
  591. }
  592. if err = PrepareWebhooks(pr.Issue.Repo, HOOK_EVENT_PULL_REQUEST, &api.PullRequestPayload{
  593. Action: api.HOOK_ISSUE_SYNCHRONIZED,
  594. Index: pr.Issue.Index,
  595. PullRequest: pr.Issue.PullRequest.APIFormat(),
  596. Repository: pr.Issue.Repo.APIFormat(nil),
  597. Sender: doer.APIFormat(),
  598. }); err != nil {
  599. log.Error(4, "PrepareWebhooks [pull_id: %v]: %v", pr.ID, err)
  600. continue
  601. }
  602. go HookQueue.Add(pr.Issue.Repo.ID)
  603. }
  604. }
  605. }
  606. addHeadRepoTasks(prs)
  607. log.Trace("AddTestPullRequestTask [base_repo_id: %d, base_branch: %s]: finding pull requests", repoID, branch)
  608. prs, err = GetUnmergedPullRequestsByBaseInfo(repoID, branch)
  609. if err != nil {
  610. log.Error(4, "Find pull requests [base_repo_id: %d, base_branch: %s]: %v", repoID, branch, err)
  611. return
  612. }
  613. for _, pr := range prs {
  614. pr.AddToTaskQueue()
  615. }
  616. }
  617. func ChangeUsernameInPullRequests(oldUserName, newUserName string) error {
  618. pr := PullRequest{
  619. HeadUserName: strings.ToLower(newUserName),
  620. }
  621. _, err := x.Cols("head_user_name").Where("head_user_name = ?", strings.ToLower(oldUserName)).Update(pr)
  622. return err
  623. }
  624. // checkAndUpdateStatus checks if pull request is possible to levaing checking status,
  625. // and set to be either conflict or mergeable.
  626. func (pr *PullRequest) checkAndUpdateStatus() {
  627. // Status is not changed to conflict means mergeable.
  628. if pr.Status == PULL_REQUEST_STATUS_CHECKING {
  629. pr.Status = PULL_REQUEST_STATUS_MERGEABLE
  630. }
  631. // Make sure there is no waiting test to process before levaing the checking status.
  632. if !PullRequestQueue.Exist(pr.ID) {
  633. if err := pr.UpdateCols("status"); err != nil {
  634. log.Error(4, "Update[%d]: %v", pr.ID, err)
  635. }
  636. }
  637. }
  638. // TestPullRequests checks and tests untested patches of pull requests.
  639. // TODO: test more pull requests at same time.
  640. func TestPullRequests() {
  641. prs := make([]*PullRequest, 0, 10)
  642. x.Iterate(PullRequest{
  643. Status: PULL_REQUEST_STATUS_CHECKING,
  644. },
  645. func(idx int, bean interface{}) error {
  646. pr := bean.(*PullRequest)
  647. if err := pr.GetBaseRepo(); err != nil {
  648. log.Error(3, "GetBaseRepo: %v", err)
  649. return nil
  650. }
  651. if err := pr.testPatch(); err != nil {
  652. log.Error(3, "testPatch: %v", err)
  653. return nil
  654. }
  655. prs = append(prs, pr)
  656. return nil
  657. })
  658. // Update pull request status.
  659. for _, pr := range prs {
  660. pr.checkAndUpdateStatus()
  661. }
  662. // Start listening on new test requests.
  663. for prID := range PullRequestQueue.Queue() {
  664. log.Trace("TestPullRequests[%v]: processing test task", prID)
  665. PullRequestQueue.Remove(prID)
  666. pr, err := GetPullRequestByID(com.StrTo(prID).MustInt64())
  667. if err != nil {
  668. log.Error(4, "GetPullRequestByID[%d]: %v", prID, err)
  669. continue
  670. } else if err = pr.testPatch(); err != nil {
  671. log.Error(4, "testPatch[%d]: %v", pr.ID, err)
  672. continue
  673. }
  674. pr.checkAndUpdateStatus()
  675. }
  676. }
  677. func InitTestPullRequests() {
  678. go TestPullRequests()
  679. }