pull.go 26 KB

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