pull.go 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890
  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. "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 `gorm:"primaryKey"`
  37. Type PullRequestType
  38. Status PullRequestStatus
  39. IssueID int64 `xorm:"INDEX" gorm:"index"`
  40. Issue *Issue `xorm:"-" json:"-" gorm:"-"`
  41. Index int64
  42. HeadRepoID int64
  43. HeadRepo *Repository `xorm:"-" json:"-" gorm:"-"`
  44. BaseRepoID int64
  45. BaseRepo *Repository `xorm:"-" json:"-" gorm:"-"`
  46. HeadUserName string
  47. HeadBranch string
  48. BaseBranch string
  49. MergeBase string `xorm:"VARCHAR(40)" gorm:"type:VARCHAR(40)"`
  50. HasMerged bool
  51. MergedCommitID string `xorm:"VARCHAR(40)" gorm:"type:VARCHAR(40)"`
  52. MergerID int64
  53. Merger *User `xorm:"-" json:"-" gorm:"-"`
  54. Merged time.Time `xorm:"-" json:"-" gorm:"-"`
  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.APIFormatLegacy(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.APIFormatLegacy(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. ctx := context.TODO()
  166. defer func() {
  167. go HookQueue.Add(pr.BaseRepo.ID)
  168. go AddTestPullRequestTask(doer, pr.BaseRepo.ID, pr.BaseBranch, false)
  169. }()
  170. sess := x.NewSession()
  171. defer sess.Close()
  172. if err = sess.Begin(); err != nil {
  173. return err
  174. }
  175. if err = pr.Issue.changeStatus(sess, doer, pr.Issue.Repo, true); err != nil {
  176. return fmt.Errorf("Issue.changeStatus: %v", err)
  177. }
  178. headRepoPath := RepoPath(pr.HeadUserName, pr.HeadRepo.Name)
  179. headGitRepo, err := git.Open(headRepoPath)
  180. if err != nil {
  181. return fmt.Errorf("open repository: %v", err)
  182. }
  183. // Create temporary directory to store temporary copy of the base repository,
  184. // and clean it up when operation finished regardless of succeed or not.
  185. tmpBasePath := filepath.Join(conf.Server.AppDataPath, "tmp", "repos", com.ToStr(time.Now().Nanosecond())+".git")
  186. if err = os.MkdirAll(filepath.Dir(tmpBasePath), os.ModePerm); err != nil {
  187. return err
  188. }
  189. defer func() {
  190. _ = os.RemoveAll(filepath.Dir(tmpBasePath))
  191. }()
  192. // Clone the base repository to the defined temporary directory,
  193. // and checks out to base branch directly.
  194. var stderr string
  195. if _, stderr, err = process.ExecTimeout(5*time.Minute,
  196. fmt.Sprintf("PullRequest.Merge (git clone): %s", tmpBasePath),
  197. "git", "clone", "-b", pr.BaseBranch, baseGitRepo.Path(), tmpBasePath); err != nil {
  198. return fmt.Errorf("git clone: %s", stderr)
  199. }
  200. // Add remote which points to the head repository.
  201. if _, stderr, err = process.ExecDir(-1, tmpBasePath,
  202. fmt.Sprintf("PullRequest.Merge (git remote add): %s", tmpBasePath),
  203. "git", "remote", "add", "head_repo", headRepoPath); err != nil {
  204. return fmt.Errorf("git remote add [%s -> %s]: %s", headRepoPath, tmpBasePath, stderr)
  205. }
  206. // Fetch information from head repository to the temporary copy.
  207. if _, stderr, err = process.ExecDir(-1, tmpBasePath,
  208. fmt.Sprintf("PullRequest.Merge (git fetch): %s", tmpBasePath),
  209. "git", "fetch", "head_repo"); err != nil {
  210. return fmt.Errorf("git fetch [%s -> %s]: %s", headRepoPath, tmpBasePath, stderr)
  211. }
  212. remoteHeadBranch := "head_repo/" + pr.HeadBranch
  213. // Check if merge style is allowed, reset to default style if not
  214. if mergeStyle == MERGE_STYLE_REBASE && !pr.BaseRepo.PullsAllowRebase {
  215. mergeStyle = MERGE_STYLE_REGULAR
  216. }
  217. switch mergeStyle {
  218. case MERGE_STYLE_REGULAR: // Create merge commit
  219. // Merge changes from head branch.
  220. if _, stderr, err = process.ExecDir(-1, tmpBasePath,
  221. fmt.Sprintf("PullRequest.Merge (git merge --no-ff --no-commit): %s", tmpBasePath),
  222. "git", "merge", "--no-ff", "--no-commit", remoteHeadBranch); err != nil {
  223. return fmt.Errorf("git merge --no-ff --no-commit [%s]: %v - %s", tmpBasePath, err, stderr)
  224. }
  225. // Create a merge commit for the base branch.
  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>'", doer.DisplayName(), doer.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 = Actions.MergePullRequest(ctx, doer, pr.Issue.Repo.Owner, pr.Issue.Repo, pr.Issue); err != nil {
  282. log.Error("Failed to create action for merge pull request, pull_request_id: %d, error: %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.APIFormatLegacy(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).APIFormat(ctx, Users, 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.APIFormatLegacy(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: ActionCreatePullRequest,
  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.APIFormatLegacy(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]any{
  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]any
  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]any{"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]any{"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. headGitRepo, err := git.Open(pr.HeadRepo.RepoPath())
  531. if err != nil {
  532. return fmt.Errorf("open repository: %v", err)
  533. }
  534. // Add a temporary remote.
  535. tmpRemote := com.ToStr(time.Now().UnixNano())
  536. baseRepoPath := RepoPath(pr.BaseRepo.MustOwner().Name, pr.BaseRepo.Name)
  537. err = headGitRepo.RemoteAdd(tmpRemote, baseRepoPath, git.RemoteAddOptions{Fetch: true})
  538. if err != nil {
  539. return fmt.Errorf("add remote %q [repo_id: %d]: %v", tmpRemote, pr.HeadRepoID, err)
  540. }
  541. defer func() {
  542. if err := headGitRepo.RemoteRemove(tmpRemote); err != nil {
  543. log.Error("Failed to remove remote %q [repo_id: %d]: %v", tmpRemote, pr.HeadRepoID, err)
  544. }
  545. }()
  546. remoteBranch := "remotes/" + tmpRemote + "/" + pr.BaseBranch
  547. pr.MergeBase, err = headGitRepo.MergeBase(remoteBranch, pr.HeadBranch)
  548. if err != nil {
  549. return fmt.Errorf("get merge base: %v", err)
  550. } else if err = pr.Update(); err != nil {
  551. return fmt.Errorf("update: %v", err)
  552. }
  553. patch, err := headGitRepo.DiffBinary(pr.MergeBase, pr.HeadBranch)
  554. if err != nil {
  555. return fmt.Errorf("get binary patch: %v", err)
  556. }
  557. if err = pr.BaseRepo.SavePatch(pr.Index, patch); err != nil {
  558. return fmt.Errorf("save patch: %v", err)
  559. }
  560. log.Trace("PullRequest[%d].UpdatePatch: patch saved", pr.ID)
  561. return nil
  562. }
  563. // PushToBaseRepo pushes commits from branches of head repository to
  564. // corresponding branches of base repository.
  565. // FIXME: Only push branches that are actually updates?
  566. func (pr *PullRequest) PushToBaseRepo() (err error) {
  567. log.Trace("PushToBaseRepo[%d]: pushing commits to base repo 'refs/pull/%d/head'", pr.BaseRepoID, pr.Index)
  568. headRepoPath := pr.HeadRepo.RepoPath()
  569. headGitRepo, err := git.Open(headRepoPath)
  570. if err != nil {
  571. return fmt.Errorf("open repository: %v", err)
  572. }
  573. tmpRemote := fmt.Sprintf("tmp-pull-%d", pr.ID)
  574. if err = headGitRepo.RemoteAdd(tmpRemote, pr.BaseRepo.RepoPath()); err != nil {
  575. return fmt.Errorf("add remote %q [repo_id: %d]: %v", tmpRemote, pr.HeadRepoID, err)
  576. }
  577. // Make sure to remove the remote even if the push fails
  578. defer func() {
  579. if err := headGitRepo.RemoteRemove(tmpRemote); err != nil {
  580. log.Error("Failed to remove remote %q [repo_id: %d]: %v", tmpRemote, pr.HeadRepoID, err)
  581. }
  582. }()
  583. headRefspec := fmt.Sprintf("refs/pull/%d/head", pr.Index)
  584. headFile := filepath.Join(pr.BaseRepo.RepoPath(), headRefspec)
  585. if osutil.IsExist(headFile) {
  586. err = os.Remove(headFile)
  587. if err != nil {
  588. return fmt.Errorf("remove head file [repo_id: %d]: %v", pr.BaseRepoID, err)
  589. }
  590. }
  591. err = headGitRepo.Push(tmpRemote, fmt.Sprintf("%s:%s", pr.HeadBranch, headRefspec))
  592. if err != nil {
  593. return fmt.Errorf("push: %v", err)
  594. }
  595. return nil
  596. }
  597. // AddToTaskQueue adds itself to pull request test task queue.
  598. func (pr *PullRequest) AddToTaskQueue() {
  599. go PullRequestQueue.AddFunc(pr.ID, func() {
  600. pr.Status = PULL_REQUEST_STATUS_CHECKING
  601. if err := pr.UpdateCols("status"); err != nil {
  602. log.Error("AddToTaskQueue.UpdateCols[%d].(add to queue): %v", pr.ID, err)
  603. }
  604. })
  605. }
  606. type PullRequestList []*PullRequest
  607. func (prs PullRequestList) loadAttributes(e Engine) (err error) {
  608. if len(prs) == 0 {
  609. return nil
  610. }
  611. // Load issues
  612. set := make(map[int64]*Issue)
  613. for i := range prs {
  614. set[prs[i].IssueID] = nil
  615. }
  616. issueIDs := make([]int64, 0, len(prs))
  617. for issueID := range set {
  618. issueIDs = append(issueIDs, issueID)
  619. }
  620. issues := make([]*Issue, 0, len(issueIDs))
  621. if err = e.Where("id > 0").In("id", issueIDs).Find(&issues); err != nil {
  622. return fmt.Errorf("find issues: %v", err)
  623. }
  624. for i := range issues {
  625. set[issues[i].ID] = issues[i]
  626. }
  627. for i := range prs {
  628. prs[i].Issue = set[prs[i].IssueID]
  629. }
  630. // Load attributes
  631. for i := range prs {
  632. if err = prs[i].loadAttributes(e); err != nil {
  633. return fmt.Errorf("loadAttributes [%d]: %v", prs[i].ID, err)
  634. }
  635. }
  636. return nil
  637. }
  638. func (prs PullRequestList) LoadAttributes() error {
  639. return prs.loadAttributes(x)
  640. }
  641. func addHeadRepoTasks(prs []*PullRequest) {
  642. for _, pr := range prs {
  643. if pr.HeadRepo == nil {
  644. log.Trace("addHeadRepoTasks[%d]: missing head repository", pr.ID)
  645. continue
  646. }
  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.APIFormatLegacy(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. // checkAndUpdateStatus checks if pull request is possible to leaving checking status,
  703. // and set to be either conflict or mergeable.
  704. func (pr *PullRequest) checkAndUpdateStatus() {
  705. // Status is not changed to conflict means mergeable.
  706. if pr.Status == PULL_REQUEST_STATUS_CHECKING {
  707. pr.Status = PULL_REQUEST_STATUS_MERGEABLE
  708. }
  709. // Make sure there is no waiting test to process before leaving the checking status.
  710. if !PullRequestQueue.Exist(pr.ID) {
  711. if err := pr.UpdateCols("status"); err != nil {
  712. log.Error("Update[%d]: %v", pr.ID, err)
  713. }
  714. }
  715. }
  716. // TestPullRequests checks and tests untested patches of pull requests.
  717. // TODO: test more pull requests at same time.
  718. func TestPullRequests() {
  719. prs := make([]*PullRequest, 0, 10)
  720. _ = x.Iterate(PullRequest{
  721. Status: PULL_REQUEST_STATUS_CHECKING,
  722. },
  723. func(idx int, bean any) error {
  724. pr := bean.(*PullRequest)
  725. if err := pr.LoadAttributes(); err != nil {
  726. log.Error("LoadAttributes: %v", err)
  727. return nil
  728. }
  729. if err := pr.testPatch(); err != nil {
  730. log.Error("testPatch: %v", err)
  731. return nil
  732. }
  733. prs = append(prs, pr)
  734. return nil
  735. })
  736. // Update pull request status.
  737. for _, pr := range prs {
  738. pr.checkAndUpdateStatus()
  739. }
  740. // Start listening on new test requests.
  741. for prID := range PullRequestQueue.Queue() {
  742. log.Trace("TestPullRequests[%v]: processing test task", prID)
  743. PullRequestQueue.Remove(prID)
  744. pr, err := GetPullRequestByID(com.StrTo(prID).MustInt64())
  745. if err != nil {
  746. log.Error("GetPullRequestByID[%s]: %v", prID, err)
  747. continue
  748. } else if err = pr.testPatch(); err != nil {
  749. log.Error("testPatch[%d]: %v", pr.ID, err)
  750. continue
  751. }
  752. pr.checkAndUpdateStatus()
  753. }
  754. }
  755. func InitTestPullRequests() {
  756. go TestPullRequests()
  757. }