1
0

pull.go 27 KB

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