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.

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