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

pull.go 28 kB

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