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.

pull.go 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  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() (err error) {
  62. pr.HeadRepo, err = GetRepositoryByID(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) GetBaseRepo() (err error) {
  69. if pr.BaseRepo != nil {
  70. return nil
  71. }
  72. pr.BaseRepo, err = GetRepositoryByID(pr.BaseRepoID)
  73. if err != nil {
  74. return fmt.Errorf("GetRepositoryByID (base): %v", err)
  75. }
  76. return nil
  77. }
  78. func (pr *PullRequest) GetMerger() (err error) {
  79. if !pr.HasMerged || pr.Merger != nil {
  80. return nil
  81. }
  82. pr.Merger, err = GetUserByID(pr.MergerID)
  83. if IsErrUserNotExist(err) {
  84. pr.MergerID = -1
  85. pr.Merger = NewFakeUser()
  86. } else if err != nil {
  87. return fmt.Errorf("GetUserByID: %v", err)
  88. }
  89. return nil
  90. }
  91. // IsChecking returns true if this pull request is still checking conflict.
  92. func (pr *PullRequest) IsChecking() bool {
  93. return pr.Status == PULL_REQUEST_STATUS_CHECKING
  94. }
  95. // CanAutoMerge returns true if this pull request can be merged automatically.
  96. func (pr *PullRequest) CanAutoMerge() bool {
  97. return pr.Status == PULL_REQUEST_STATUS_MERGEABLE
  98. }
  99. // Merge merges pull request to base repository.
  100. func (pr *PullRequest) Merge(doer *User, baseGitRepo *git.Repository) (err error) {
  101. sess := x.NewSession()
  102. defer sessionRelease(sess)
  103. if err = sess.Begin(); err != nil {
  104. return err
  105. }
  106. if err = pr.Issue.changeStatus(sess, doer, true); err != nil {
  107. return fmt.Errorf("Issue.changeStatus: %v", err)
  108. }
  109. if err = pr.GetHeadRepo(); err != nil {
  110. return fmt.Errorf("GetHeadRepo: %v", err)
  111. }
  112. headRepoPath := RepoPath(pr.HeadUserName, pr.HeadRepo.Name)
  113. headGitRepo, err := git.OpenRepository(headRepoPath)
  114. if err != nil {
  115. return fmt.Errorf("OpenRepository: %v", err)
  116. }
  117. pr.MergedCommitID, err = headGitRepo.GetCommitIdOfBranch(pr.HeadBranch)
  118. if err != nil {
  119. return fmt.Errorf("GetCommitIdOfBranch: %v", err)
  120. }
  121. if err = mergePullRequestAction(sess, doer, pr.Issue.Repo, pr.Issue); err != nil {
  122. return fmt.Errorf("mergePullRequestAction: %v", err)
  123. }
  124. pr.HasMerged = true
  125. pr.Merged = time.Now()
  126. pr.MergerID = doer.Id
  127. if _, err = sess.Id(pr.ID).AllCols().Update(pr); err != nil {
  128. return fmt.Errorf("update pull request: %v", err)
  129. }
  130. // Clone base repo.
  131. tmpBasePath := path.Join("data/tmp/repos", com.ToStr(time.Now().Nanosecond())+".git")
  132. os.MkdirAll(path.Dir(tmpBasePath), os.ModePerm)
  133. defer os.RemoveAll(path.Dir(tmpBasePath))
  134. var stderr string
  135. if _, stderr, err = process.ExecTimeout(5*time.Minute,
  136. fmt.Sprintf("PullRequest.Merge(git clone): %s", tmpBasePath),
  137. "git", "clone", baseGitRepo.Path, tmpBasePath); err != nil {
  138. return fmt.Errorf("git clone: %s", stderr)
  139. }
  140. // Check out base branch.
  141. if _, stderr, err = process.ExecDir(-1, tmpBasePath,
  142. fmt.Sprintf("PullRequest.Merge(git checkout): %s", tmpBasePath),
  143. "git", "checkout", pr.BaseBranch); err != nil {
  144. return fmt.Errorf("git checkout: %s", stderr)
  145. }
  146. // Add head repo remote.
  147. if _, stderr, err = process.ExecDir(-1, tmpBasePath,
  148. fmt.Sprintf("PullRequest.Merge(git remote add): %s", tmpBasePath),
  149. "git", "remote", "add", "head_repo", headRepoPath); err != nil {
  150. return fmt.Errorf("git remote add[%s -> %s]: %s", headRepoPath, tmpBasePath, stderr)
  151. }
  152. // Merge commits.
  153. if _, stderr, err = process.ExecDir(-1, tmpBasePath,
  154. fmt.Sprintf("PullRequest.Merge(git fetch): %s", tmpBasePath),
  155. "git", "fetch", "head_repo"); err != nil {
  156. return fmt.Errorf("git fetch[%s -> %s]: %s", headRepoPath, tmpBasePath, stderr)
  157. }
  158. if _, stderr, err = process.ExecDir(-1, tmpBasePath,
  159. fmt.Sprintf("PullRequest.Merge(git merge): %s", tmpBasePath),
  160. "git", "merge", "--no-ff", "-m",
  161. fmt.Sprintf("Merge branch '%s' of %s/%s into %s", pr.HeadBranch, pr.HeadUserName, pr.HeadRepo.Name, pr.BaseBranch),
  162. "head_repo/"+pr.HeadBranch); err != nil {
  163. return fmt.Errorf("git merge[%s]: %s", tmpBasePath, stderr)
  164. }
  165. // Push back to upstream.
  166. if _, stderr, err = process.ExecDir(-1, tmpBasePath,
  167. fmt.Sprintf("PullRequest.Merge(git push): %s", tmpBasePath),
  168. "git", "push", baseGitRepo.Path, pr.BaseBranch); err != nil {
  169. return fmt.Errorf("git push: %s", stderr)
  170. }
  171. return sess.Commit()
  172. }
  173. // testPatch checks if patch can be merged to base repository without conflit.
  174. func (pr *PullRequest) testPatch() (err error) {
  175. if pr.BaseRepo == nil {
  176. pr.BaseRepo, err = GetRepositoryByID(pr.BaseRepoID)
  177. if err != nil {
  178. return fmt.Errorf("GetRepositoryByID: %v", err)
  179. }
  180. }
  181. patchPath, err := pr.BaseRepo.PatchPath(pr.Index)
  182. if err != nil {
  183. return fmt.Errorf("BaseRepo.PatchPath: %v", err)
  184. }
  185. log.Trace("PullRequest[%d].testPatch(patchPath): %s", pr.ID, patchPath)
  186. if err := pr.BaseRepo.UpdateLocalCopy(); err != nil {
  187. return fmt.Errorf("UpdateLocalCopy: %v", err)
  188. }
  189. pr.Status = PULL_REQUEST_STATUS_CHECKING
  190. _, stderr, err := process.ExecDir(-1, pr.BaseRepo.LocalCopyPath(),
  191. fmt.Sprintf("testPatch(git apply --check): %d", pr.BaseRepo.ID),
  192. "git", "apply", "--check", patchPath)
  193. if err != nil {
  194. if strings.Contains(stderr, "patch does not apply") {
  195. log.Trace("PullRequest[%d].testPatch(apply): has conflit", pr.ID)
  196. pr.Status = PULL_REQUEST_STATUS_CONFLICT
  197. } else {
  198. return fmt.Errorf("git apply --check: %v - %s", err, stderr)
  199. }
  200. }
  201. return nil
  202. }
  203. // NewPullRequest creates new pull request with labels for repository.
  204. func NewPullRequest(repo *Repository, pull *Issue, labelIDs []int64, uuids []string, pr *PullRequest, patch []byte) (err error) {
  205. sess := x.NewSession()
  206. defer sessionRelease(sess)
  207. if err = sess.Begin(); err != nil {
  208. return err
  209. }
  210. if err = newIssue(sess, repo, pull, labelIDs, uuids, true); err != nil {
  211. return fmt.Errorf("newIssue: %v", err)
  212. }
  213. // Notify watchers.
  214. act := &Action{
  215. ActUserID: pull.Poster.Id,
  216. ActUserName: pull.Poster.Name,
  217. ActEmail: pull.Poster.Email,
  218. OpType: CREATE_PULL_REQUEST,
  219. Content: fmt.Sprintf("%d|%s", pull.Index, pull.Name),
  220. RepoID: repo.ID,
  221. RepoUserName: repo.Owner.Name,
  222. RepoName: repo.Name,
  223. IsPrivate: repo.IsPrivate,
  224. }
  225. if err = notifyWatchers(sess, act); err != nil {
  226. return err
  227. }
  228. if err = repo.SavePatch(pr.Index, patch); err != nil {
  229. return fmt.Errorf("SavePatch: %v", err)
  230. }
  231. pr.BaseRepo = repo
  232. if err = pr.testPatch(); err != nil {
  233. return fmt.Errorf("testPatch: %v", err)
  234. }
  235. if pr.Status == PULL_REQUEST_STATUS_CHECKING {
  236. pr.Status = PULL_REQUEST_STATUS_MERGEABLE
  237. }
  238. pr.IssueID = pull.ID
  239. pr.Index = pull.Index
  240. if _, err = sess.Insert(pr); err != nil {
  241. return fmt.Errorf("insert pull repo: %v", err)
  242. }
  243. return sess.Commit()
  244. }
  245. // GetUnmergedPullRequest returnss a pull request that is open and has not been merged
  246. // by given head/base and repo/branch.
  247. func GetUnmergedPullRequest(headRepoID, baseRepoID int64, headBranch, baseBranch string) (*PullRequest, error) {
  248. pr := new(PullRequest)
  249. has, err := x.Where("head_repo_id=? AND head_branch=? AND base_repo_id=? AND base_branch=? AND has_merged=? AND issue.is_closed=?",
  250. headRepoID, headBranch, baseRepoID, baseBranch, false, false).
  251. Join("INNER", "issue", "issue.id=pull_request.issue_id").Get(pr)
  252. if err != nil {
  253. return nil, err
  254. } else if !has {
  255. return nil, ErrPullRequestNotExist{0, 0, headRepoID, baseRepoID, headBranch, baseBranch}
  256. }
  257. return pr, nil
  258. }
  259. // GetUnmergedPullRequestsByHeadInfo returnss all pull requests that are open and has not been merged
  260. // by given head information (repo and branch).
  261. func GetUnmergedPullRequestsByHeadInfo(headRepoID int64, headBranch string) ([]*PullRequest, error) {
  262. prs := make([]*PullRequest, 0, 2)
  263. return prs, x.Where("head_repo_id=? AND head_branch=? AND has_merged=? AND issue.is_closed=?",
  264. headRepoID, headBranch, false, false).
  265. Join("INNER", "issue", "issue.id=pull_request.issue_id").Find(&prs)
  266. }
  267. // GetPullRequestByID returns a pull request by given ID.
  268. func GetPullRequestByID(id int64) (*PullRequest, error) {
  269. pr := new(PullRequest)
  270. has, err := x.Id(id).Get(pr)
  271. if err != nil {
  272. return nil, err
  273. } else if !has {
  274. return nil, ErrPullRequestNotExist{id, 0, 0, 0, "", ""}
  275. }
  276. return pr, nil
  277. }
  278. // GetPullRequestByIssueID returns pull request by given issue ID.
  279. func GetPullRequestByIssueID(issueID int64) (*PullRequest, error) {
  280. pr := &PullRequest{
  281. IssueID: issueID,
  282. }
  283. has, err := x.Get(pr)
  284. if err != nil {
  285. return nil, err
  286. } else if !has {
  287. return nil, ErrPullRequestNotExist{0, issueID, 0, 0, "", ""}
  288. }
  289. return pr, nil
  290. }
  291. // Update updates all fields of pull request.
  292. func (pr *PullRequest) Update() error {
  293. _, err := x.Id(pr.ID).AllCols().Update(pr)
  294. return err
  295. }
  296. // Update updates specific fields of pull request.
  297. func (pr *PullRequest) UpdateCols(cols ...string) error {
  298. _, err := x.Id(pr.ID).Cols(cols...).Update(pr)
  299. return err
  300. }
  301. var PullRequestQueue = NewUniqueQueue(setting.Repository.PullRequestQueueLength)
  302. // checkAndUpdateStatus checks if pull request is possible to levaing checking status,
  303. // and set to be either conflict or mergeable.
  304. func (pr *PullRequest) checkAndUpdateStatus() {
  305. // Status is not changed to conflict means mergeable.
  306. if pr.Status == PULL_REQUEST_STATUS_CHECKING {
  307. pr.Status = PULL_REQUEST_STATUS_MERGEABLE
  308. }
  309. // Make sure there is no waiting test to process before levaing the checking status.
  310. if !PullRequestQueue.Exist(pr.ID) {
  311. if err := pr.UpdateCols("status"); err != nil {
  312. log.Error(4, "Update[%d]: %v", pr.ID, err)
  313. }
  314. }
  315. }
  316. // AddTestPullRequestTask adds new test tasks by given head repository and head branch,
  317. // and generate new patch for testing as needed.
  318. func AddTestPullRequestTask(headRepoID int64, headBranch string) {
  319. log.Trace("AddTestPullRequestTask[head_repo_id: %d, head_branch: %s]: finding pull requests", headRepoID, headBranch)
  320. prs, err := GetUnmergedPullRequestsByHeadInfo(headRepoID, headBranch)
  321. if err != nil {
  322. log.Error(4, "Find pull requests[head_repo_id: %d, head_branch: %s]: %v", headRepoID, headBranch, err)
  323. return
  324. }
  325. for _, pr := range prs {
  326. log.Trace("AddTestPullRequestTask[%d]: composing new test task", pr.ID)
  327. if err := pr.GetHeadRepo(); err != nil {
  328. log.Error(4, "GetHeadRepo[%d]: %v", pr.ID, err)
  329. continue
  330. } else if pr.HeadRepo == nil {
  331. log.Trace("AddTestPullRequestTask[%d]: ignored cruppted data", pr.ID)
  332. continue
  333. }
  334. if err := pr.GetBaseRepo(); err != nil {
  335. log.Error(4, "GetBaseRepo[%d]: %v", pr.ID, err)
  336. continue
  337. }
  338. headRepoPath, err := pr.HeadRepo.RepoPath()
  339. if err != nil {
  340. log.Error(4, "HeadRepo.RepoPath[%d]: %v", pr.ID, err)
  341. continue
  342. }
  343. headGitRepo, err := git.OpenRepository(headRepoPath)
  344. if err != nil {
  345. log.Error(4, "OpenRepository[%d]: %v", pr.ID, err)
  346. continue
  347. }
  348. // Generate patch.
  349. patch, err := headGitRepo.GetPatch(pr.MergeBase, pr.HeadBranch)
  350. if err != nil {
  351. log.Error(4, "GetPatch[%d]: %v", pr.ID, err)
  352. continue
  353. }
  354. if err = pr.BaseRepo.SavePatch(pr.Index, patch); err != nil {
  355. log.Error(4, "BaseRepo.SavePatch[%d]: %v", pr.ID, err)
  356. continue
  357. }
  358. if !PullRequestQueue.Exist(pr.ID) {
  359. go func() {
  360. PullRequestQueue.Add(pr.ID)
  361. pr.Status = PULL_REQUEST_STATUS_CHECKING
  362. if err = pr.UpdateCols("status"); err != nil {
  363. log.Error(5, "AddTestPullRequestTask.UpdateCols[%d].(add to queue): %v", pr.ID, err)
  364. }
  365. }()
  366. }
  367. }
  368. }
  369. // TestPullRequests checks and tests untested patches of pull requests.
  370. // TODO: test more pull requests at same time.
  371. func TestPullRequests() {
  372. prs := make([]*PullRequest, 0, 10)
  373. x.Iterate(PullRequest{
  374. Status: PULL_REQUEST_STATUS_CHECKING,
  375. },
  376. func(idx int, bean interface{}) error {
  377. pr := bean.(*PullRequest)
  378. if err := pr.GetBaseRepo(); err != nil {
  379. log.Error(3, "GetBaseRepo: %v", err)
  380. return nil
  381. }
  382. if err := pr.testPatch(); err != nil {
  383. log.Error(3, "testPatch: %v", err)
  384. return nil
  385. }
  386. prs = append(prs, pr)
  387. return nil
  388. })
  389. // Update pull request status.
  390. for _, pr := range prs {
  391. pr.checkAndUpdateStatus()
  392. }
  393. // Start listening on new test requests.
  394. for prID := range PullRequestQueue.Queue() {
  395. log.Trace("TestPullRequests[%v]: processing test task", prID)
  396. PullRequestQueue.Remove(prID)
  397. pr, err := GetPullRequestByID(com.StrTo(prID).MustInt64())
  398. if err != nil {
  399. log.Error(4, "GetPullRequestByID[%d]: %v", prID, err)
  400. continue
  401. } else if err = pr.testPatch(); err != nil {
  402. log.Error(4, "testPatch[%d]: %v", pr.ID, err)
  403. continue
  404. }
  405. pr.checkAndUpdateStatus()
  406. }
  407. }
  408. func InitTestPullRequests() {
  409. go TestPullRequests()
  410. }