pull.go 27 KB

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