pull.go 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896
  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/errutil"
  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 && !IsErrRepoNotExist(err) {
  75. return fmt.Errorf("get head repository by ID: %v", err)
  76. }
  77. }
  78. if pr.BaseRepo == nil {
  79. pr.BaseRepo, err = getRepositoryByID(e, pr.BaseRepoID)
  80. if err != nil {
  81. return fmt.Errorf("get base repository by ID: %v", err)
  82. }
  83. }
  84. if pr.HasMerged && pr.Merger == nil {
  85. pr.Merger, err = getUserByID(e, pr.MergerID)
  86. if IsErrUserNotExist(err) {
  87. pr.MergerID = -1
  88. pr.Merger = NewGhostUser()
  89. } else if err != nil {
  90. return fmt.Errorf("get merger by ID: %v", 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. if err = os.MkdirAll(filepath.Dir(tmpBasePath), os.ModePerm); err != nil {
  186. return err
  187. }
  188. defer func() {
  189. _ = os.RemoveAll(filepath.Dir(tmpBasePath))
  190. }()
  191. // Clone the base repository to the defined temporary directory,
  192. // and checks out to base branch directly.
  193. var stderr string
  194. if _, stderr, err = process.ExecTimeout(5*time.Minute,
  195. fmt.Sprintf("PullRequest.Merge (git clone): %s", tmpBasePath),
  196. "git", "clone", "-b", pr.BaseBranch, baseGitRepo.Path(), tmpBasePath); err != nil {
  197. return fmt.Errorf("git clone: %s", stderr)
  198. }
  199. // Add remote which points to the head repository.
  200. if _, stderr, err = process.ExecDir(-1, tmpBasePath,
  201. fmt.Sprintf("PullRequest.Merge (git remote add): %s", tmpBasePath),
  202. "git", "remote", "add", "head_repo", headRepoPath); err != nil {
  203. return fmt.Errorf("git remote add [%s -> %s]: %s", headRepoPath, tmpBasePath, stderr)
  204. }
  205. // Fetch information from head repository to the temporary copy.
  206. if _, stderr, err = process.ExecDir(-1, tmpBasePath,
  207. fmt.Sprintf("PullRequest.Merge (git fetch): %s", tmpBasePath),
  208. "git", "fetch", "head_repo"); err != nil {
  209. return fmt.Errorf("git fetch [%s -> %s]: %s", headRepoPath, tmpBasePath, stderr)
  210. }
  211. remoteHeadBranch := "head_repo/" + pr.HeadBranch
  212. // Check if merge style is allowed, reset to default style if not
  213. if mergeStyle == MERGE_STYLE_REBASE && !pr.BaseRepo.PullsAllowRebase {
  214. mergeStyle = MERGE_STYLE_REGULAR
  215. }
  216. switch mergeStyle {
  217. case MERGE_STYLE_REGULAR: // Create merge commit
  218. // Merge changes from head branch.
  219. if _, stderr, err = process.ExecDir(-1, tmpBasePath,
  220. fmt.Sprintf("PullRequest.Merge (git merge --no-ff --no-commit): %s", tmpBasePath),
  221. "git", "merge", "--no-ff", "--no-commit", remoteHeadBranch); err != nil {
  222. return fmt.Errorf("git merge --no-ff --no-commit [%s]: %v - %s", tmpBasePath, err, stderr)
  223. }
  224. // Create a merge commit for the base branch.
  225. sig := doer.NewGitSig()
  226. if _, stderr, err = process.ExecDir(-1, tmpBasePath,
  227. fmt.Sprintf("PullRequest.Merge (git merge): %s", tmpBasePath),
  228. "git", "commit", fmt.Sprintf("--author='%s <%s>'", sig.Name, sig.Email),
  229. "-m", fmt.Sprintf("Merge branch '%s' of %s/%s into %s", pr.HeadBranch, pr.HeadUserName, pr.HeadRepo.Name, pr.BaseBranch),
  230. "-m", commitDescription); err != nil {
  231. return fmt.Errorf("git commit [%s]: %v - %s", tmpBasePath, err, stderr)
  232. }
  233. case MERGE_STYLE_REBASE: // Rebase before merging
  234. // Rebase head branch based on base branch, this creates a non-branch commit state.
  235. if _, stderr, err = process.ExecDir(-1, tmpBasePath,
  236. fmt.Sprintf("PullRequest.Merge (git rebase): %s", tmpBasePath),
  237. "git", "rebase", "--quiet", pr.BaseBranch, remoteHeadBranch); err != nil {
  238. return fmt.Errorf("git rebase [%s on %s]: %s", remoteHeadBranch, pr.BaseBranch, stderr)
  239. }
  240. // Name non-branch commit state to a new temporary branch in order to save changes.
  241. tmpBranch := com.ToStr(time.Now().UnixNano(), 10)
  242. if _, stderr, err = process.ExecDir(-1, tmpBasePath,
  243. fmt.Sprintf("PullRequest.Merge (git checkout): %s", tmpBasePath),
  244. "git", "checkout", "-b", tmpBranch); err != nil {
  245. return fmt.Errorf("git checkout '%s': %s", tmpBranch, stderr)
  246. }
  247. // Check out the base branch to be operated on.
  248. if _, stderr, err = process.ExecDir(-1, tmpBasePath,
  249. fmt.Sprintf("PullRequest.Merge (git checkout): %s", tmpBasePath),
  250. "git", "checkout", pr.BaseBranch); err != nil {
  251. return fmt.Errorf("git checkout '%s': %s", pr.BaseBranch, stderr)
  252. }
  253. // Merge changes from temporary branch to the base branch.
  254. if _, stderr, err = process.ExecDir(-1, tmpBasePath,
  255. fmt.Sprintf("PullRequest.Merge (git merge): %s", tmpBasePath),
  256. "git", "merge", tmpBranch); err != nil {
  257. return fmt.Errorf("git merge [%s]: %v - %s", tmpBasePath, err, stderr)
  258. }
  259. default:
  260. return fmt.Errorf("unknown merge style: %s", mergeStyle)
  261. }
  262. // Push changes on base branch to upstream.
  263. if _, stderr, err = process.ExecDir(-1, tmpBasePath,
  264. fmt.Sprintf("PullRequest.Merge (git push): %s", tmpBasePath),
  265. "git", "push", baseGitRepo.Path(), pr.BaseBranch); err != nil {
  266. return fmt.Errorf("git push: %s", stderr)
  267. }
  268. pr.MergedCommitID, err = headGitRepo.BranchCommitID(pr.HeadBranch)
  269. if err != nil {
  270. return fmt.Errorf("get head branch %q commit ID: %v", pr.HeadBranch, err)
  271. }
  272. pr.HasMerged = true
  273. pr.Merged = time.Now()
  274. pr.MergerID = doer.ID
  275. if _, err = sess.ID(pr.ID).AllCols().Update(pr); err != nil {
  276. return fmt.Errorf("update pull request: %v", err)
  277. }
  278. if err = sess.Commit(); err != nil {
  279. return fmt.Errorf("Commit: %v", err)
  280. }
  281. if err = MergePullRequestAction(doer, pr.Issue.Repo, pr.Issue); err != nil {
  282. log.Error("MergePullRequestAction [%d]: %v", pr.ID, err)
  283. }
  284. // Reload pull request information.
  285. if err = pr.LoadAttributes(); err != nil {
  286. log.Error("LoadAttributes: %v", err)
  287. return nil
  288. }
  289. if err = PrepareWebhooks(pr.Issue.Repo, HOOK_EVENT_PULL_REQUEST, &api.PullRequestPayload{
  290. Action: api.HOOK_ISSUE_CLOSED,
  291. Index: pr.Index,
  292. PullRequest: pr.APIFormat(),
  293. Repository: pr.Issue.Repo.APIFormat(nil),
  294. Sender: doer.APIFormat(),
  295. }); err != nil {
  296. log.Error("PrepareWebhooks: %v", err)
  297. return nil
  298. }
  299. commits, err := headGitRepo.RevList([]string{pr.MergeBase + "..." + pr.MergedCommitID})
  300. if err != nil {
  301. log.Error("Failed to list commits [merge_base: %s, merged_commit_id: %s]: %v", pr.MergeBase, pr.MergedCommitID, err)
  302. return nil
  303. }
  304. // NOTE: It is possible that head branch is not fully sync with base branch
  305. // for merge commits, so we need to get latest head commit and append merge
  306. // commit manually to avoid strange diff commits produced.
  307. mergeCommit, err := baseGitRepo.BranchCommit(pr.BaseBranch)
  308. if err != nil {
  309. log.Error("Failed to get base branch %q commit: %v", pr.BaseBranch, err)
  310. return nil
  311. }
  312. if mergeStyle == MERGE_STYLE_REGULAR {
  313. commits = append([]*git.Commit{mergeCommit}, commits...)
  314. }
  315. pcs, err := CommitsToPushCommits(commits).ToApiPayloadCommits(pr.BaseRepo.RepoPath(), pr.BaseRepo.HTMLURL())
  316. if err != nil {
  317. log.Error("Failed to convert to API payload commits: %v", err)
  318. return nil
  319. }
  320. p := &api.PushPayload{
  321. Ref: git.RefsHeads + pr.BaseBranch,
  322. Before: pr.MergeBase,
  323. After: mergeCommit.ID.String(),
  324. CompareURL: conf.Server.ExternalURL + pr.BaseRepo.ComposeCompareURL(pr.MergeBase, pr.MergedCommitID),
  325. Commits: pcs,
  326. Repo: pr.BaseRepo.APIFormat(nil),
  327. Pusher: pr.HeadRepo.MustOwner().APIFormat(),
  328. Sender: doer.APIFormat(),
  329. }
  330. if err = PrepareWebhooks(pr.BaseRepo, HOOK_EVENT_PUSH, p); err != nil {
  331. log.Error("Failed to prepare webhooks: %v", err)
  332. return nil
  333. }
  334. return nil
  335. }
  336. // testPatch checks if patch can be merged to base repository without conflict.
  337. // FIXME: make a mechanism to clean up stable local copies.
  338. func (pr *PullRequest) testPatch() (err error) {
  339. if pr.BaseRepo == nil {
  340. pr.BaseRepo, err = GetRepositoryByID(pr.BaseRepoID)
  341. if err != nil {
  342. return fmt.Errorf("GetRepositoryByID: %v", err)
  343. }
  344. }
  345. patchPath, err := pr.BaseRepo.PatchPath(pr.Index)
  346. if err != nil {
  347. return fmt.Errorf("BaseRepo.PatchPath: %v", err)
  348. }
  349. // Fast fail if patch does not exist, this assumes data is corrupted.
  350. if !osutil.IsFile(patchPath) {
  351. log.Trace("PullRequest[%d].testPatch: ignored corrupted data", pr.ID)
  352. return nil
  353. }
  354. repoWorkingPool.CheckIn(com.ToStr(pr.BaseRepoID))
  355. defer repoWorkingPool.CheckOut(com.ToStr(pr.BaseRepoID))
  356. log.Trace("PullRequest[%d].testPatch (patchPath): %s", pr.ID, patchPath)
  357. if err := pr.BaseRepo.UpdateLocalCopyBranch(pr.BaseBranch); err != nil {
  358. return fmt.Errorf("UpdateLocalCopy [%d]: %v", pr.BaseRepoID, err)
  359. }
  360. args := []string{"apply", "--check"}
  361. if pr.BaseRepo.PullsIgnoreWhitespace {
  362. args = append(args, "--ignore-whitespace")
  363. }
  364. args = append(args, patchPath)
  365. pr.Status = PULL_REQUEST_STATUS_CHECKING
  366. _, stderr, err := process.ExecDir(-1, pr.BaseRepo.LocalCopyPath(),
  367. fmt.Sprintf("testPatch (git apply --check): %d", pr.BaseRepo.ID),
  368. "git", args...)
  369. if err != nil {
  370. log.Trace("PullRequest[%d].testPatch (apply): has conflict\n%s", pr.ID, stderr)
  371. pr.Status = PULL_REQUEST_STATUS_CONFLICT
  372. return nil
  373. }
  374. return nil
  375. }
  376. // NewPullRequest creates new pull request with labels for repository.
  377. func NewPullRequest(repo *Repository, pull *Issue, labelIDs []int64, uuids []string, pr *PullRequest, patch []byte) (err error) {
  378. sess := x.NewSession()
  379. defer sess.Close()
  380. if err = sess.Begin(); err != nil {
  381. return err
  382. }
  383. if err = newIssue(sess, NewIssueOptions{
  384. Repo: repo,
  385. Issue: pull,
  386. LableIDs: labelIDs,
  387. Attachments: uuids,
  388. IsPull: true,
  389. }); err != nil {
  390. return fmt.Errorf("newIssue: %v", err)
  391. }
  392. pr.Index = pull.Index
  393. if err = repo.SavePatch(pr.Index, patch); err != nil {
  394. return fmt.Errorf("SavePatch: %v", err)
  395. }
  396. pr.BaseRepo = repo
  397. if err = pr.testPatch(); err != nil {
  398. return fmt.Errorf("testPatch: %v", err)
  399. }
  400. // No conflict appears after test means mergeable.
  401. if pr.Status == PULL_REQUEST_STATUS_CHECKING {
  402. pr.Status = PULL_REQUEST_STATUS_MERGEABLE
  403. }
  404. pr.IssueID = pull.ID
  405. if _, err = sess.Insert(pr); err != nil {
  406. return fmt.Errorf("insert pull repo: %v", err)
  407. }
  408. if err = sess.Commit(); err != nil {
  409. return fmt.Errorf("Commit: %v", err)
  410. }
  411. if err = NotifyWatchers(&Action{
  412. ActUserID: pull.Poster.ID,
  413. ActUserName: pull.Poster.Name,
  414. OpType: ACTION_CREATE_PULL_REQUEST,
  415. Content: fmt.Sprintf("%d|%s", pull.Index, pull.Title),
  416. RepoID: repo.ID,
  417. RepoUserName: repo.Owner.Name,
  418. RepoName: repo.Name,
  419. IsPrivate: repo.IsPrivate,
  420. }); err != nil {
  421. log.Error("NotifyWatchers: %v", err)
  422. }
  423. if err = pull.MailParticipants(); err != nil {
  424. log.Error("MailParticipants: %v", err)
  425. }
  426. pr.Issue = pull
  427. pull.PullRequest = pr
  428. if err = PrepareWebhooks(repo, HOOK_EVENT_PULL_REQUEST, &api.PullRequestPayload{
  429. Action: api.HOOK_ISSUE_OPENED,
  430. Index: pull.Index,
  431. PullRequest: pr.APIFormat(),
  432. Repository: repo.APIFormat(nil),
  433. Sender: pull.Poster.APIFormat(),
  434. }); err != nil {
  435. log.Error("PrepareWebhooks: %v", err)
  436. }
  437. return nil
  438. }
  439. // GetUnmergedPullRequest returns a pull request that is open and has not been merged
  440. // by given head/base and repo/branch.
  441. func GetUnmergedPullRequest(headRepoID, baseRepoID int64, headBranch, baseBranch string) (*PullRequest, error) {
  442. pr := new(PullRequest)
  443. has, err := x.Where("head_repo_id=? AND head_branch=? AND base_repo_id=? AND base_branch=? AND has_merged=? AND issue.is_closed=?",
  444. headRepoID, headBranch, baseRepoID, baseBranch, false, false).
  445. Join("INNER", "issue", "issue.id=pull_request.issue_id").Get(pr)
  446. if err != nil {
  447. return nil, err
  448. } else if !has {
  449. return nil, ErrPullRequestNotExist{args: map[string]interface{}{
  450. "headRepoID": headRepoID,
  451. "baseRepoID": baseRepoID,
  452. "headBranch": headBranch,
  453. "baseBranch": baseBranch,
  454. }}
  455. }
  456. return pr, nil
  457. }
  458. // GetUnmergedPullRequestsByHeadInfo returns all pull requests that are open and has not been merged
  459. // by given head information (repo and branch).
  460. func GetUnmergedPullRequestsByHeadInfo(repoID int64, branch string) ([]*PullRequest, error) {
  461. prs := make([]*PullRequest, 0, 2)
  462. return prs, x.Where("head_repo_id = ? AND head_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. // GetUnmergedPullRequestsByBaseInfo returns all pull requests that are open and has not been merged
  467. // by given base information (repo and branch).
  468. func GetUnmergedPullRequestsByBaseInfo(repoID int64, branch string) ([]*PullRequest, error) {
  469. prs := make([]*PullRequest, 0, 2)
  470. return prs, x.Where("base_repo_id=? AND base_branch=? AND has_merged=? AND issue.is_closed=?",
  471. repoID, branch, false, false).
  472. Join("INNER", "issue", "issue.id=pull_request.issue_id").Find(&prs)
  473. }
  474. var _ errutil.NotFound = (*ErrPullRequestNotExist)(nil)
  475. type ErrPullRequestNotExist struct {
  476. args map[string]interface{}
  477. }
  478. func IsErrPullRequestNotExist(err error) bool {
  479. _, ok := err.(ErrPullRequestNotExist)
  480. return ok
  481. }
  482. func (err ErrPullRequestNotExist) Error() string {
  483. return fmt.Sprintf("pull request does not exist: %v", err.args)
  484. }
  485. func (ErrPullRequestNotExist) NotFound() bool {
  486. return true
  487. }
  488. func getPullRequestByID(e Engine, id int64) (*PullRequest, error) {
  489. pr := new(PullRequest)
  490. has, err := e.ID(id).Get(pr)
  491. if err != nil {
  492. return nil, err
  493. } else if !has {
  494. return nil, ErrPullRequestNotExist{args: map[string]interface{}{"pullRequestID": id}}
  495. }
  496. return pr, pr.loadAttributes(e)
  497. }
  498. // GetPullRequestByID returns a pull request by given ID.
  499. func GetPullRequestByID(id int64) (*PullRequest, error) {
  500. return getPullRequestByID(x, id)
  501. }
  502. func getPullRequestByIssueID(e Engine, issueID int64) (*PullRequest, error) {
  503. pr := &PullRequest{
  504. IssueID: issueID,
  505. }
  506. has, err := e.Get(pr)
  507. if err != nil {
  508. return nil, err
  509. } else if !has {
  510. return nil, ErrPullRequestNotExist{args: map[string]interface{}{"issueID": issueID}}
  511. }
  512. return pr, pr.loadAttributes(e)
  513. }
  514. // GetPullRequestByIssueID returns pull request by given issue ID.
  515. func GetPullRequestByIssueID(issueID int64) (*PullRequest, error) {
  516. return getPullRequestByIssueID(x, issueID)
  517. }
  518. // Update updates all fields of pull request.
  519. func (pr *PullRequest) Update() error {
  520. _, err := x.Id(pr.ID).AllCols().Update(pr)
  521. return err
  522. }
  523. // Update updates specific fields of pull request.
  524. func (pr *PullRequest) UpdateCols(cols ...string) error {
  525. _, err := x.Id(pr.ID).Cols(cols...).Update(pr)
  526. return err
  527. }
  528. // UpdatePatch generates and saves a new patch.
  529. func (pr *PullRequest) UpdatePatch() (err error) {
  530. if pr.HeadRepo == nil {
  531. log.Trace("PullRequest[%d].UpdatePatch: ignored corrupted data", pr.ID)
  532. return nil
  533. }
  534. headGitRepo, err := git.Open(pr.HeadRepo.RepoPath())
  535. if err != nil {
  536. return fmt.Errorf("open repository: %v", err)
  537. }
  538. // Add a temporary remote.
  539. tmpRemote := com.ToStr(time.Now().UnixNano())
  540. baseRepoPath := RepoPath(pr.BaseRepo.MustOwner().Name, pr.BaseRepo.Name)
  541. err = headGitRepo.AddRemote(tmpRemote, baseRepoPath, git.AddRemoteOptions{Fetch: true})
  542. if err != nil {
  543. return fmt.Errorf("add remote %q [repo_id: %d]: %v", tmpRemote, pr.HeadRepoID, err)
  544. }
  545. defer func() {
  546. if err := headGitRepo.RemoveRemote(tmpRemote); err != nil {
  547. log.Error("Failed to remove remote %q [repo_id: %d]: %v", tmpRemote, pr.HeadRepoID, err)
  548. }
  549. }()
  550. remoteBranch := "remotes/" + tmpRemote + "/" + pr.BaseBranch
  551. pr.MergeBase, err = headGitRepo.MergeBase(remoteBranch, pr.HeadBranch)
  552. if err != nil {
  553. return fmt.Errorf("get merge base: %v", err)
  554. } else if err = pr.Update(); err != nil {
  555. return fmt.Errorf("update: %v", err)
  556. }
  557. patch, err := headGitRepo.DiffBinary(pr.MergeBase, pr.HeadBranch)
  558. if err != nil {
  559. return fmt.Errorf("get binary patch: %v", err)
  560. }
  561. if err = pr.BaseRepo.SavePatch(pr.Index, patch); err != nil {
  562. return fmt.Errorf("save patch: %v", err)
  563. }
  564. log.Trace("PullRequest[%d].UpdatePatch: patch saved", pr.ID)
  565. return nil
  566. }
  567. // PushToBaseRepo pushes commits from branches of head repository to
  568. // corresponding branches of base repository.
  569. // FIXME: Only push branches that are actually updates?
  570. func (pr *PullRequest) PushToBaseRepo() (err error) {
  571. log.Trace("PushToBaseRepo[%d]: pushing commits to base repo 'refs/pull/%d/head'", pr.BaseRepoID, pr.Index)
  572. headRepoPath := pr.HeadRepo.RepoPath()
  573. headGitRepo, err := git.Open(headRepoPath)
  574. if err != nil {
  575. return fmt.Errorf("open repository: %v", err)
  576. }
  577. tmpRemote := fmt.Sprintf("tmp-pull-%d", pr.ID)
  578. if err = headGitRepo.AddRemote(tmpRemote, pr.BaseRepo.RepoPath()); err != nil {
  579. return fmt.Errorf("add remote %q [repo_id: %d]: %v", tmpRemote, pr.HeadRepoID, err)
  580. }
  581. // Make sure to remove the remote even if the push fails
  582. defer func() {
  583. if err := headGitRepo.RemoveRemote(tmpRemote); err != nil {
  584. log.Error("Failed to remove remote %q [repo_id: %d]: %v", tmpRemote, pr.HeadRepoID, err)
  585. }
  586. }()
  587. headRefspec := fmt.Sprintf("refs/pull/%d/head", pr.Index)
  588. headFile := filepath.Join(pr.BaseRepo.RepoPath(), headRefspec)
  589. if osutil.IsExist(headFile) {
  590. err = os.Remove(headFile)
  591. if err != nil {
  592. return fmt.Errorf("remove head file [repo_id: %d]: %v", pr.BaseRepoID, err)
  593. }
  594. }
  595. err = headGitRepo.Push(tmpRemote, fmt.Sprintf("%s:%s", pr.HeadBranch, headRefspec))
  596. if err != nil {
  597. return fmt.Errorf("push: %v", err)
  598. }
  599. return nil
  600. }
  601. // AddToTaskQueue adds itself to pull request test task queue.
  602. func (pr *PullRequest) AddToTaskQueue() {
  603. go PullRequestQueue.AddFunc(pr.ID, func() {
  604. pr.Status = PULL_REQUEST_STATUS_CHECKING
  605. if err := pr.UpdateCols("status"); err != nil {
  606. log.Error("AddToTaskQueue.UpdateCols[%d].(add to queue): %v", pr.ID, err)
  607. }
  608. })
  609. }
  610. type PullRequestList []*PullRequest
  611. func (prs PullRequestList) loadAttributes(e Engine) (err error) {
  612. if len(prs) == 0 {
  613. return nil
  614. }
  615. // Load issues
  616. set := make(map[int64]*Issue)
  617. for i := range prs {
  618. set[prs[i].IssueID] = nil
  619. }
  620. issueIDs := make([]int64, 0, len(prs))
  621. for issueID := range set {
  622. issueIDs = append(issueIDs, issueID)
  623. }
  624. issues := make([]*Issue, 0, len(issueIDs))
  625. if err = e.Where("id > 0").In("id", issueIDs).Find(&issues); err != nil {
  626. return fmt.Errorf("find issues: %v", err)
  627. }
  628. for i := range issues {
  629. set[issues[i].ID] = issues[i]
  630. }
  631. for i := range prs {
  632. prs[i].Issue = set[prs[i].IssueID]
  633. }
  634. // Load attributes
  635. for i := range prs {
  636. if err = prs[i].loadAttributes(e); err != nil {
  637. return fmt.Errorf("loadAttributes [%d]: %v", prs[i].ID, err)
  638. }
  639. }
  640. return nil
  641. }
  642. func (prs PullRequestList) LoadAttributes() error {
  643. return prs.loadAttributes(x)
  644. }
  645. func addHeadRepoTasks(prs []*PullRequest) {
  646. for _, pr := range prs {
  647. log.Trace("addHeadRepoTasks[%d]: composing new test task", pr.ID)
  648. if err := pr.UpdatePatch(); err != nil {
  649. log.Error("UpdatePatch: %v", err)
  650. continue
  651. } else if err := pr.PushToBaseRepo(); err != nil {
  652. log.Error("PushToBaseRepo: %v", err)
  653. continue
  654. }
  655. pr.AddToTaskQueue()
  656. }
  657. }
  658. // AddTestPullRequestTask adds new test tasks by given head/base repository and head/base branch,
  659. // and generate new patch for testing as needed.
  660. func AddTestPullRequestTask(doer *User, repoID int64, branch string, isSync bool) {
  661. log.Trace("AddTestPullRequestTask [head_repo_id: %d, head_branch: %s]: finding pull requests", repoID, branch)
  662. prs, err := GetUnmergedPullRequestsByHeadInfo(repoID, branch)
  663. if err != nil {
  664. log.Error("Find pull requests [head_repo_id: %d, head_branch: %s]: %v", repoID, branch, err)
  665. return
  666. }
  667. if isSync {
  668. if err = PullRequestList(prs).LoadAttributes(); err != nil {
  669. log.Error("PullRequestList.LoadAttributes: %v", err)
  670. }
  671. if err == nil {
  672. for _, pr := range prs {
  673. pr.Issue.PullRequest = pr
  674. if err = pr.Issue.LoadAttributes(); err != nil {
  675. log.Error("LoadAttributes: %v", err)
  676. continue
  677. }
  678. if err = PrepareWebhooks(pr.Issue.Repo, HOOK_EVENT_PULL_REQUEST, &api.PullRequestPayload{
  679. Action: api.HOOK_ISSUE_SYNCHRONIZED,
  680. Index: pr.Issue.Index,
  681. PullRequest: pr.Issue.PullRequest.APIFormat(),
  682. Repository: pr.Issue.Repo.APIFormat(nil),
  683. Sender: doer.APIFormat(),
  684. }); err != nil {
  685. log.Error("PrepareWebhooks [pull_id: %v]: %v", pr.ID, err)
  686. continue
  687. }
  688. }
  689. }
  690. }
  691. addHeadRepoTasks(prs)
  692. log.Trace("AddTestPullRequestTask [base_repo_id: %d, base_branch: %s]: finding pull requests", repoID, branch)
  693. prs, err = GetUnmergedPullRequestsByBaseInfo(repoID, branch)
  694. if err != nil {
  695. log.Error("Find pull requests [base_repo_id: %d, base_branch: %s]: %v", repoID, branch, err)
  696. return
  697. }
  698. for _, pr := range prs {
  699. pr.AddToTaskQueue()
  700. }
  701. }
  702. func ChangeUsernameInPullRequests(oldUserName, newUserName string) error {
  703. pr := PullRequest{
  704. HeadUserName: strings.ToLower(newUserName),
  705. }
  706. _, err := x.Cols("head_user_name").Where("head_user_name = ?", strings.ToLower(oldUserName)).Update(pr)
  707. return err
  708. }
  709. // checkAndUpdateStatus checks if pull request is possible to leaving checking status,
  710. // and set to be either conflict or mergeable.
  711. func (pr *PullRequest) checkAndUpdateStatus() {
  712. // Status is not changed to conflict means mergeable.
  713. if pr.Status == PULL_REQUEST_STATUS_CHECKING {
  714. pr.Status = PULL_REQUEST_STATUS_MERGEABLE
  715. }
  716. // Make sure there is no waiting test to process before leaving the checking status.
  717. if !PullRequestQueue.Exist(pr.ID) {
  718. if err := pr.UpdateCols("status"); err != nil {
  719. log.Error("Update[%d]: %v", pr.ID, err)
  720. }
  721. }
  722. }
  723. // TestPullRequests checks and tests untested patches of pull requests.
  724. // TODO: test more pull requests at same time.
  725. func TestPullRequests() {
  726. prs := make([]*PullRequest, 0, 10)
  727. _ = x.Iterate(PullRequest{
  728. Status: PULL_REQUEST_STATUS_CHECKING,
  729. },
  730. func(idx int, bean interface{}) error {
  731. pr := bean.(*PullRequest)
  732. if err := pr.LoadAttributes(); err != nil {
  733. log.Error("LoadAttributes: %v", err)
  734. return nil
  735. }
  736. if err := pr.testPatch(); err != nil {
  737. log.Error("testPatch: %v", err)
  738. return nil
  739. }
  740. prs = append(prs, pr)
  741. return nil
  742. })
  743. // Update pull request status.
  744. for _, pr := range prs {
  745. pr.checkAndUpdateStatus()
  746. }
  747. // Start listening on new test requests.
  748. for prID := range PullRequestQueue.Queue() {
  749. log.Trace("TestPullRequests[%v]: processing test task", prID)
  750. PullRequestQueue.Remove(prID)
  751. pr, err := GetPullRequestByID(com.StrTo(prID).MustInt64())
  752. if err != nil {
  753. log.Error("GetPullRequestByID[%s]: %v", prID, err)
  754. continue
  755. } else if err = pr.testPatch(); err != nil {
  756. log.Error("testPatch[%d]: %v", pr.ID, err)
  757. continue
  758. }
  759. pr.checkAndUpdateStatus()
  760. }
  761. }
  762. func InitTestPullRequests() {
  763. go TestPullRequests()
  764. }