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.

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