1
0

pull.go 27 KB

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