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