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

pull.go 27KB

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