pull.go 27 KB

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