pull.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868
  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/filepath"
  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/conf"
  17. "gogs.io/gogs/internal/db/errors"
  18. "gogs.io/gogs/internal/osutil"
  19. "gogs.io/gogs/internal/process"
  20. "gogs.io/gogs/internal/sync"
  21. )
  22. var PullRequestQueue = sync.NewUniqueQueue(1000)
  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.Open(headRepoPath)
  179. if err != nil {
  180. return fmt.Errorf("open repository: %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 := filepath.Join(conf.Server.AppDataPath, "tmp", "repos", com.ToStr(time.Now().Nanosecond())+".git")
  185. os.MkdirAll(filepath.Dir(tmpBasePath), os.ModePerm)
  186. defer os.RemoveAll(filepath.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.BranchCommitID(pr.HeadBranch)
  265. if err != nil {
  266. return fmt.Errorf("get head branch %q commit ID: %v", pr.HeadBranch, 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. commits, err := headGitRepo.RevList([]string{pr.MergeBase + "..." + pr.MergedCommitID})
  296. if err != nil {
  297. log.Error("Failed to list commits [merge_base: %s, merged_commit_id: %s]: %v", pr.MergeBase, pr.MergedCommitID, err)
  298. return nil
  299. }
  300. // NOTE: It is possible that head branch is not fully sync with base branch
  301. // for merge commits, so we need to get latest head commit and append merge
  302. // commit manully to avoid strange diff commits produced.
  303. mergeCommit, err := baseGitRepo.BranchCommit(pr.BaseBranch)
  304. if err != nil {
  305. log.Error("Failed to get base branch %q commit: %v", pr.BaseBranch, err)
  306. return nil
  307. }
  308. if mergeStyle == MERGE_STYLE_REGULAR {
  309. commits = append([]*git.Commit{mergeCommit}, commits...)
  310. }
  311. pcs, err := CommitsToPushCommits(commits).ToApiPayloadCommits(pr.BaseRepo.RepoPath(), pr.BaseRepo.HTMLURL())
  312. if err != nil {
  313. log.Error("Failed to convert to API payload commits: %v", err)
  314. return nil
  315. }
  316. p := &api.PushPayload{
  317. Ref: git.RefsHeads + pr.BaseBranch,
  318. Before: pr.MergeBase,
  319. After: mergeCommit.ID.String(),
  320. CompareURL: conf.Server.ExternalURL + pr.BaseRepo.ComposeCompareURL(pr.MergeBase, pr.MergedCommitID),
  321. Commits: pcs,
  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("Failed to prepare webhooks: %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.Open(pr.HeadRepo.RepoPath())
  512. if err != nil {
  513. return fmt.Errorf("open repository: %v", err)
  514. }
  515. // Add a temporary remote.
  516. tmpRemote := com.ToStr(time.Now().UnixNano())
  517. baseRepoPath := RepoPath(pr.BaseRepo.MustOwner().Name, pr.BaseRepo.Name)
  518. err = headGitRepo.AddRemote(tmpRemote, baseRepoPath, git.AddRemoteOptions{Fetch: true})
  519. if err != nil {
  520. return fmt.Errorf("add remote %q [repo_id: %d]: %v", tmpRemote, pr.HeadRepoID, err)
  521. }
  522. defer func() {
  523. if err := headGitRepo.RemoveRemote(tmpRemote); err != nil {
  524. log.Error("Failed to remove remote %q [repo_id: %d]: %v", tmpRemote, pr.HeadRepoID, err)
  525. }
  526. }()
  527. remoteBranch := "remotes/" + tmpRemote + "/" + pr.BaseBranch
  528. pr.MergeBase, err = headGitRepo.MergeBase(remoteBranch, pr.HeadBranch)
  529. if err != nil {
  530. return fmt.Errorf("get merge base: %v", err)
  531. } else if err = pr.Update(); err != nil {
  532. return fmt.Errorf("update: %v", err)
  533. }
  534. patch, err := headGitRepo.DiffBinary(pr.MergeBase, pr.HeadBranch)
  535. if err != nil {
  536. return fmt.Errorf("get binary patch: %v", err)
  537. }
  538. if err = pr.BaseRepo.SavePatch(pr.Index, patch); err != nil {
  539. return fmt.Errorf("save patch: %v", err)
  540. }
  541. log.Trace("PullRequest[%d].UpdatePatch: patch saved", pr.ID)
  542. return nil
  543. }
  544. // PushToBaseRepo pushes commits from branches of head repository to
  545. // corresponding branches of base repository.
  546. // FIXME: Only push branches that are actually updates?
  547. func (pr *PullRequest) PushToBaseRepo() (err error) {
  548. log.Trace("PushToBaseRepo[%d]: pushing commits to base repo 'refs/pull/%d/head'", pr.BaseRepoID, pr.Index)
  549. headRepoPath := pr.HeadRepo.RepoPath()
  550. headGitRepo, err := git.Open(headRepoPath)
  551. if err != nil {
  552. return fmt.Errorf("open repository: %v", err)
  553. }
  554. tmpRemote := fmt.Sprintf("tmp-pull-%d", pr.ID)
  555. if err = headGitRepo.AddRemote(tmpRemote, pr.BaseRepo.RepoPath()); err != nil {
  556. return fmt.Errorf("add remote %q [repo_id: %d]: %v", tmpRemote, pr.HeadRepoID, err)
  557. }
  558. // Make sure to remove the remote even if the push fails
  559. defer func() {
  560. if err := headGitRepo.RemoveRemote(tmpRemote); err != nil {
  561. log.Error("Failed to remove remote %q [repo_id: %d]: %v", tmpRemote, pr.HeadRepoID, err)
  562. }
  563. }()
  564. headRefspec := fmt.Sprintf("refs/pull/%d/head", pr.Index)
  565. headFile := filepath.Join(pr.BaseRepo.RepoPath(), headRefspec)
  566. if osutil.IsExist(headFile) {
  567. err = os.Remove(headFile)
  568. if err != nil {
  569. return fmt.Errorf("remove head file [repo_id: %d]: %v", pr.BaseRepoID, err)
  570. }
  571. }
  572. err = headGitRepo.Push(tmpRemote, fmt.Sprintf("%s:%s", pr.HeadBranch, headRefspec))
  573. if err != nil {
  574. return fmt.Errorf("push: %v", err)
  575. }
  576. return nil
  577. }
  578. // AddToTaskQueue adds itself to pull request test task queue.
  579. func (pr *PullRequest) AddToTaskQueue() {
  580. go PullRequestQueue.AddFunc(pr.ID, func() {
  581. pr.Status = PULL_REQUEST_STATUS_CHECKING
  582. if err := pr.UpdateCols("status"); err != nil {
  583. log.Error("AddToTaskQueue.UpdateCols[%d].(add to queue): %v", pr.ID, err)
  584. }
  585. })
  586. }
  587. type PullRequestList []*PullRequest
  588. func (prs PullRequestList) loadAttributes(e Engine) (err error) {
  589. if len(prs) == 0 {
  590. return nil
  591. }
  592. // Load issues
  593. set := make(map[int64]*Issue)
  594. for i := range prs {
  595. set[prs[i].IssueID] = nil
  596. }
  597. issueIDs := make([]int64, 0, len(prs))
  598. for issueID := range set {
  599. issueIDs = append(issueIDs, issueID)
  600. }
  601. issues := make([]*Issue, 0, len(issueIDs))
  602. if err = e.Where("id > 0").In("id", issueIDs).Find(&issues); err != nil {
  603. return fmt.Errorf("find issues: %v", err)
  604. }
  605. for i := range issues {
  606. set[issues[i].ID] = issues[i]
  607. }
  608. for i := range prs {
  609. prs[i].Issue = set[prs[i].IssueID]
  610. }
  611. // Load attributes
  612. for i := range prs {
  613. if err = prs[i].loadAttributes(e); err != nil {
  614. return fmt.Errorf("loadAttributes [%d]: %v", prs[i].ID, err)
  615. }
  616. }
  617. return nil
  618. }
  619. func (prs PullRequestList) LoadAttributes() error {
  620. return prs.loadAttributes(x)
  621. }
  622. func addHeadRepoTasks(prs []*PullRequest) {
  623. for _, pr := range prs {
  624. log.Trace("addHeadRepoTasks[%d]: composing new test task", pr.ID)
  625. if err := pr.UpdatePatch(); err != nil {
  626. log.Error("UpdatePatch: %v", err)
  627. continue
  628. } else if err := pr.PushToBaseRepo(); err != nil {
  629. log.Error("PushToBaseRepo: %v", err)
  630. continue
  631. }
  632. pr.AddToTaskQueue()
  633. }
  634. }
  635. // AddTestPullRequestTask adds new test tasks by given head/base repository and head/base branch,
  636. // and generate new patch for testing as needed.
  637. func AddTestPullRequestTask(doer *User, repoID int64, branch string, isSync bool) {
  638. log.Trace("AddTestPullRequestTask [head_repo_id: %d, head_branch: %s]: finding pull requests", repoID, branch)
  639. prs, err := GetUnmergedPullRequestsByHeadInfo(repoID, branch)
  640. if err != nil {
  641. log.Error("Find pull requests [head_repo_id: %d, head_branch: %s]: %v", repoID, branch, err)
  642. return
  643. }
  644. if isSync {
  645. if err = PullRequestList(prs).LoadAttributes(); err != nil {
  646. log.Error("PullRequestList.LoadAttributes: %v", err)
  647. }
  648. if err == nil {
  649. for _, pr := range prs {
  650. pr.Issue.PullRequest = pr
  651. if err = pr.Issue.LoadAttributes(); err != nil {
  652. log.Error("LoadAttributes: %v", err)
  653. continue
  654. }
  655. if err = PrepareWebhooks(pr.Issue.Repo, HOOK_EVENT_PULL_REQUEST, &api.PullRequestPayload{
  656. Action: api.HOOK_ISSUE_SYNCHRONIZED,
  657. Index: pr.Issue.Index,
  658. PullRequest: pr.Issue.PullRequest.APIFormat(),
  659. Repository: pr.Issue.Repo.APIFormat(nil),
  660. Sender: doer.APIFormat(),
  661. }); err != nil {
  662. log.Error("PrepareWebhooks [pull_id: %v]: %v", pr.ID, err)
  663. continue
  664. }
  665. }
  666. }
  667. }
  668. addHeadRepoTasks(prs)
  669. log.Trace("AddTestPullRequestTask [base_repo_id: %d, base_branch: %s]: finding pull requests", repoID, branch)
  670. prs, err = GetUnmergedPullRequestsByBaseInfo(repoID, branch)
  671. if err != nil {
  672. log.Error("Find pull requests [base_repo_id: %d, base_branch: %s]: %v", repoID, branch, err)
  673. return
  674. }
  675. for _, pr := range prs {
  676. pr.AddToTaskQueue()
  677. }
  678. }
  679. func ChangeUsernameInPullRequests(oldUserName, newUserName string) error {
  680. pr := PullRequest{
  681. HeadUserName: strings.ToLower(newUserName),
  682. }
  683. _, err := x.Cols("head_user_name").Where("head_user_name = ?", strings.ToLower(oldUserName)).Update(pr)
  684. return err
  685. }
  686. // checkAndUpdateStatus checks if pull request is possible to levaing checking status,
  687. // and set to be either conflict or mergeable.
  688. func (pr *PullRequest) checkAndUpdateStatus() {
  689. // Status is not changed to conflict means mergeable.
  690. if pr.Status == PULL_REQUEST_STATUS_CHECKING {
  691. pr.Status = PULL_REQUEST_STATUS_MERGEABLE
  692. }
  693. // Make sure there is no waiting test to process before levaing the checking status.
  694. if !PullRequestQueue.Exist(pr.ID) {
  695. if err := pr.UpdateCols("status"); err != nil {
  696. log.Error("Update[%d]: %v", pr.ID, err)
  697. }
  698. }
  699. }
  700. // TestPullRequests checks and tests untested patches of pull requests.
  701. // TODO: test more pull requests at same time.
  702. func TestPullRequests() {
  703. prs := make([]*PullRequest, 0, 10)
  704. x.Iterate(PullRequest{
  705. Status: PULL_REQUEST_STATUS_CHECKING,
  706. },
  707. func(idx int, bean interface{}) error {
  708. pr := bean.(*PullRequest)
  709. if err := pr.LoadAttributes(); err != nil {
  710. log.Error("LoadAttributes: %v", err)
  711. return nil
  712. }
  713. if err := pr.testPatch(); err != nil {
  714. log.Error("testPatch: %v", err)
  715. return nil
  716. }
  717. prs = append(prs, pr)
  718. return nil
  719. })
  720. // Update pull request status.
  721. for _, pr := range prs {
  722. pr.checkAndUpdateStatus()
  723. }
  724. // Start listening on new test requests.
  725. for prID := range PullRequestQueue.Queue() {
  726. log.Trace("TestPullRequests[%v]: processing test task", prID)
  727. PullRequestQueue.Remove(prID)
  728. pr, err := GetPullRequestByID(com.StrTo(prID).MustInt64())
  729. if err != nil {
  730. log.Error("GetPullRequestByID[%s]: %v", prID, err)
  731. continue
  732. } else if err = pr.testPatch(); err != nil {
  733. log.Error("testPatch[%d]: %v", pr.ID, err)
  734. continue
  735. }
  736. pr.checkAndUpdateStatus()
  737. }
  738. }
  739. func InitTestPullRequests() {
  740. go TestPullRequests()
  741. }