pull.go 26 KB

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