pull.go 27 KB

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