pull.go 26 KB

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