pull.go 26 KB

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