pull.go 24 KB

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. log "gopkg.in/clog.v1"
  14. "github.com/gogits/git-module"
  15. api "github.com/gogits/go-gogs-client"
  16. "github.com/gogits/gogs/modules/process"
  17. "github.com/gogits/gogs/modules/setting"
  18. "github.com/gogits/gogs/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.HeadRepo == nil {
  71. pr.HeadRepo, err = getRepositoryByID(e, pr.HeadRepoID)
  72. if err != nil && !IsErrRepoNotExist(err) {
  73. return fmt.Errorf("getRepositoryByID.(HeadRepo) [%d]: %v", pr.HeadRepoID, err)
  74. }
  75. }
  76. if pr.BaseRepo == nil {
  77. pr.BaseRepo, err = getRepositoryByID(e, pr.BaseRepoID)
  78. if err != nil {
  79. return fmt.Errorf("getRepositoryByID.(BaseRepo) [%d]: %v", pr.BaseRepoID, err)
  80. }
  81. }
  82. if pr.HasMerged && pr.Merger == nil {
  83. pr.Merger, err = getUserByID(e, pr.MergerID)
  84. if IsErrUserNotExist(err) {
  85. pr.MergerID = -1
  86. pr.Merger = NewGhostUser()
  87. } else if err != nil {
  88. return fmt.Errorf("getUserByID [%d]: %v", pr.MergerID, err)
  89. }
  90. }
  91. return nil
  92. }
  93. func (pr *PullRequest) LoadAttributes() error {
  94. return pr.loadAttributes(x)
  95. }
  96. func (pr *PullRequest) LoadIssue() (err error) {
  97. if pr.Issue != nil {
  98. return nil
  99. }
  100. pr.Issue, err = GetIssueByID(pr.IssueID)
  101. return err
  102. }
  103. // This method assumes following fields have been assigned with valid values:
  104. // Required - Issue, BaseRepo
  105. // Optional - HeadRepo, Merger
  106. func (pr *PullRequest) APIFormat() *api.PullRequest {
  107. // In case of head repo has been deleted.
  108. var apiHeadRepo *api.Repository
  109. if pr.HeadRepo == nil {
  110. apiHeadRepo = &api.Repository{
  111. Name: "deleted",
  112. }
  113. } else {
  114. apiHeadRepo = pr.HeadRepo.APIFormat(nil)
  115. }
  116. apiIssue := pr.Issue.APIFormat()
  117. apiPullRequest := &api.PullRequest{
  118. ID: pr.ID,
  119. Index: pr.Index,
  120. Poster: apiIssue.Poster,
  121. Title: apiIssue.Title,
  122. Body: apiIssue.Body,
  123. Labels: apiIssue.Labels,
  124. Milestone: apiIssue.Milestone,
  125. Assignee: apiIssue.Assignee,
  126. State: apiIssue.State,
  127. Comments: apiIssue.Comments,
  128. HeadBranch: pr.HeadBranch,
  129. HeadRepo: apiHeadRepo,
  130. BaseBranch: pr.BaseBranch,
  131. BaseRepo: pr.BaseRepo.APIFormat(nil),
  132. HTMLURL: pr.Issue.HTMLURL(),
  133. HasMerged: pr.HasMerged,
  134. }
  135. if pr.Status != PULL_REQUEST_STATUS_CHECKING {
  136. mergeable := pr.Status != PULL_REQUEST_STATUS_CONFLICT
  137. apiPullRequest.Mergeable = &mergeable
  138. }
  139. if pr.HasMerged {
  140. apiPullRequest.Merged = &pr.Merged
  141. apiPullRequest.MergedCommitID = &pr.MergedCommitID
  142. apiPullRequest.MergedBy = pr.Merger.APIFormat()
  143. }
  144. return apiPullRequest
  145. }
  146. // IsChecking returns true if this pull request is still checking conflict.
  147. func (pr *PullRequest) IsChecking() bool {
  148. return pr.Status == PULL_REQUEST_STATUS_CHECKING
  149. }
  150. // CanAutoMerge returns true if this pull request can be merged automatically.
  151. func (pr *PullRequest) CanAutoMerge() bool {
  152. return pr.Status == PULL_REQUEST_STATUS_MERGEABLE
  153. }
  154. // Merge merges pull request to base repository.
  155. // FIXME: add repoWorkingPull make sure two merges does not happen at same time.
  156. func (pr *PullRequest) Merge(doer *User, baseGitRepo *git.Repository) (err error) {
  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 [%d]: %v", pr.BaseRepoID, 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 pr.HeadRepo == nil {
  465. log.Trace("PullRequest[%d].UpdatePatch: ignored cruppted data", pr.ID)
  466. return nil
  467. }
  468. headGitRepo, err := git.OpenRepository(pr.HeadRepo.RepoPath())
  469. if err != nil {
  470. return fmt.Errorf("OpenRepository: %v", err)
  471. }
  472. // Add a temporary remote.
  473. tmpRemote := com.ToStr(time.Now().UnixNano())
  474. if err = headGitRepo.AddRemote(tmpRemote, RepoPath(pr.BaseRepo.MustOwner().Name, pr.BaseRepo.Name), true); err != nil {
  475. return fmt.Errorf("AddRemote: %v", err)
  476. }
  477. defer func() {
  478. headGitRepo.RemoveRemote(tmpRemote)
  479. }()
  480. remoteBranch := "remotes/" + tmpRemote + "/" + pr.BaseBranch
  481. pr.MergeBase, err = headGitRepo.GetMergeBase(remoteBranch, pr.HeadBranch)
  482. if err != nil {
  483. return fmt.Errorf("GetMergeBase: %v", err)
  484. } else if err = pr.Update(); err != nil {
  485. return fmt.Errorf("Update: %v", err)
  486. }
  487. patch, err := headGitRepo.GetPatch(pr.MergeBase, pr.HeadBranch)
  488. if err != nil {
  489. return fmt.Errorf("GetPatch: %v", err)
  490. }
  491. if err = pr.BaseRepo.SavePatch(pr.Index, patch); err != nil {
  492. return fmt.Errorf("BaseRepo.SavePatch: %v", err)
  493. }
  494. return nil
  495. }
  496. // PushToBaseRepo pushes commits from branches of head repository to
  497. // corresponding branches of base repository.
  498. // FIXME: Only push branches that are actually updates?
  499. func (pr *PullRequest) PushToBaseRepo() (err error) {
  500. log.Trace("PushToBaseRepo[%d]: pushing commits to base repo 'refs/pull/%d/head'", pr.BaseRepoID, pr.Index)
  501. headRepoPath := pr.HeadRepo.RepoPath()
  502. headGitRepo, err := git.OpenRepository(headRepoPath)
  503. if err != nil {
  504. return fmt.Errorf("OpenRepository: %v", err)
  505. }
  506. tmpRemoteName := fmt.Sprintf("tmp-pull-%d", pr.ID)
  507. if err = headGitRepo.AddRemote(tmpRemoteName, pr.BaseRepo.RepoPath(), false); err != nil {
  508. return fmt.Errorf("headGitRepo.AddRemote: %v", err)
  509. }
  510. // Make sure to remove the remote even if the push fails
  511. defer headGitRepo.RemoveRemote(tmpRemoteName)
  512. headFile := fmt.Sprintf("refs/pull/%d/head", pr.Index)
  513. // Remove head in case there is a conflict.
  514. os.Remove(path.Join(pr.BaseRepo.RepoPath(), headFile))
  515. if err = git.Push(headRepoPath, tmpRemoteName, fmt.Sprintf("%s:%s", pr.HeadBranch, headFile)); err != nil {
  516. return fmt.Errorf("Push: %v", err)
  517. }
  518. return nil
  519. }
  520. // AddToTaskQueue adds itself to pull request test task queue.
  521. func (pr *PullRequest) AddToTaskQueue() {
  522. go PullRequestQueue.AddFunc(pr.ID, func() {
  523. pr.Status = PULL_REQUEST_STATUS_CHECKING
  524. if err := pr.UpdateCols("status"); err != nil {
  525. log.Error(5, "AddToTaskQueue.UpdateCols[%d].(add to queue): %v", pr.ID, err)
  526. }
  527. })
  528. }
  529. type PullRequestList []*PullRequest
  530. func (prs PullRequestList) loadAttributes(e Engine) (err error) {
  531. if len(prs) == 0 {
  532. return nil
  533. }
  534. // Load issues
  535. issueIDs := make([]int64, 0, len(prs))
  536. for i := range prs {
  537. issueIDs = append(issueIDs, prs[i].IssueID)
  538. }
  539. issues := make([]*Issue, 0, len(issueIDs))
  540. if err = e.Where("id > 0").In("id", issueIDs).Find(&issues); err != nil {
  541. return fmt.Errorf("find issues: %v", err)
  542. }
  543. set := make(map[int64]*Issue)
  544. for i := range issues {
  545. set[issues[i].ID] = issues[i]
  546. }
  547. for i := range prs {
  548. prs[i].Issue = set[prs[i].IssueID]
  549. }
  550. // Load attributes
  551. for i := range prs {
  552. if err = prs[i].loadAttributes(e); err != nil {
  553. return fmt.Errorf("loadAttributes [%d]: %v", prs[i].ID, err)
  554. }
  555. }
  556. return nil
  557. }
  558. func (prs PullRequestList) LoadAttributes() error {
  559. return prs.loadAttributes(x)
  560. }
  561. func addHeadRepoTasks(prs []*PullRequest) {
  562. for _, pr := range prs {
  563. log.Trace("addHeadRepoTasks[%d]: composing new test task", pr.ID)
  564. if err := pr.UpdatePatch(); err != nil {
  565. log.Error(4, "UpdatePatch: %v", err)
  566. continue
  567. } else if err := pr.PushToBaseRepo(); err != nil {
  568. log.Error(4, "PushToBaseRepo: %v", err)
  569. continue
  570. }
  571. pr.AddToTaskQueue()
  572. }
  573. }
  574. // AddTestPullRequestTask adds new test tasks by given head/base repository and head/base branch,
  575. // and generate new patch for testing as needed.
  576. func AddTestPullRequestTask(doer *User, repoID int64, branch string, isSync bool) {
  577. log.Trace("AddTestPullRequestTask [head_repo_id: %d, head_branch: %s]: finding pull requests", repoID, branch)
  578. prs, err := GetUnmergedPullRequestsByHeadInfo(repoID, branch)
  579. if err != nil {
  580. log.Error(4, "Find pull requests [head_repo_id: %d, head_branch: %s]: %v", repoID, branch, err)
  581. return
  582. }
  583. if isSync {
  584. if err = PullRequestList(prs).LoadAttributes(); err != nil {
  585. log.Error(4, "PullRequestList.LoadAttributes: %v", err)
  586. }
  587. if err == nil {
  588. for _, pr := range prs {
  589. pr.Issue.PullRequest = pr
  590. if err = pr.Issue.LoadAttributes(); err != nil {
  591. log.Error(4, "LoadAttributes: %v", err)
  592. continue
  593. }
  594. if err = PrepareWebhooks(pr.Issue.Repo, HOOK_EVENT_PULL_REQUEST, &api.PullRequestPayload{
  595. Action: api.HOOK_ISSUE_SYNCHRONIZED,
  596. Index: pr.Issue.Index,
  597. PullRequest: pr.Issue.PullRequest.APIFormat(),
  598. Repository: pr.Issue.Repo.APIFormat(nil),
  599. Sender: doer.APIFormat(),
  600. }); err != nil {
  601. log.Error(4, "PrepareWebhooks [pull_id: %v]: %v", pr.ID, err)
  602. continue
  603. }
  604. go HookQueue.Add(pr.Issue.Repo.ID)
  605. }
  606. }
  607. }
  608. addHeadRepoTasks(prs)
  609. log.Trace("AddTestPullRequestTask [base_repo_id: %d, base_branch: %s]: finding pull requests", repoID, branch)
  610. prs, err = GetUnmergedPullRequestsByBaseInfo(repoID, branch)
  611. if err != nil {
  612. log.Error(4, "Find pull requests [base_repo_id: %d, base_branch: %s]: %v", repoID, branch, err)
  613. return
  614. }
  615. for _, pr := range prs {
  616. pr.AddToTaskQueue()
  617. }
  618. }
  619. func ChangeUsernameInPullRequests(oldUserName, newUserName string) error {
  620. pr := PullRequest{
  621. HeadUserName: strings.ToLower(newUserName),
  622. }
  623. _, err := x.Cols("head_user_name").Where("head_user_name = ?", strings.ToLower(oldUserName)).Update(pr)
  624. return err
  625. }
  626. // checkAndUpdateStatus checks if pull request is possible to levaing checking status,
  627. // and set to be either conflict or mergeable.
  628. func (pr *PullRequest) checkAndUpdateStatus() {
  629. // Status is not changed to conflict means mergeable.
  630. if pr.Status == PULL_REQUEST_STATUS_CHECKING {
  631. pr.Status = PULL_REQUEST_STATUS_MERGEABLE
  632. }
  633. // Make sure there is no waiting test to process before levaing the checking status.
  634. if !PullRequestQueue.Exist(pr.ID) {
  635. if err := pr.UpdateCols("status"); err != nil {
  636. log.Error(4, "Update[%d]: %v", pr.ID, err)
  637. }
  638. }
  639. }
  640. // TestPullRequests checks and tests untested patches of pull requests.
  641. // TODO: test more pull requests at same time.
  642. func TestPullRequests() {
  643. prs := make([]*PullRequest, 0, 10)
  644. x.Iterate(PullRequest{
  645. Status: PULL_REQUEST_STATUS_CHECKING,
  646. },
  647. func(idx int, bean interface{}) error {
  648. pr := bean.(*PullRequest)
  649. if err := pr.LoadAttributes(); err != nil {
  650. log.Error(3, "LoadAttributes: %v", err)
  651. return nil
  652. }
  653. if err := pr.testPatch(); err != nil {
  654. log.Error(3, "testPatch: %v", err)
  655. return nil
  656. }
  657. prs = append(prs, pr)
  658. return nil
  659. })
  660. // Update pull request status.
  661. for _, pr := range prs {
  662. pr.checkAndUpdateStatus()
  663. }
  664. // Start listening on new test requests.
  665. for prID := range PullRequestQueue.Queue() {
  666. log.Trace("TestPullRequests[%v]: processing test task", prID)
  667. PullRequestQueue.Remove(prID)
  668. pr, err := GetPullRequestByID(com.StrTo(prID).MustInt64())
  669. if err != nil {
  670. log.Error(4, "GetPullRequestByID[%s]: %v", prID, err)
  671. continue
  672. } else if err = pr.testPatch(); err != nil {
  673. log.Error(4, "testPatch[%d]: %v", pr.ID, err)
  674. continue
  675. }
  676. pr.checkAndUpdateStatus()
  677. }
  678. }
  679. func InitTestPullRequests() {
  680. go TestPullRequests()
  681. }