pull.go 27 KB

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