pull.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559
  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. "os"
  8. "path"
  9. "strings"
  10. "time"
  11. "github.com/Unknwon/com"
  12. "github.com/go-xorm/xorm"
  13. "github.com/gogits/gogs/modules/git"
  14. "github.com/gogits/gogs/modules/log"
  15. "github.com/gogits/gogs/modules/process"
  16. "github.com/gogits/gogs/modules/setting"
  17. )
  18. type PullRequestType int
  19. const (
  20. PULL_REQUEST_GOGS PullRequestType = iota
  21. PLLL_ERQUEST_GIT
  22. )
  23. type PullRequestStatus int
  24. const (
  25. PULL_REQUEST_STATUS_CONFLICT PullRequestStatus = iota
  26. PULL_REQUEST_STATUS_CHECKING
  27. PULL_REQUEST_STATUS_MERGEABLE
  28. )
  29. // PullRequest represents relation between pull request and repositories.
  30. type PullRequest struct {
  31. ID int64 `xorm:"pk autoincr"`
  32. Type PullRequestType
  33. Status PullRequestStatus
  34. IssueID int64 `xorm:"INDEX"`
  35. Issue *Issue `xorm:"-"`
  36. Index int64
  37. HeadRepoID int64
  38. HeadRepo *Repository `xorm:"-"`
  39. BaseRepoID int64
  40. BaseRepo *Repository `xorm:"-"`
  41. HeadUserName string
  42. HeadBranch string
  43. BaseBranch string
  44. MergeBase string `xorm:"VARCHAR(40)"`
  45. HasMerged bool
  46. MergedCommitID string `xorm:"VARCHAR(40)"`
  47. Merged time.Time
  48. MergerID int64
  49. Merger *User `xorm:"-"`
  50. }
  51. // Note: don't try to get Pull because will end up recursive querying.
  52. func (pr *PullRequest) AfterSet(colName string, _ xorm.Cell) {
  53. switch colName {
  54. case "merged":
  55. if !pr.HasMerged {
  56. return
  57. }
  58. pr.Merged = regulateTimeZone(pr.Merged)
  59. }
  60. }
  61. func (pr *PullRequest) getHeadRepo(e Engine) (err error) {
  62. pr.HeadRepo, err = getRepositoryByID(e, pr.HeadRepoID)
  63. if err != nil && !IsErrRepoNotExist(err) {
  64. return fmt.Errorf("getRepositoryByID(head): %v", err)
  65. }
  66. return nil
  67. }
  68. func (pr *PullRequest) GetHeadRepo() (err error) {
  69. return pr.getHeadRepo(x)
  70. }
  71. func (pr *PullRequest) GetBaseRepo() (err error) {
  72. if pr.BaseRepo != nil {
  73. return nil
  74. }
  75. pr.BaseRepo, err = GetRepositoryByID(pr.BaseRepoID)
  76. if err != nil {
  77. return fmt.Errorf("GetRepositoryByID(base): %v", err)
  78. }
  79. return nil
  80. }
  81. func (pr *PullRequest) GetMerger() (err error) {
  82. if !pr.HasMerged || pr.Merger != nil {
  83. return nil
  84. }
  85. pr.Merger, err = GetUserByID(pr.MergerID)
  86. if IsErrUserNotExist(err) {
  87. pr.MergerID = -1
  88. pr.Merger = NewFakeUser()
  89. } else if err != nil {
  90. return fmt.Errorf("GetUserByID: %v", err)
  91. }
  92. return nil
  93. }
  94. // IsChecking returns true if this pull request is still checking conflict.
  95. func (pr *PullRequest) IsChecking() bool {
  96. return pr.Status == PULL_REQUEST_STATUS_CHECKING
  97. }
  98. // CanAutoMerge returns true if this pull request can be merged automatically.
  99. func (pr *PullRequest) CanAutoMerge() bool {
  100. return pr.Status == PULL_REQUEST_STATUS_MERGEABLE
  101. }
  102. // Merge merges pull request to base repository.
  103. func (pr *PullRequest) Merge(doer *User, baseGitRepo *git.Repository) (err error) {
  104. sess := x.NewSession()
  105. defer sessionRelease(sess)
  106. if err = sess.Begin(); err != nil {
  107. return err
  108. }
  109. if err = pr.Issue.changeStatus(sess, doer, true); err != nil {
  110. return fmt.Errorf("Issue.changeStatus: %v", err)
  111. }
  112. if err = pr.getHeadRepo(sess); err != nil {
  113. return fmt.Errorf("getHeadRepo: %v", err)
  114. }
  115. headRepoPath := RepoPath(pr.HeadUserName, pr.HeadRepo.Name)
  116. headGitRepo, err := git.OpenRepository(headRepoPath)
  117. if err != nil {
  118. return fmt.Errorf("OpenRepository: %v", err)
  119. }
  120. pr.MergedCommitID, err = headGitRepo.GetCommitIdOfBranch(pr.HeadBranch)
  121. if err != nil {
  122. return fmt.Errorf("GetCommitIdOfBranch: %v", err)
  123. }
  124. if err = mergePullRequestAction(sess, doer, pr.Issue.Repo, pr.Issue); err != nil {
  125. return fmt.Errorf("mergePullRequestAction: %v", err)
  126. }
  127. pr.HasMerged = true
  128. pr.Merged = time.Now()
  129. pr.MergerID = doer.Id
  130. if _, err = sess.Id(pr.ID).AllCols().Update(pr); err != nil {
  131. return fmt.Errorf("update pull request: %v", err)
  132. }
  133. // Clone base repo.
  134. tmpBasePath := path.Join(setting.AppDataPath, "tmp/repos", com.ToStr(time.Now().Nanosecond())+".git")
  135. os.MkdirAll(path.Dir(tmpBasePath), os.ModePerm)
  136. defer os.RemoveAll(path.Dir(tmpBasePath))
  137. var stderr string
  138. if _, stderr, err = process.ExecTimeout(5*time.Minute,
  139. fmt.Sprintf("PullRequest.Merge (git clone): %s", tmpBasePath),
  140. "git", "clone", baseGitRepo.Path, tmpBasePath); err != nil {
  141. return fmt.Errorf("git clone: %s", stderr)
  142. }
  143. // Check out base branch.
  144. if _, stderr, err = process.ExecDir(-1, tmpBasePath,
  145. fmt.Sprintf("PullRequest.Merge (git checkout): %s", tmpBasePath),
  146. "git", "checkout", pr.BaseBranch); err != nil {
  147. return fmt.Errorf("git checkout: %s", stderr)
  148. }
  149. // Add head repo remote.
  150. if _, stderr, err = process.ExecDir(-1, tmpBasePath,
  151. fmt.Sprintf("PullRequest.Merge (git remote add): %s", tmpBasePath),
  152. "git", "remote", "add", "head_repo", headRepoPath); err != nil {
  153. return fmt.Errorf("git remote add [%s -> %s]: %s", headRepoPath, tmpBasePath, stderr)
  154. }
  155. // Merge commits.
  156. if _, stderr, err = process.ExecDir(-1, tmpBasePath,
  157. fmt.Sprintf("PullRequest.Merge (git fetch): %s", tmpBasePath),
  158. "git", "fetch", "head_repo"); err != nil {
  159. return fmt.Errorf("git fetch [%s -> %s]: %s", headRepoPath, tmpBasePath, stderr)
  160. }
  161. if _, stderr, err = process.ExecDir(-1, tmpBasePath,
  162. fmt.Sprintf("PullRequest.Merge (git merge --no-ff --no-commit): %s", tmpBasePath),
  163. "git", "merge", "--no-ff", "--no-commit", "head_repo/"+pr.HeadBranch); err != nil {
  164. return fmt.Errorf("git merge --no-ff --no-commit [%s]: %v - %s", tmpBasePath, err, stderr)
  165. }
  166. sig := doer.NewGitSig()
  167. if _, stderr, err = process.ExecDir(-1, tmpBasePath,
  168. fmt.Sprintf("PullRequest.Merge (git merge): %s", tmpBasePath),
  169. "git", "commit", fmt.Sprintf("--author='%s <%s>'", sig.Name, sig.Email),
  170. "-m", fmt.Sprintf("Merge branch '%s' of %s/%s into %s", pr.HeadBranch, pr.HeadUserName, pr.HeadRepo.Name, pr.BaseBranch)); err != nil {
  171. return fmt.Errorf("git commit [%s]: %v - %s", tmpBasePath, err, stderr)
  172. }
  173. // Push back to upstream.
  174. if _, stderr, err = process.ExecDir(-1, tmpBasePath,
  175. fmt.Sprintf("PullRequest.Merge (git push): %s", tmpBasePath),
  176. "git", "push", baseGitRepo.Path, pr.BaseBranch); err != nil {
  177. return fmt.Errorf("git push: %s", stderr)
  178. }
  179. return sess.Commit()
  180. }
  181. // patchConflicts is a list of conflit description from Git.
  182. var patchConflicts = []string{
  183. "patch does not apply",
  184. "already exists in working directory",
  185. "unrecognized input",
  186. }
  187. // testPatch checks if patch can be merged to base repository without conflit.
  188. // FIXME: make a mechanism to clean up stable local copies.
  189. func (pr *PullRequest) testPatch() (err error) {
  190. if pr.BaseRepo == nil {
  191. pr.BaseRepo, err = GetRepositoryByID(pr.BaseRepoID)
  192. if err != nil {
  193. return fmt.Errorf("GetRepositoryByID: %v", err)
  194. }
  195. }
  196. patchPath, err := pr.BaseRepo.PatchPath(pr.Index)
  197. if err != nil {
  198. return fmt.Errorf("BaseRepo.PatchPath: %v", err)
  199. }
  200. // Fast fail if patch does not exist, this assumes data is cruppted.
  201. if !com.IsFile(patchPath) {
  202. log.Trace("PullRequest[%d].testPatch: ignored cruppted data", pr.ID)
  203. return nil
  204. }
  205. log.Trace("PullRequest[%d].testPatch(patchPath): %s", pr.ID, patchPath)
  206. if err := pr.BaseRepo.UpdateLocalCopy(); err != nil {
  207. return fmt.Errorf("UpdateLocalCopy: %v", err)
  208. }
  209. // Checkout base branch.
  210. _, stderr, err := process.ExecDir(-1, pr.BaseRepo.LocalCopyPath(),
  211. fmt.Sprintf("PullRequest.Merge(git checkout): %v", pr.BaseRepo.ID),
  212. "git", "checkout", pr.BaseBranch)
  213. if err != nil {
  214. return fmt.Errorf("git checkout: %s", stderr)
  215. }
  216. pr.Status = PULL_REQUEST_STATUS_CHECKING
  217. _, stderr, err = process.ExecDir(-1, pr.BaseRepo.LocalCopyPath(),
  218. fmt.Sprintf("testPatch(git apply --check): %d", pr.BaseRepo.ID),
  219. "git", "apply", "--check", patchPath)
  220. if err != nil {
  221. for i := range patchConflicts {
  222. if strings.Contains(stderr, patchConflicts[i]) {
  223. log.Trace("PullRequest[%d].testPatch(apply): has conflit", pr.ID)
  224. fmt.Println(stderr)
  225. pr.Status = PULL_REQUEST_STATUS_CONFLICT
  226. return nil
  227. }
  228. }
  229. return fmt.Errorf("git apply --check: %v - %s", err, stderr)
  230. }
  231. return nil
  232. }
  233. // NewPullRequest creates new pull request with labels for repository.
  234. func NewPullRequest(repo *Repository, pull *Issue, labelIDs []int64, uuids []string, pr *PullRequest, patch []byte) (err error) {
  235. sess := x.NewSession()
  236. defer sessionRelease(sess)
  237. if err = sess.Begin(); err != nil {
  238. return err
  239. }
  240. if err = newIssue(sess, repo, pull, labelIDs, uuids, true); err != nil {
  241. return fmt.Errorf("newIssue: %v", err)
  242. }
  243. // Notify watchers.
  244. act := &Action{
  245. ActUserID: pull.Poster.Id,
  246. ActUserName: pull.Poster.Name,
  247. ActEmail: pull.Poster.Email,
  248. OpType: CREATE_PULL_REQUEST,
  249. Content: fmt.Sprintf("%d|%s", pull.Index, pull.Name),
  250. RepoID: repo.ID,
  251. RepoUserName: repo.Owner.Name,
  252. RepoName: repo.Name,
  253. IsPrivate: repo.IsPrivate,
  254. }
  255. if err = notifyWatchers(sess, act); err != nil {
  256. return err
  257. }
  258. pr.Index = pull.Index
  259. if err = repo.SavePatch(pr.Index, patch); err != nil {
  260. return fmt.Errorf("SavePatch: %v", err)
  261. }
  262. pr.BaseRepo = repo
  263. if err = pr.testPatch(); err != nil {
  264. return fmt.Errorf("testPatch: %v", err)
  265. }
  266. if pr.Status == PULL_REQUEST_STATUS_CHECKING {
  267. pr.Status = PULL_REQUEST_STATUS_MERGEABLE
  268. }
  269. pr.IssueID = pull.ID
  270. if _, err = sess.Insert(pr); err != nil {
  271. return fmt.Errorf("insert pull repo: %v", err)
  272. }
  273. return sess.Commit()
  274. }
  275. // GetUnmergedPullRequest returnss a pull request that is open and has not been merged
  276. // by given head/base and repo/branch.
  277. func GetUnmergedPullRequest(headRepoID, baseRepoID int64, headBranch, baseBranch string) (*PullRequest, error) {
  278. pr := new(PullRequest)
  279. has, err := x.Where("head_repo_id=? AND head_branch=? AND base_repo_id=? AND base_branch=? AND has_merged=? AND issue.is_closed=?",
  280. headRepoID, headBranch, baseRepoID, baseBranch, false, false).
  281. Join("INNER", "issue", "issue.id=pull_request.issue_id").Get(pr)
  282. if err != nil {
  283. return nil, err
  284. } else if !has {
  285. return nil, ErrPullRequestNotExist{0, 0, headRepoID, baseRepoID, headBranch, baseBranch}
  286. }
  287. return pr, nil
  288. }
  289. // GetUnmergedPullRequestsByHeadInfo returnss all pull requests that are open and has not been merged
  290. // by given head information (repo and branch).
  291. func GetUnmergedPullRequestsByHeadInfo(repoID int64, branch string) ([]*PullRequest, error) {
  292. prs := make([]*PullRequest, 0, 2)
  293. return prs, x.Where("head_repo_id=? AND head_branch=? AND has_merged=? AND issue.is_closed=?",
  294. repoID, branch, false, false).
  295. Join("INNER", "issue", "issue.id=pull_request.issue_id").Find(&prs)
  296. }
  297. // GetUnmergedPullRequestsByBaseInfo returnss all pull requests that are open and has not been merged
  298. // by given base information (repo and branch).
  299. func GetUnmergedPullRequestsByBaseInfo(repoID int64, branch string) ([]*PullRequest, error) {
  300. prs := make([]*PullRequest, 0, 2)
  301. return prs, x.Where("base_repo_id=? AND base_branch=? AND has_merged=? AND issue.is_closed=?",
  302. repoID, branch, false, false).
  303. Join("INNER", "issue", "issue.id=pull_request.issue_id").Find(&prs)
  304. }
  305. // GetPullRequestByID returns a pull request by given ID.
  306. func GetPullRequestByID(id int64) (*PullRequest, error) {
  307. pr := new(PullRequest)
  308. has, err := x.Id(id).Get(pr)
  309. if err != nil {
  310. return nil, err
  311. } else if !has {
  312. return nil, ErrPullRequestNotExist{id, 0, 0, 0, "", ""}
  313. }
  314. return pr, nil
  315. }
  316. // GetPullRequestByIssueID returns pull request by given issue ID.
  317. func GetPullRequestByIssueID(issueID int64) (*PullRequest, error) {
  318. pr := &PullRequest{
  319. IssueID: issueID,
  320. }
  321. has, err := x.Get(pr)
  322. if err != nil {
  323. return nil, err
  324. } else if !has {
  325. return nil, ErrPullRequestNotExist{0, issueID, 0, 0, "", ""}
  326. }
  327. return pr, nil
  328. }
  329. // Update updates all fields of pull request.
  330. func (pr *PullRequest) Update() error {
  331. _, err := x.Id(pr.ID).AllCols().Update(pr)
  332. return err
  333. }
  334. // Update updates specific fields of pull request.
  335. func (pr *PullRequest) UpdateCols(cols ...string) error {
  336. _, err := x.Id(pr.ID).Cols(cols...).Update(pr)
  337. return err
  338. }
  339. var PullRequestQueue = NewUniqueQueue(setting.Repository.PullRequestQueueLength)
  340. // UpdatePatch generates and saves a new patch.
  341. func (pr *PullRequest) UpdatePatch() (err error) {
  342. if err = pr.GetHeadRepo(); err != nil {
  343. return fmt.Errorf("GetHeadRepo: %v", err)
  344. } else if pr.HeadRepo == nil {
  345. log.Trace("PullRequest[%d].UpdatePatch: ignored cruppted data", pr.ID)
  346. return nil
  347. }
  348. if err = pr.GetBaseRepo(); err != nil {
  349. return fmt.Errorf("GetBaseRepo: %v", err)
  350. } else if err = pr.BaseRepo.GetOwner(); err != nil {
  351. return fmt.Errorf("GetOwner: %v", err)
  352. }
  353. headGitRepo, err := git.OpenRepository(pr.HeadRepo.RepoPath())
  354. if err != nil {
  355. return fmt.Errorf("OpenRepository: %v", err)
  356. }
  357. // Add a temporary remote.
  358. tmpRemote := com.ToStr(time.Now().UnixNano())
  359. if err = headGitRepo.AddRemote(tmpRemote, RepoPath(pr.BaseRepo.Owner.Name, pr.BaseRepo.Name)); err != nil {
  360. return fmt.Errorf("AddRemote: %v", err)
  361. }
  362. defer func() {
  363. headGitRepo.RemoveRemote(tmpRemote)
  364. }()
  365. remoteBranch := "remotes/" + tmpRemote + "/" + pr.BaseBranch
  366. pr.MergeBase, err = headGitRepo.GetMergeBase(remoteBranch, pr.HeadBranch)
  367. if err != nil {
  368. return fmt.Errorf("GetMergeBase: %v", err)
  369. } else if err = pr.Update(); err != nil {
  370. return fmt.Errorf("Update: %v", err)
  371. }
  372. patch, err := headGitRepo.GetPatch(pr.MergeBase, pr.HeadBranch)
  373. if err != nil {
  374. return fmt.Errorf("GetPatch: %v", err)
  375. }
  376. if err = pr.BaseRepo.SavePatch(pr.Index, patch); err != nil {
  377. return fmt.Errorf("BaseRepo.SavePatch: %v", err)
  378. }
  379. return nil
  380. }
  381. // AddToTaskQueue adds itself to pull request test task queue.
  382. func (pr *PullRequest) AddToTaskQueue() {
  383. go PullRequestQueue.AddFunc(pr.ID, func() {
  384. pr.Status = PULL_REQUEST_STATUS_CHECKING
  385. if err := pr.UpdateCols("status"); err != nil {
  386. log.Error(5, "AddToTaskQueue.UpdateCols[%d].(add to queue): %v", pr.ID, err)
  387. }
  388. })
  389. }
  390. func addHeadRepoTasks(prs []*PullRequest) {
  391. for _, pr := range prs {
  392. log.Trace("addHeadRepoTasks[%d]: composing new test task", pr.ID)
  393. if err := pr.UpdatePatch(); err != nil {
  394. log.Error(4, "UpdatePatch: %v", err)
  395. continue
  396. }
  397. pr.AddToTaskQueue()
  398. }
  399. }
  400. // AddTestPullRequestTask adds new test tasks by given head/base repository and head/base branch,
  401. // and generate new patch for testing as needed.
  402. func AddTestPullRequestTask(repoID int64, branch string) {
  403. log.Trace("AddTestPullRequestTask[head_repo_id: %d, head_branch: %s]: finding pull requests", repoID, branch)
  404. prs, err := GetUnmergedPullRequestsByHeadInfo(repoID, branch)
  405. if err != nil {
  406. log.Error(4, "Find pull requests[head_repo_id: %d, head_branch: %s]: %v", repoID, branch, err)
  407. return
  408. }
  409. addHeadRepoTasks(prs)
  410. log.Trace("AddTestPullRequestTask[base_repo_id: %d, base_branch: %s]: finding pull requests", repoID, branch)
  411. prs, err = GetUnmergedPullRequestsByBaseInfo(repoID, branch)
  412. if err != nil {
  413. log.Error(4, "Find pull requests[base_repo_id: %d, base_branch: %s]: %v", repoID, branch, err)
  414. return
  415. }
  416. for _, pr := range prs {
  417. pr.AddToTaskQueue()
  418. }
  419. }
  420. // checkAndUpdateStatus checks if pull request is possible to levaing checking status,
  421. // and set to be either conflict or mergeable.
  422. func (pr *PullRequest) checkAndUpdateStatus() {
  423. // Status is not changed to conflict means mergeable.
  424. if pr.Status == PULL_REQUEST_STATUS_CHECKING {
  425. pr.Status = PULL_REQUEST_STATUS_MERGEABLE
  426. }
  427. // Make sure there is no waiting test to process before levaing the checking status.
  428. if !PullRequestQueue.Exist(pr.ID) {
  429. if err := pr.UpdateCols("status"); err != nil {
  430. log.Error(4, "Update[%d]: %v", pr.ID, err)
  431. }
  432. }
  433. }
  434. // TestPullRequests checks and tests untested patches of pull requests.
  435. // TODO: test more pull requests at same time.
  436. func TestPullRequests() {
  437. prs := make([]*PullRequest, 0, 10)
  438. x.Iterate(PullRequest{
  439. Status: PULL_REQUEST_STATUS_CHECKING,
  440. },
  441. func(idx int, bean interface{}) error {
  442. pr := bean.(*PullRequest)
  443. if err := pr.GetBaseRepo(); err != nil {
  444. log.Error(3, "GetBaseRepo: %v", err)
  445. return nil
  446. }
  447. if err := pr.testPatch(); err != nil {
  448. log.Error(3, "testPatch: %v", err)
  449. return nil
  450. }
  451. prs = append(prs, pr)
  452. return nil
  453. })
  454. // Update pull request status.
  455. for _, pr := range prs {
  456. pr.checkAndUpdateStatus()
  457. }
  458. // Start listening on new test requests.
  459. for prID := range PullRequestQueue.Queue() {
  460. log.Trace("TestPullRequests[%v]: processing test task", prID)
  461. PullRequestQueue.Remove(prID)
  462. pr, err := GetPullRequestByID(com.StrTo(prID).MustInt64())
  463. if err != nil {
  464. log.Error(4, "GetPullRequestByID[%d]: %v", prID, err)
  465. continue
  466. } else if err = pr.testPatch(); err != nil {
  467. log.Error(4, "testPatch[%d]: %v", pr.ID, err)
  468. continue
  469. }
  470. pr.checkAndUpdateStatus()
  471. }
  472. }
  473. func InitTestPullRequests() {
  474. go TestPullRequests()
  475. }