You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1101 lines
33 KiB

9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 years ago
8 years ago
8 years ago
8 years ago
9 years ago
9 years ago
  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 models
  5. import (
  6. "fmt"
  7. "io/ioutil"
  8. "os"
  9. "path"
  10. "path/filepath"
  11. "strconv"
  12. "strings"
  13. "time"
  14. "code.gitea.io/git"
  15. "code.gitea.io/gitea/modules/base"
  16. "code.gitea.io/gitea/modules/log"
  17. "code.gitea.io/gitea/modules/process"
  18. "code.gitea.io/gitea/modules/setting"
  19. "code.gitea.io/gitea/modules/sync"
  20. api "code.gitea.io/sdk/gitea"
  21. "github.com/Unknwon/com"
  22. "github.com/go-xorm/xorm"
  23. )
  24. var pullRequestQueue = sync.NewUniqueQueue(setting.Repository.PullRequestQueueLength)
  25. // PullRequestType defines pull request type
  26. type PullRequestType int
  27. // Enumerate all the pull request types
  28. const (
  29. PullRequestGitea PullRequestType = iota
  30. PullRequestGit
  31. )
  32. // PullRequestStatus defines pull request status
  33. type PullRequestStatus int
  34. // Enumerate all the pull request status
  35. const (
  36. PullRequestStatusConflict PullRequestStatus = iota
  37. PullRequestStatusChecking
  38. PullRequestStatusMergeable
  39. PullRequestStatusManuallyMerged
  40. )
  41. // PullRequest represents relation between pull request and repositories.
  42. type PullRequest struct {
  43. ID int64 `xorm:"pk autoincr"`
  44. Type PullRequestType
  45. Status PullRequestStatus
  46. IssueID int64 `xorm:"INDEX"`
  47. Issue *Issue `xorm:"-"`
  48. Index int64
  49. HeadRepoID int64 `xorm:"INDEX"`
  50. HeadRepo *Repository `xorm:"-"`
  51. BaseRepoID int64 `xorm:"INDEX"`
  52. BaseRepo *Repository `xorm:"-"`
  53. HeadUserName string
  54. HeadBranch string
  55. BaseBranch string
  56. MergeBase string `xorm:"VARCHAR(40)"`
  57. HasMerged bool `xorm:"INDEX"`
  58. MergedCommitID string `xorm:"VARCHAR(40)"`
  59. MergerID int64 `xorm:"INDEX"`
  60. Merger *User `xorm:"-"`
  61. Merged time.Time `xorm:"-"`
  62. MergedUnix int64 `xorm:"INDEX"`
  63. }
  64. // BeforeUpdate is invoked from XORM before updating an object of this type.
  65. func (pr *PullRequest) BeforeUpdate() {
  66. pr.MergedUnix = pr.Merged.Unix()
  67. }
  68. // AfterSet is invoked from XORM after setting the value of a field of this object.
  69. // Note: don't try to get Issue because will end up recursive querying.
  70. func (pr *PullRequest) AfterSet(colName string, _ xorm.Cell) {
  71. switch colName {
  72. case "merged_unix":
  73. if !pr.HasMerged {
  74. return
  75. }
  76. pr.Merged = time.Unix(pr.MergedUnix, 0).Local()
  77. }
  78. }
  79. // Note: don't try to get Issue because will end up recursive querying.
  80. func (pr *PullRequest) loadAttributes(e Engine) (err error) {
  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("getUserByID [%d]: %v", pr.MergerID, err)
  88. }
  89. }
  90. return nil
  91. }
  92. // LoadAttributes loads pull request attributes from database
  93. func (pr *PullRequest) LoadAttributes() error {
  94. return pr.loadAttributes(x)
  95. }
  96. // LoadIssue loads issue information from database
  97. func (pr *PullRequest) LoadIssue() (err error) {
  98. if pr.Issue != nil {
  99. return nil
  100. }
  101. pr.Issue, err = GetIssueByID(pr.IssueID)
  102. return err
  103. }
  104. // APIFormat assumes following fields have been assigned with valid values:
  105. // Required - Issue
  106. // Optional - Merger
  107. func (pr *PullRequest) APIFormat() *api.PullRequest {
  108. var (
  109. baseBranch *Branch
  110. headBranch *Branch
  111. baseCommit *git.Commit
  112. headCommit *git.Commit
  113. err error
  114. )
  115. apiIssue := pr.Issue.APIFormat()
  116. if pr.BaseRepo == nil {
  117. pr.BaseRepo, err = GetRepositoryByID(pr.BaseRepoID)
  118. if err != nil {
  119. log.Error(log.ERROR, "GetRepositoryById[%d]: %v", pr.ID, err)
  120. return nil
  121. }
  122. }
  123. if pr.HeadRepo == nil {
  124. pr.HeadRepo, err = GetRepositoryByID(pr.HeadRepoID)
  125. if err != nil {
  126. log.Error(log.ERROR, "GetRepositoryById[%d]: %v", pr.ID, err)
  127. return nil
  128. }
  129. }
  130. if baseBranch, err = pr.BaseRepo.GetBranch(pr.BaseBranch); err != nil {
  131. return nil
  132. }
  133. if baseCommit, err = baseBranch.GetCommit(); err != nil {
  134. return nil
  135. }
  136. if headBranch, err = pr.HeadRepo.GetBranch(pr.HeadBranch); err != nil {
  137. return nil
  138. }
  139. if headCommit, err = headBranch.GetCommit(); err != nil {
  140. return nil
  141. }
  142. apiBaseBranchInfo := &api.PRBranchInfo{
  143. Name: pr.BaseBranch,
  144. Ref: pr.BaseBranch,
  145. Sha: baseCommit.ID.String(),
  146. RepoID: pr.BaseRepoID,
  147. Repository: pr.BaseRepo.APIFormat(AccessModeNone),
  148. }
  149. apiHeadBranchInfo := &api.PRBranchInfo{
  150. Name: pr.HeadBranch,
  151. Ref: pr.HeadBranch,
  152. Sha: headCommit.ID.String(),
  153. RepoID: pr.HeadRepoID,
  154. Repository: pr.HeadRepo.APIFormat(AccessModeNone),
  155. }
  156. apiPullRequest := &api.PullRequest{
  157. ID: pr.ID,
  158. Index: pr.Index,
  159. Poster: apiIssue.Poster,
  160. Title: apiIssue.Title,
  161. Body: apiIssue.Body,
  162. Labels: apiIssue.Labels,
  163. Milestone: apiIssue.Milestone,
  164. Assignee: apiIssue.Assignee,
  165. State: apiIssue.State,
  166. Comments: apiIssue.Comments,
  167. HTMLURL: pr.Issue.HTMLURL(),
  168. DiffURL: pr.Issue.DiffURL(),
  169. PatchURL: pr.Issue.PatchURL(),
  170. HasMerged: pr.HasMerged,
  171. Base: apiBaseBranchInfo,
  172. Head: apiHeadBranchInfo,
  173. MergeBase: pr.MergeBase,
  174. }
  175. if pr.Status != PullRequestStatusChecking {
  176. mergeable := pr.Status != PullRequestStatusConflict
  177. apiPullRequest.Mergeable = mergeable
  178. }
  179. if pr.HasMerged {
  180. apiPullRequest.Merged = &pr.Merged
  181. apiPullRequest.MergedCommitID = &pr.MergedCommitID
  182. apiPullRequest.MergedBy = pr.Merger.APIFormat()
  183. }
  184. return apiPullRequest
  185. }
  186. func (pr *PullRequest) getHeadRepo(e Engine) (err error) {
  187. pr.HeadRepo, err = getRepositoryByID(e, pr.HeadRepoID)
  188. if err != nil && !IsErrRepoNotExist(err) {
  189. return fmt.Errorf("getRepositoryByID(head): %v", err)
  190. }
  191. return nil
  192. }
  193. // GetHeadRepo loads the head repository
  194. func (pr *PullRequest) GetHeadRepo() error {
  195. return pr.getHeadRepo(x)
  196. }
  197. // GetBaseRepo loads the target repository
  198. func (pr *PullRequest) GetBaseRepo() (err error) {
  199. if pr.BaseRepo != nil {
  200. return nil
  201. }
  202. pr.BaseRepo, err = GetRepositoryByID(pr.BaseRepoID)
  203. if err != nil {
  204. return fmt.Errorf("GetRepositoryByID(base): %v", err)
  205. }
  206. return nil
  207. }
  208. // IsChecking returns true if this pull request is still checking conflict.
  209. func (pr *PullRequest) IsChecking() bool {
  210. return pr.Status == PullRequestStatusChecking
  211. }
  212. // CanAutoMerge returns true if this pull request can be merged automatically.
  213. func (pr *PullRequest) CanAutoMerge() bool {
  214. return pr.Status == PullRequestStatusMergeable
  215. }
  216. // Merge merges pull request to base repository.
  217. // FIXME: add repoWorkingPull make sure two merges does not happen at same time.
  218. func (pr *PullRequest) Merge(doer *User, baseGitRepo *git.Repository) (err error) {
  219. if err = pr.GetHeadRepo(); err != nil {
  220. return fmt.Errorf("GetHeadRepo: %v", err)
  221. } else if err = pr.GetBaseRepo(); err != nil {
  222. return fmt.Errorf("GetBaseRepo: %v", err)
  223. }
  224. defer func() {
  225. go HookQueue.Add(pr.BaseRepo.ID)
  226. go AddTestPullRequestTask(doer, pr.BaseRepo.ID, pr.BaseBranch, false)
  227. }()
  228. headRepoPath := RepoPath(pr.HeadUserName, pr.HeadRepo.Name)
  229. headGitRepo, err := git.OpenRepository(headRepoPath)
  230. if err != nil {
  231. return fmt.Errorf("OpenRepository: %v", err)
  232. }
  233. // Clone base repo.
  234. tmpBasePath := path.Join(setting.AppDataPath, "tmp/repos", com.ToStr(time.Now().Nanosecond())+".git")
  235. if err := os.MkdirAll(path.Dir(tmpBasePath), os.ModePerm); err != nil {
  236. return fmt.Errorf("Failed to create dir %s: %v", tmpBasePath, err)
  237. }
  238. defer os.RemoveAll(path.Dir(tmpBasePath))
  239. var stderr string
  240. if _, stderr, err = process.GetManager().ExecTimeout(5*time.Minute,
  241. fmt.Sprintf("PullRequest.Merge (git clone): %s", tmpBasePath),
  242. "git", "clone", baseGitRepo.Path, tmpBasePath); err != nil {
  243. return fmt.Errorf("git clone: %s", stderr)
  244. }
  245. // Check out base branch.
  246. if _, stderr, err = process.GetManager().ExecDir(-1, tmpBasePath,
  247. fmt.Sprintf("PullRequest.Merge (git checkout): %s", tmpBasePath),
  248. "git", "checkout", pr.BaseBranch); err != nil {
  249. return fmt.Errorf("git checkout: %s", stderr)
  250. }
  251. // Add head repo remote.
  252. if _, stderr, err = process.GetManager().ExecDir(-1, tmpBasePath,
  253. fmt.Sprintf("PullRequest.Merge (git remote add): %s", tmpBasePath),
  254. "git", "remote", "add", "head_repo", headRepoPath); err != nil {
  255. return fmt.Errorf("git remote add [%s -> %s]: %s", headRepoPath, tmpBasePath, stderr)
  256. }
  257. // Merge commits.
  258. if _, stderr, err = process.GetManager().ExecDir(-1, tmpBasePath,
  259. fmt.Sprintf("PullRequest.Merge (git fetch): %s", tmpBasePath),
  260. "git", "fetch", "head_repo"); err != nil {
  261. return fmt.Errorf("git fetch [%s -> %s]: %s", headRepoPath, tmpBasePath, stderr)
  262. }
  263. if _, stderr, err = process.GetManager().ExecDir(-1, tmpBasePath,
  264. fmt.Sprintf("PullRequest.Merge (git merge --no-ff --no-commit): %s", tmpBasePath),
  265. "git", "merge", "--no-ff", "--no-commit", "head_repo/"+pr.HeadBranch); err != nil {
  266. return fmt.Errorf("git merge --no-ff --no-commit [%s]: %v - %s", tmpBasePath, err, stderr)
  267. }
  268. sig := doer.NewGitSig()
  269. if _, stderr, err = process.GetManager().ExecDir(-1, tmpBasePath,
  270. fmt.Sprintf("PullRequest.Merge (git merge): %s", tmpBasePath),
  271. "git", "commit", fmt.Sprintf("--author='%s <%s>'", sig.Name, sig.Email),
  272. "-m", fmt.Sprintf("Merge branch '%s' of %s/%s into %s", pr.HeadBranch, pr.HeadUserName, pr.HeadRepo.Name, pr.BaseBranch)); err != nil {
  273. return fmt.Errorf("git commit [%s]: %v - %s", tmpBasePath, err, stderr)
  274. }
  275. // Push back to upstream.
  276. if _, stderr, err = process.GetManager().ExecDir(-1, tmpBasePath,
  277. fmt.Sprintf("PullRequest.Merge (git push): %s", tmpBasePath),
  278. "git", "push", baseGitRepo.Path, pr.BaseBranch); err != nil {
  279. return fmt.Errorf("git push: %s", stderr)
  280. }
  281. pr.MergedCommitID, err = headGitRepo.GetBranchCommitID(pr.HeadBranch)
  282. if err != nil {
  283. return fmt.Errorf("GetBranchCommit: %v", err)
  284. }
  285. pr.Merged = time.Now()
  286. pr.Merger = doer
  287. pr.MergerID = doer.ID
  288. if err = pr.setMerged(); err != nil {
  289. log.Error(4, "setMerged [%d]: %v", pr.ID, err)
  290. }
  291. if err = MergePullRequestAction(doer, pr.Issue.Repo, pr.Issue); err != nil {
  292. log.Error(4, "MergePullRequestAction [%d]: %v", pr.ID, err)
  293. }
  294. // Reload pull request information.
  295. if err = pr.LoadAttributes(); err != nil {
  296. log.Error(4, "LoadAttributes: %v", err)
  297. return nil
  298. }
  299. if err = PrepareWebhooks(pr.Issue.Repo, HookEventPullRequest, &api.PullRequestPayload{
  300. Action: api.HookIssueClosed,
  301. Index: pr.Index,
  302. PullRequest: pr.APIFormat(),
  303. Repository: pr.Issue.Repo.APIFormat(AccessModeNone),
  304. Sender: doer.APIFormat(),
  305. }); err != nil {
  306. log.Error(4, "PrepareWebhooks: %v", err)
  307. return nil
  308. }
  309. l, err := headGitRepo.CommitsBetweenIDs(pr.MergedCommitID, pr.MergeBase)
  310. if err != nil {
  311. log.Error(4, "CommitsBetweenIDs: %v", err)
  312. return nil
  313. }
  314. // TODO: when squash commits, no need to append merge commit.
  315. // It is possible that head branch is not fully sync with base branch for merge commits,
  316. // so we need to get latest head commit and append merge commit manually
  317. // to avoid strange diff commits produced.
  318. mergeCommit, err := baseGitRepo.GetBranchCommit(pr.BaseBranch)
  319. if err != nil {
  320. log.Error(4, "GetBranchCommit: %v", err)
  321. return nil
  322. }
  323. l.PushFront(mergeCommit)
  324. p := &api.PushPayload{
  325. Ref: git.BranchPrefix + pr.BaseBranch,
  326. Before: pr.MergeBase,
  327. After: pr.MergedCommitID,
  328. CompareURL: setting.AppURL + pr.BaseRepo.ComposeCompareURL(pr.MergeBase, pr.MergedCommitID),
  329. Commits: ListToPushCommits(l).ToAPIPayloadCommits(pr.BaseRepo.HTMLURL()),
  330. Repo: pr.BaseRepo.APIFormat(AccessModeNone),
  331. Pusher: pr.HeadRepo.MustOwner().APIFormat(),
  332. Sender: doer.APIFormat(),
  333. }
  334. if err = PrepareWebhooks(pr.BaseRepo, HookEventPush, p); err != nil {
  335. return fmt.Errorf("PrepareWebhooks: %v", err)
  336. }
  337. return nil
  338. }
  339. // setMerged sets a pull request to merged and closes the corresponding issue
  340. func (pr *PullRequest) setMerged() (err error) {
  341. if pr.HasMerged {
  342. return fmt.Errorf("PullRequest[%d] already merged", pr.Index)
  343. }
  344. if pr.MergedCommitID == "" || pr.Merged.IsZero() || pr.Merger == nil {
  345. return fmt.Errorf("Unable to merge PullRequest[%d], some required fields are empty", pr.Index)
  346. }
  347. pr.HasMerged = true
  348. sess := x.NewSession()
  349. defer sessionRelease(sess)
  350. if err = sess.Begin(); err != nil {
  351. return err
  352. }
  353. if err = pr.LoadIssue(); err != nil {
  354. return err
  355. }
  356. if pr.Issue.Repo.Owner == nil {
  357. if err = pr.Issue.Repo.GetOwner(); err != nil {
  358. return err
  359. }
  360. }
  361. if err = pr.Issue.changeStatus(sess, pr.Merger, pr.Issue.Repo, true); err != nil {
  362. return fmt.Errorf("Issue.changeStatus: %v", err)
  363. }
  364. if _, err = sess.Id(pr.ID).AllCols().Update(pr); err != nil {
  365. return fmt.Errorf("update pull request: %v", err)
  366. }
  367. if err = sess.Commit(); err != nil {
  368. return fmt.Errorf("Commit: %v", err)
  369. }
  370. return nil
  371. }
  372. // manuallyMerged checks if a pull request got manually merged
  373. // When a pull request got manually merged mark the pull request as merged
  374. func (pr *PullRequest) manuallyMerged() bool {
  375. commit, err := pr.getMergeCommit()
  376. if err != nil {
  377. log.Error(4, "PullRequest[%d].getMergeCommit: %v", pr.ID, err)
  378. return false
  379. }
  380. if commit != nil {
  381. pr.MergedCommitID = commit.ID.String()
  382. pr.Merged = commit.Author.When
  383. pr.Status = PullRequestStatusManuallyMerged
  384. merger, _ := GetUserByEmail(commit.Author.Email)
  385. // When the commit author is unknown set the BaseRepo owner as merger
  386. if merger == nil {
  387. if pr.BaseRepo.Owner == nil {
  388. if err = pr.BaseRepo.getOwner(x); err != nil {
  389. log.Error(4, "BaseRepo.getOwner[%d]: %v", pr.ID, err)
  390. return false
  391. }
  392. }
  393. merger = pr.BaseRepo.Owner
  394. }
  395. pr.Merger = merger
  396. pr.MergerID = merger.ID
  397. if err = pr.setMerged(); err != nil {
  398. log.Error(4, "PullRequest[%d].setMerged : %v", pr.ID, err)
  399. return false
  400. }
  401. log.Info("manuallyMerged[%d]: Marked as manually merged into %s/%s by commit id: %s", pr.ID, pr.BaseRepo.Name, pr.BaseBranch, commit.ID.String())
  402. return true
  403. }
  404. return false
  405. }
  406. // getMergeCommit checks if a pull request got merged
  407. // Returns the git.Commit of the pull request if merged
  408. func (pr *PullRequest) getMergeCommit() (*git.Commit, error) {
  409. if pr.BaseRepo == nil {
  410. var err error
  411. pr.BaseRepo, err = GetRepositoryByID(pr.BaseRepoID)
  412. if err != nil {
  413. return nil, fmt.Errorf("GetRepositoryByID: %v", err)
  414. }
  415. }
  416. indexTmpPath := filepath.Join(os.TempDir(), "gitea-"+pr.BaseRepo.Name+"-"+strconv.Itoa(time.Now().Nanosecond()))
  417. defer os.Remove(indexTmpPath)
  418. headFile := fmt.Sprintf("refs/pull/%d/head", pr.Index)
  419. // Check if a pull request is merged into BaseBranch
  420. _, stderr, err := process.GetManager().ExecDirEnv(-1, "", fmt.Sprintf("isMerged (git merge-base --is-ancestor): %d", pr.BaseRepo.ID),
  421. []string{"GIT_INDEX_FILE=" + indexTmpPath, "GIT_DIR=" + pr.BaseRepo.RepoPath()},
  422. "git", "merge-base", "--is-ancestor", headFile, pr.BaseBranch)
  423. if err != nil {
  424. // Errors are signaled by a non-zero status that is not 1
  425. if err.Error() == "exit status 1" {
  426. return nil, nil
  427. }
  428. return nil, fmt.Errorf("git merge-base --is-ancestor: %v %v", stderr, err)
  429. }
  430. // We can ignore this error since we only get here when there's a valid commit in headFile
  431. commitID, _ := ioutil.ReadFile(pr.BaseRepo.RepoPath() + "/" + headFile)
  432. cmd := string(commitID)[:40] + ".." + pr.BaseBranch
  433. // Get the commit from BaseBranch where the pull request got merged
  434. mergeCommit, stderr, err := process.GetManager().ExecDirEnv(-1, "", fmt.Sprintf("isMerged (git rev-list --ancestry-path --merges --reverse): %d", pr.BaseRepo.ID),
  435. []string{"GIT_INDEX_FILE=" + indexTmpPath, "GIT_DIR=" + pr.BaseRepo.RepoPath()},
  436. "git", "rev-list", "--ancestry-path", "--merges", "--reverse", cmd)
  437. if err != nil {
  438. return nil, fmt.Errorf("git rev-list --ancestry-path --merges --reverse: %v %v", stderr, err)
  439. }
  440. gitRepo, err := git.OpenRepository(pr.BaseRepo.RepoPath())
  441. if err != nil {
  442. return nil, fmt.Errorf("OpenRepository: %v", err)
  443. }
  444. commit, err := gitRepo.GetCommit(mergeCommit[:40])
  445. if err != nil {
  446. return nil, fmt.Errorf("GetCommit: %v", err)
  447. }
  448. return commit, nil
  449. }
  450. // patchConflicts is a list of conflict description from Git.
  451. var patchConflicts = []string{
  452. "patch does not apply",
  453. "already exists in working directory",
  454. "unrecognized input",
  455. "error:",
  456. }
  457. // testPatch checks if patch can be merged to base repository without conflict.
  458. func (pr *PullRequest) testPatch() (err error) {
  459. if pr.BaseRepo == nil {
  460. pr.BaseRepo, err = GetRepositoryByID(pr.BaseRepoID)
  461. if err != nil {
  462. return fmt.Errorf("GetRepositoryByID: %v", err)
  463. }
  464. }
  465. patchPath, err := pr.BaseRepo.PatchPath(pr.Index)
  466. if err != nil {
  467. return fmt.Errorf("BaseRepo.PatchPath: %v", err)
  468. }
  469. // Fast fail if patch does not exist, this assumes data is corrupted.
  470. if !com.IsFile(patchPath) {
  471. log.Trace("PullRequest[%d].testPatch: ignored corrupted data", pr.ID)
  472. return nil
  473. }
  474. repoWorkingPool.CheckIn(com.ToStr(pr.BaseRepoID))
  475. defer repoWorkingPool.CheckOut(com.ToStr(pr.BaseRepoID))
  476. log.Trace("PullRequest[%d].testPatch (patchPath): %s", pr.ID, patchPath)
  477. pr.Status = PullRequestStatusChecking
  478. indexTmpPath := filepath.Join(os.TempDir(), "gitea-"+pr.BaseRepo.Name+"-"+strconv.Itoa(time.Now().Nanosecond()))
  479. defer os.Remove(indexTmpPath)
  480. var stderr string
  481. _, stderr, err = process.GetManager().ExecDirEnv(-1, "", fmt.Sprintf("testPatch (git read-tree): %d", pr.BaseRepo.ID),
  482. []string{"GIT_DIR=" + pr.BaseRepo.RepoPath(), "GIT_INDEX_FILE=" + indexTmpPath},
  483. "git", "read-tree", pr.BaseBranch)
  484. if err != nil {
  485. return fmt.Errorf("git read-tree --index-output=%s %s: %v - %s", indexTmpPath, pr.BaseBranch, err, stderr)
  486. }
  487. _, stderr, err = process.GetManager().ExecDirEnv(-1, "", fmt.Sprintf("testPatch (git apply --check): %d", pr.BaseRepo.ID),
  488. []string{"GIT_INDEX_FILE=" + indexTmpPath, "GIT_DIR=" + pr.BaseRepo.RepoPath()},
  489. "git", "apply", "--check", "--cached", patchPath)
  490. if err != nil {
  491. for i := range patchConflicts {
  492. if strings.Contains(stderr, patchConflicts[i]) {
  493. log.Trace("PullRequest[%d].testPatch (apply): has conflict", pr.ID)
  494. fmt.Println(stderr)
  495. pr.Status = PullRequestStatusConflict
  496. return nil
  497. }
  498. }
  499. return fmt.Errorf("git apply --check: %v - %s", err, stderr)
  500. }
  501. return nil
  502. }
  503. // NewPullRequest creates new pull request with labels for repository.
  504. func NewPullRequest(repo *Repository, pull *Issue, labelIDs []int64, uuids []string, pr *PullRequest, patch []byte) (err error) {
  505. sess := x.NewSession()
  506. defer sessionRelease(sess)
  507. if err = sess.Begin(); err != nil {
  508. return err
  509. }
  510. if err = newIssue(sess, pull.Poster, NewIssueOptions{
  511. Repo: repo,
  512. Issue: pull,
  513. LableIDs: labelIDs,
  514. Attachments: uuids,
  515. IsPull: true,
  516. }); err != nil {
  517. return fmt.Errorf("newIssue: %v", err)
  518. }
  519. pr.Index = pull.Index
  520. if err = repo.SavePatch(pr.Index, patch); err != nil {
  521. return fmt.Errorf("SavePatch: %v", err)
  522. }
  523. pr.BaseRepo = repo
  524. if err = pr.testPatch(); err != nil {
  525. return fmt.Errorf("testPatch: %v", err)
  526. }
  527. // No conflict appears after test means mergeable.
  528. if pr.Status == PullRequestStatusChecking {
  529. pr.Status = PullRequestStatusMergeable
  530. }
  531. pr.IssueID = pull.ID
  532. if _, err = sess.Insert(pr); err != nil {
  533. return fmt.Errorf("insert pull repo: %v", err)
  534. }
  535. if err = sess.Commit(); err != nil {
  536. return fmt.Errorf("Commit: %v", err)
  537. }
  538. if err = NotifyWatchers(&Action{
  539. ActUserID: pull.Poster.ID,
  540. ActUserName: pull.Poster.Name,
  541. OpType: ActionCreatePullRequest,
  542. Content: fmt.Sprintf("%d|%s", pull.Index, pull.Title),
  543. RepoID: repo.ID,
  544. RepoUserName: repo.Owner.Name,
  545. RepoName: repo.Name,
  546. IsPrivate: repo.IsPrivate,
  547. }); err != nil {
  548. log.Error(4, "NotifyWatchers: %v", err)
  549. } else if err = pull.MailParticipants(); err != nil {
  550. log.Error(4, "MailParticipants: %v", err)
  551. }
  552. pr.Issue = pull
  553. pull.PullRequest = pr
  554. if err = PrepareWebhooks(repo, HookEventPullRequest, &api.PullRequestPayload{
  555. Action: api.HookIssueOpened,
  556. Index: pull.Index,
  557. PullRequest: pr.APIFormat(),
  558. Repository: repo.APIFormat(AccessModeNone),
  559. Sender: pull.Poster.APIFormat(),
  560. }); err != nil {
  561. log.Error(4, "PrepareWebhooks: %v", err)
  562. }
  563. go HookQueue.Add(repo.ID)
  564. return nil
  565. }
  566. // PullRequestsOptions holds the options for PRs
  567. type PullRequestsOptions struct {
  568. Page int
  569. State string
  570. SortType string
  571. Labels []string
  572. MilestoneID int64
  573. }
  574. func listPullRequestStatement(baseRepoID int64, opts *PullRequestsOptions) (*xorm.Session, error) {
  575. sess := x.Where("pull_request.base_repo_id=?", baseRepoID)
  576. sess.Join("INNER", "issue", "pull_request.issue_id = issue.id")
  577. switch opts.State {
  578. case "closed", "open":
  579. sess.And("issue.is_closed=?", opts.State == "closed")
  580. }
  581. sortIssuesSession(sess, opts.SortType)
  582. if labelIDs, err := base.StringsToInt64s(opts.Labels); err != nil {
  583. return nil, err
  584. } else if len(labelIDs) > 0 {
  585. sess.Join("INNER", "issue_label", "issue.id = issue_label.issue_id").
  586. In("issue_label.label_id", labelIDs)
  587. }
  588. if opts.MilestoneID > 0 {
  589. sess.And("issue.milestone_id=?", opts.MilestoneID)
  590. }
  591. return sess, nil
  592. }
  593. // PullRequests returns all pull requests for a base Repo by the given conditions
  594. func PullRequests(baseRepoID int64, opts *PullRequestsOptions) ([]*PullRequest, int64, error) {
  595. if opts.Page <= 0 {
  596. opts.Page = 1
  597. }
  598. countSession, err := listPullRequestStatement(baseRepoID, opts)
  599. if err != nil {
  600. log.Error(4, "listPullRequestStatement", err)
  601. return nil, 0, err
  602. }
  603. maxResults, err := countSession.Count(new(PullRequest))
  604. if err != nil {
  605. log.Error(4, "Count PRs", err)
  606. return nil, maxResults, err
  607. }
  608. prs := make([]*PullRequest, 0, ItemsPerPage)
  609. findSession, err := listPullRequestStatement(baseRepoID, opts)
  610. if err != nil {
  611. log.Error(4, "listPullRequestStatement", err)
  612. return nil, maxResults, err
  613. }
  614. findSession.Limit(ItemsPerPage, (opts.Page-1)*ItemsPerPage)
  615. return prs, maxResults, findSession.Find(&prs)
  616. }
  617. // GetUnmergedPullRequest returns a pull request that is open and has not been merged
  618. // by given head/base and repo/branch.
  619. func GetUnmergedPullRequest(headRepoID, baseRepoID int64, headBranch, baseBranch string) (*PullRequest, error) {
  620. pr := new(PullRequest)
  621. has, err := x.
  622. Where("head_repo_id=? AND head_branch=? AND base_repo_id=? AND base_branch=? AND has_merged=? AND issue.is_closed=?",
  623. headRepoID, headBranch, baseRepoID, baseBranch, false, false).
  624. Join("INNER", "issue", "issue.id=pull_request.issue_id").
  625. Get(pr)
  626. if err != nil {
  627. return nil, err
  628. } else if !has {
  629. return nil, ErrPullRequestNotExist{0, 0, headRepoID, baseRepoID, headBranch, baseBranch}
  630. }
  631. return pr, nil
  632. }
  633. // GetUnmergedPullRequestsByHeadInfo returns all pull requests that are open and has not been merged
  634. // by given head information (repo and branch).
  635. func GetUnmergedPullRequestsByHeadInfo(repoID int64, branch string) ([]*PullRequest, error) {
  636. prs := make([]*PullRequest, 0, 2)
  637. return prs, x.
  638. Where("head_repo_id = ? AND head_branch = ? AND has_merged = ? AND issue.is_closed = ?",
  639. repoID, branch, false, false).
  640. Join("INNER", "issue", "issue.id = pull_request.issue_id").
  641. Find(&prs)
  642. }
  643. // GetUnmergedPullRequestsByBaseInfo returns all pull requests that are open and has not been merged
  644. // by given base information (repo and branch).
  645. func GetUnmergedPullRequestsByBaseInfo(repoID int64, branch string) ([]*PullRequest, error) {
  646. prs := make([]*PullRequest, 0, 2)
  647. return prs, x.
  648. Where("base_repo_id=? AND base_branch=? AND has_merged=? AND issue.is_closed=?",
  649. repoID, branch, false, false).
  650. Join("INNER", "issue", "issue.id=pull_request.issue_id").
  651. Find(&prs)
  652. }
  653. // GetPullRequestByIndex returns a pull request by the given index
  654. func GetPullRequestByIndex(repoID int64, index int64) (*PullRequest, error) {
  655. pr := &PullRequest{
  656. BaseRepoID: repoID,
  657. Index: index,
  658. }
  659. has, err := x.Get(pr)
  660. if err != nil {
  661. return nil, err
  662. } else if !has {
  663. return nil, ErrPullRequestNotExist{0, 0, 0, repoID, "", ""}
  664. }
  665. if err = pr.LoadAttributes(); err != nil {
  666. return nil, err
  667. }
  668. if err = pr.LoadIssue(); err != nil {
  669. return nil, err
  670. }
  671. return pr, nil
  672. }
  673. func getPullRequestByID(e Engine, id int64) (*PullRequest, error) {
  674. pr := new(PullRequest)
  675. has, err := e.Id(id).Get(pr)
  676. if err != nil {
  677. return nil, err
  678. } else if !has {
  679. return nil, ErrPullRequestNotExist{id, 0, 0, 0, "", ""}
  680. }
  681. return pr, pr.loadAttributes(e)
  682. }
  683. // GetPullRequestByID returns a pull request by given ID.
  684. func GetPullRequestByID(id int64) (*PullRequest, error) {
  685. return getPullRequestByID(x, id)
  686. }
  687. func getPullRequestByIssueID(e Engine, issueID int64) (*PullRequest, error) {
  688. pr := &PullRequest{
  689. IssueID: issueID,
  690. }
  691. has, err := e.Get(pr)
  692. if err != nil {
  693. return nil, err
  694. } else if !has {
  695. return nil, ErrPullRequestNotExist{0, issueID, 0, 0, "", ""}
  696. }
  697. return pr, pr.loadAttributes(e)
  698. }
  699. // GetPullRequestByIssueID returns pull request by given issue ID.
  700. func GetPullRequestByIssueID(issueID int64) (*PullRequest, error) {
  701. return getPullRequestByIssueID(x, issueID)
  702. }
  703. // Update updates all fields of pull request.
  704. func (pr *PullRequest) Update() error {
  705. _, err := x.Id(pr.ID).AllCols().Update(pr)
  706. return err
  707. }
  708. // UpdateCols updates specific fields of pull request.
  709. func (pr *PullRequest) UpdateCols(cols ...string) error {
  710. _, err := x.Id(pr.ID).Cols(cols...).Update(pr)
  711. return err
  712. }
  713. // UpdatePatch generates and saves a new patch.
  714. func (pr *PullRequest) UpdatePatch() (err error) {
  715. if err = pr.GetHeadRepo(); err != nil {
  716. return fmt.Errorf("GetHeadRepo: %v", err)
  717. } else if pr.HeadRepo == nil {
  718. log.Trace("PullRequest[%d].UpdatePatch: ignored cruppted data", pr.ID)
  719. return nil
  720. }
  721. if err = pr.GetBaseRepo(); err != nil {
  722. return fmt.Errorf("GetBaseRepo: %v", err)
  723. }
  724. headGitRepo, err := git.OpenRepository(pr.HeadRepo.RepoPath())
  725. if err != nil {
  726. return fmt.Errorf("OpenRepository: %v", err)
  727. }
  728. // Add a temporary remote.
  729. tmpRemote := com.ToStr(time.Now().UnixNano())
  730. if err = headGitRepo.AddRemote(tmpRemote, RepoPath(pr.BaseRepo.MustOwner().Name, pr.BaseRepo.Name), true); err != nil {
  731. return fmt.Errorf("AddRemote: %v", err)
  732. }
  733. defer func() {
  734. headGitRepo.RemoveRemote(tmpRemote)
  735. }()
  736. remoteBranch := "remotes/" + tmpRemote + "/" + pr.BaseBranch
  737. pr.MergeBase, err = headGitRepo.GetMergeBase(remoteBranch, pr.HeadBranch)
  738. if err != nil {
  739. return fmt.Errorf("GetMergeBase: %v", err)
  740. } else if err = pr.Update(); err != nil {
  741. return fmt.Errorf("Update: %v", err)
  742. }
  743. patch, err := headGitRepo.GetPatch(pr.MergeBase, pr.HeadBranch)
  744. if err != nil {
  745. return fmt.Errorf("GetPatch: %v", err)
  746. }
  747. if err = pr.BaseRepo.SavePatch(pr.Index, patch); err != nil {
  748. return fmt.Errorf("BaseRepo.SavePatch: %v", err)
  749. }
  750. return nil
  751. }
  752. // PushToBaseRepo pushes commits from branches of head repository to
  753. // corresponding branches of base repository.
  754. // FIXME: Only push branches that are actually updates?
  755. func (pr *PullRequest) PushToBaseRepo() (err error) {
  756. log.Trace("PushToBaseRepo[%d]: pushing commits to base repo 'refs/pull/%d/head'", pr.BaseRepoID, pr.Index)
  757. headRepoPath := pr.HeadRepo.RepoPath()
  758. headGitRepo, err := git.OpenRepository(headRepoPath)
  759. if err != nil {
  760. return fmt.Errorf("OpenRepository: %v", err)
  761. }
  762. tmpRemoteName := fmt.Sprintf("tmp-pull-%d", pr.ID)
  763. if err = headGitRepo.AddRemote(tmpRemoteName, pr.BaseRepo.RepoPath(), false); err != nil {
  764. return fmt.Errorf("headGitRepo.AddRemote: %v", err)
  765. }
  766. // Make sure to remove the remote even if the push fails
  767. defer headGitRepo.RemoveRemote(tmpRemoteName)
  768. headFile := fmt.Sprintf("refs/pull/%d/head", pr.Index)
  769. // Remove head in case there is a conflict.
  770. file := path.Join(pr.BaseRepo.RepoPath(), headFile)
  771. _ = os.Remove(file)
  772. if err = git.Push(headRepoPath, tmpRemoteName, fmt.Sprintf("%s:%s", pr.HeadBranch, headFile)); err != nil {
  773. return fmt.Errorf("Push: %v", err)
  774. }
  775. return nil
  776. }
  777. // AddToTaskQueue adds itself to pull request test task queue.
  778. func (pr *PullRequest) AddToTaskQueue() {
  779. go pullRequestQueue.AddFunc(pr.ID, func() {
  780. pr.Status = PullRequestStatusChecking
  781. if err := pr.UpdateCols("status"); err != nil {
  782. log.Error(5, "AddToTaskQueue.UpdateCols[%d].(add to queue): %v", pr.ID, err)
  783. }
  784. })
  785. }
  786. // PullRequestList defines a list of pull requests
  787. type PullRequestList []*PullRequest
  788. func (prs PullRequestList) loadAttributes(e Engine) error {
  789. if len(prs) == 0 {
  790. return nil
  791. }
  792. // Load issues.
  793. issueIDs := make([]int64, 0, len(prs))
  794. for i := range prs {
  795. issueIDs = append(issueIDs, prs[i].IssueID)
  796. }
  797. issues := make([]*Issue, 0, len(issueIDs))
  798. if err := e.
  799. Where("id > 0").
  800. In("id", issueIDs).
  801. Find(&issues); err != nil {
  802. return fmt.Errorf("find issues: %v", err)
  803. }
  804. set := make(map[int64]*Issue)
  805. for i := range issues {
  806. set[issues[i].ID] = issues[i]
  807. }
  808. for i := range prs {
  809. prs[i].Issue = set[prs[i].IssueID]
  810. }
  811. return nil
  812. }
  813. // LoadAttributes load all the prs attributes
  814. func (prs PullRequestList) LoadAttributes() error {
  815. return prs.loadAttributes(x)
  816. }
  817. func addHeadRepoTasks(prs []*PullRequest) {
  818. for _, pr := range prs {
  819. log.Trace("addHeadRepoTasks[%d]: composing new test task", pr.ID)
  820. if err := pr.UpdatePatch(); err != nil {
  821. log.Error(4, "UpdatePatch: %v", err)
  822. continue
  823. } else if err := pr.PushToBaseRepo(); err != nil {
  824. log.Error(4, "PushToBaseRepo: %v", err)
  825. continue
  826. }
  827. pr.AddToTaskQueue()
  828. }
  829. }
  830. // AddTestPullRequestTask adds new test tasks by given head/base repository and head/base branch,
  831. // and generate new patch for testing as needed.
  832. func AddTestPullRequestTask(doer *User, repoID int64, branch string, isSync bool) {
  833. log.Trace("AddTestPullRequestTask [head_repo_id: %d, head_branch: %s]: finding pull requests", repoID, branch)
  834. prs, err := GetUnmergedPullRequestsByHeadInfo(repoID, branch)
  835. if err != nil {
  836. log.Error(4, "Find pull requests [head_repo_id: %d, head_branch: %s]: %v", repoID, branch, err)
  837. return
  838. }
  839. if isSync {
  840. if err = PullRequestList(prs).LoadAttributes(); err != nil {
  841. log.Error(4, "PullRequestList.LoadAttributes: %v", err)
  842. }
  843. if err == nil {
  844. for _, pr := range prs {
  845. pr.Issue.PullRequest = pr
  846. if err = pr.Issue.LoadAttributes(); err != nil {
  847. log.Error(4, "LoadAttributes: %v", err)
  848. continue
  849. }
  850. if err = PrepareWebhooks(pr.Issue.Repo, HookEventPullRequest, &api.PullRequestPayload{
  851. Action: api.HookIssueSynchronized,
  852. Index: pr.Issue.Index,
  853. PullRequest: pr.Issue.PullRequest.APIFormat(),
  854. Repository: pr.Issue.Repo.APIFormat(AccessModeNone),
  855. Sender: doer.APIFormat(),
  856. }); err != nil {
  857. log.Error(4, "PrepareWebhooks [pull_id: %v]: %v", pr.ID, err)
  858. continue
  859. }
  860. go HookQueue.Add(pr.Issue.Repo.ID)
  861. }
  862. }
  863. }
  864. addHeadRepoTasks(prs)
  865. log.Trace("AddTestPullRequestTask [base_repo_id: %d, base_branch: %s]: finding pull requests", repoID, branch)
  866. prs, err = GetUnmergedPullRequestsByBaseInfo(repoID, branch)
  867. if err != nil {
  868. log.Error(4, "Find pull requests [base_repo_id: %d, base_branch: %s]: %v", repoID, branch, err)
  869. return
  870. }
  871. for _, pr := range prs {
  872. pr.AddToTaskQueue()
  873. }
  874. }
  875. // ChangeUsernameInPullRequests changes the name of head_user_name
  876. func ChangeUsernameInPullRequests(oldUserName, newUserName string) error {
  877. pr := PullRequest{
  878. HeadUserName: strings.ToLower(newUserName),
  879. }
  880. _, err := x.
  881. Cols("head_user_name").
  882. Where("head_user_name = ?", strings.ToLower(oldUserName)).
  883. Update(pr)
  884. return err
  885. }
  886. // checkAndUpdateStatus checks if pull request is possible to leaving checking status,
  887. // and set to be either conflict or mergeable.
  888. func (pr *PullRequest) checkAndUpdateStatus() {
  889. // Status is not changed to conflict means mergeable.
  890. if pr.Status == PullRequestStatusChecking {
  891. pr.Status = PullRequestStatusMergeable
  892. }
  893. // Make sure there is no waiting test to process before leaving the checking status.
  894. if !pullRequestQueue.Exist(pr.ID) {
  895. if err := pr.UpdateCols("status"); err != nil {
  896. log.Error(4, "Update[%d]: %v", pr.ID, err)
  897. }
  898. }
  899. }
  900. // TestPullRequests checks and tests untested patches of pull requests.
  901. // TODO: test more pull requests at same time.
  902. func TestPullRequests() {
  903. prs := make([]*PullRequest, 0, 10)
  904. x.Iterate(PullRequest{
  905. Status: PullRequestStatusChecking,
  906. },
  907. func(idx int, bean interface{}) error {
  908. pr := bean.(*PullRequest)
  909. if err := pr.GetBaseRepo(); err != nil {
  910. log.Error(3, "GetBaseRepo: %v", err)
  911. return nil
  912. }
  913. if pr.manuallyMerged() {
  914. return nil
  915. }
  916. if err := pr.testPatch(); err != nil {
  917. log.Error(3, "testPatch: %v", err)
  918. return nil
  919. }
  920. prs = append(prs, pr)
  921. return nil
  922. })
  923. // Update pull request status.
  924. for _, pr := range prs {
  925. pr.checkAndUpdateStatus()
  926. }
  927. // Start listening on new test requests.
  928. for prID := range pullRequestQueue.Queue() {
  929. log.Trace("TestPullRequests[%v]: processing test task", prID)
  930. pullRequestQueue.Remove(prID)
  931. pr, err := GetPullRequestByID(com.StrTo(prID).MustInt64())
  932. if err != nil {
  933. log.Error(4, "GetPullRequestByID[%s]: %v", prID, err)
  934. continue
  935. } else if pr.manuallyMerged() {
  936. continue
  937. } else if err = pr.testPatch(); err != nil {
  938. log.Error(4, "testPatch[%d]: %v", pr.ID, err)
  939. continue
  940. }
  941. pr.checkAndUpdateStatus()
  942. }
  943. }
  944. // InitTestPullRequests runs the task to test all the checking status pull requests
  945. func InitTestPullRequests() {
  946. go TestPullRequests()
  947. }