pull.go 27 KB

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