pull.go 25 KB

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