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 19KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722
  1. // Copyright 2016 The Gitea 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 repo
  5. import (
  6. "fmt"
  7. "net/http"
  8. "strings"
  9. "code.gitea.io/gitea/models"
  10. "code.gitea.io/gitea/modules/auth"
  11. "code.gitea.io/gitea/modules/context"
  12. "code.gitea.io/gitea/modules/git"
  13. "code.gitea.io/gitea/modules/log"
  14. "code.gitea.io/gitea/modules/notification"
  15. api "code.gitea.io/gitea/modules/structs"
  16. "code.gitea.io/gitea/modules/util"
  17. )
  18. // ListPullRequests returns a list of all PRs
  19. func ListPullRequests(ctx *context.APIContext, form api.ListPullRequestsOptions) {
  20. // swagger:operation GET /repos/{owner}/{repo}/pulls repository repoListPullRequests
  21. // ---
  22. // summary: List a repo's pull requests
  23. // produces:
  24. // - application/json
  25. // parameters:
  26. // - name: owner
  27. // in: path
  28. // description: owner of the repo
  29. // type: string
  30. // required: true
  31. // - name: repo
  32. // in: path
  33. // description: name of the repo
  34. // type: string
  35. // required: true
  36. // - name: page
  37. // in: query
  38. // description: Page number
  39. // type: integer
  40. // - name: state
  41. // in: query
  42. // description: "State of pull request: open or closed (optional)"
  43. // type: string
  44. // enum: [closed, open, all]
  45. // - name: sort
  46. // in: query
  47. // description: "Type of sort"
  48. // type: string
  49. // enum: [oldest, recentupdate, leastupdate, mostcomment, leastcomment, priority]
  50. // - name: milestone
  51. // in: query
  52. // description: "ID of the milestone"
  53. // type: integer
  54. // format: int64
  55. // - name: labels
  56. // in: query
  57. // description: "Label IDs"
  58. // type: array
  59. // collectionFormat: multi
  60. // items:
  61. // type: integer
  62. // format: int64
  63. // responses:
  64. // "200":
  65. // "$ref": "#/responses/PullRequestList"
  66. prs, maxResults, err := models.PullRequests(ctx.Repo.Repository.ID, &models.PullRequestsOptions{
  67. Page: ctx.QueryInt("page"),
  68. State: ctx.QueryTrim("state"),
  69. SortType: ctx.QueryTrim("sort"),
  70. Labels: ctx.QueryStrings("labels"),
  71. MilestoneID: ctx.QueryInt64("milestone"),
  72. })
  73. if err != nil {
  74. ctx.Error(500, "PullRequests", err)
  75. return
  76. }
  77. apiPrs := make([]*api.PullRequest, len(prs))
  78. for i := range prs {
  79. if err = prs[i].LoadIssue(); err != nil {
  80. ctx.Error(500, "LoadIssue", err)
  81. return
  82. }
  83. if err = prs[i].LoadAttributes(); err != nil {
  84. ctx.Error(500, "LoadAttributes", err)
  85. return
  86. }
  87. if err = prs[i].GetBaseRepo(); err != nil {
  88. ctx.Error(500, "GetBaseRepo", err)
  89. return
  90. }
  91. if err = prs[i].GetHeadRepo(); err != nil {
  92. ctx.Error(500, "GetHeadRepo", err)
  93. return
  94. }
  95. apiPrs[i] = prs[i].APIFormat()
  96. }
  97. ctx.SetLinkHeader(int(maxResults), models.ItemsPerPage)
  98. ctx.JSON(200, &apiPrs)
  99. }
  100. // GetPullRequest returns a single PR based on index
  101. func GetPullRequest(ctx *context.APIContext) {
  102. // swagger:operation GET /repos/{owner}/{repo}/pulls/{index} repository repoGetPullRequest
  103. // ---
  104. // summary: Get a pull request
  105. // produces:
  106. // - application/json
  107. // parameters:
  108. // - name: owner
  109. // in: path
  110. // description: owner of the repo
  111. // type: string
  112. // required: true
  113. // - name: repo
  114. // in: path
  115. // description: name of the repo
  116. // type: string
  117. // required: true
  118. // - name: index
  119. // in: path
  120. // description: index of the pull request to get
  121. // type: integer
  122. // format: int64
  123. // required: true
  124. // responses:
  125. // "200":
  126. // "$ref": "#/responses/PullRequest"
  127. pr, err := models.GetPullRequestByIndex(ctx.Repo.Repository.ID, ctx.ParamsInt64(":index"))
  128. if err != nil {
  129. if models.IsErrPullRequestNotExist(err) {
  130. ctx.NotFound()
  131. } else {
  132. ctx.Error(500, "GetPullRequestByIndex", err)
  133. }
  134. return
  135. }
  136. if err = pr.GetBaseRepo(); err != nil {
  137. ctx.Error(500, "GetBaseRepo", err)
  138. return
  139. }
  140. if err = pr.GetHeadRepo(); err != nil {
  141. ctx.Error(500, "GetHeadRepo", err)
  142. return
  143. }
  144. ctx.JSON(200, pr.APIFormat())
  145. }
  146. // CreatePullRequest does what it says
  147. func CreatePullRequest(ctx *context.APIContext, form api.CreatePullRequestOption) {
  148. // swagger:operation POST /repos/{owner}/{repo}/pulls repository repoCreatePullRequest
  149. // ---
  150. // summary: Create a pull request
  151. // consumes:
  152. // - application/json
  153. // produces:
  154. // - application/json
  155. // parameters:
  156. // - name: owner
  157. // in: path
  158. // description: owner of the repo
  159. // type: string
  160. // required: true
  161. // - name: repo
  162. // in: path
  163. // description: name of the repo
  164. // type: string
  165. // required: true
  166. // - name: body
  167. // in: body
  168. // schema:
  169. // "$ref": "#/definitions/CreatePullRequestOption"
  170. // responses:
  171. // "201":
  172. // "$ref": "#/responses/PullRequest"
  173. var (
  174. repo = ctx.Repo.Repository
  175. labelIDs []int64
  176. assigneeID int64
  177. milestoneID int64
  178. )
  179. // Get repo/branch information
  180. headUser, headRepo, headGitRepo, prInfo, baseBranch, headBranch := parseCompareInfo(ctx, form)
  181. if ctx.Written() {
  182. return
  183. }
  184. // Check if another PR exists with the same targets
  185. existingPr, err := models.GetUnmergedPullRequest(headRepo.ID, ctx.Repo.Repository.ID, headBranch, baseBranch)
  186. if err != nil {
  187. if !models.IsErrPullRequestNotExist(err) {
  188. ctx.Error(500, "GetUnmergedPullRequest", err)
  189. return
  190. }
  191. } else {
  192. err = models.ErrPullRequestAlreadyExists{
  193. ID: existingPr.ID,
  194. IssueID: existingPr.Index,
  195. HeadRepoID: existingPr.HeadRepoID,
  196. BaseRepoID: existingPr.BaseRepoID,
  197. HeadBranch: existingPr.HeadBranch,
  198. BaseBranch: existingPr.BaseBranch,
  199. }
  200. ctx.Error(409, "GetUnmergedPullRequest", err)
  201. return
  202. }
  203. if len(form.Labels) > 0 {
  204. labels, err := models.GetLabelsInRepoByIDs(ctx.Repo.Repository.ID, form.Labels)
  205. if err != nil {
  206. ctx.Error(500, "GetLabelsInRepoByIDs", err)
  207. return
  208. }
  209. labelIDs = make([]int64, len(labels))
  210. for i := range labels {
  211. labelIDs[i] = labels[i].ID
  212. }
  213. }
  214. if form.Milestone > 0 {
  215. milestone, err := models.GetMilestoneByRepoID(ctx.Repo.Repository.ID, milestoneID)
  216. if err != nil {
  217. if models.IsErrMilestoneNotExist(err) {
  218. ctx.NotFound()
  219. } else {
  220. ctx.Error(500, "GetMilestoneByRepoID", err)
  221. }
  222. return
  223. }
  224. milestoneID = milestone.ID
  225. }
  226. patch, err := headGitRepo.GetPatch(prInfo.MergeBase, headBranch)
  227. if err != nil {
  228. ctx.Error(500, "GetPatch", err)
  229. return
  230. }
  231. var deadlineUnix util.TimeStamp
  232. if form.Deadline != nil {
  233. deadlineUnix = util.TimeStamp(form.Deadline.Unix())
  234. }
  235. maxIndex, err := models.GetMaxIndexOfIssue(repo.ID)
  236. if err != nil {
  237. ctx.ServerError("GetPatch", err)
  238. return
  239. }
  240. prIssue := &models.Issue{
  241. RepoID: repo.ID,
  242. Index: maxIndex + 1,
  243. Title: form.Title,
  244. PosterID: ctx.User.ID,
  245. Poster: ctx.User,
  246. MilestoneID: milestoneID,
  247. AssigneeID: assigneeID,
  248. IsPull: true,
  249. Content: form.Body,
  250. DeadlineUnix: deadlineUnix,
  251. }
  252. pr := &models.PullRequest{
  253. HeadRepoID: headRepo.ID,
  254. BaseRepoID: repo.ID,
  255. HeadUserName: headUser.Name,
  256. HeadBranch: headBranch,
  257. BaseBranch: baseBranch,
  258. HeadRepo: headRepo,
  259. BaseRepo: repo,
  260. MergeBase: prInfo.MergeBase,
  261. Type: models.PullRequestGitea,
  262. }
  263. // Get all assignee IDs
  264. assigneeIDs, err := models.MakeIDsFromAPIAssigneesToAdd(form.Assignee, form.Assignees)
  265. if err != nil {
  266. if models.IsErrUserNotExist(err) {
  267. ctx.Error(422, "", fmt.Sprintf("Assignee does not exist: [name: %s]", err))
  268. } else {
  269. ctx.Error(500, "AddAssigneeByName", err)
  270. }
  271. return
  272. }
  273. if err := models.NewPullRequest(repo, prIssue, labelIDs, []string{}, pr, patch, assigneeIDs); err != nil {
  274. if models.IsErrUserDoesNotHaveAccessToRepo(err) {
  275. ctx.Error(400, "UserDoesNotHaveAccessToRepo", err)
  276. return
  277. }
  278. ctx.Error(500, "NewPullRequest", err)
  279. return
  280. } else if err := pr.PushToBaseRepo(); err != nil {
  281. ctx.Error(500, "PushToBaseRepo", err)
  282. return
  283. }
  284. notification.NotifyNewPullRequest(pr)
  285. log.Trace("Pull request created: %d/%d", repo.ID, prIssue.ID)
  286. ctx.JSON(201, pr.APIFormat())
  287. }
  288. // EditPullRequest does what it says
  289. func EditPullRequest(ctx *context.APIContext, form api.EditPullRequestOption) {
  290. // swagger:operation PATCH /repos/{owner}/{repo}/pulls/{index} repository repoEditPullRequest
  291. // ---
  292. // summary: Update a pull request
  293. // consumes:
  294. // - application/json
  295. // produces:
  296. // - application/json
  297. // parameters:
  298. // - name: owner
  299. // in: path
  300. // description: owner of the repo
  301. // type: string
  302. // required: true
  303. // - name: repo
  304. // in: path
  305. // description: name of the repo
  306. // type: string
  307. // required: true
  308. // - name: index
  309. // in: path
  310. // description: index of the pull request to edit
  311. // type: integer
  312. // format: int64
  313. // required: true
  314. // - name: body
  315. // in: body
  316. // schema:
  317. // "$ref": "#/definitions/EditPullRequestOption"
  318. // responses:
  319. // "201":
  320. // "$ref": "#/responses/PullRequest"
  321. pr, err := models.GetPullRequestByIndex(ctx.Repo.Repository.ID, ctx.ParamsInt64(":index"))
  322. if err != nil {
  323. if models.IsErrPullRequestNotExist(err) {
  324. ctx.NotFound()
  325. } else {
  326. ctx.Error(500, "GetPullRequestByIndex", err)
  327. }
  328. return
  329. }
  330. pr.LoadIssue()
  331. issue := pr.Issue
  332. issue.Repo = ctx.Repo.Repository
  333. if !issue.IsPoster(ctx.User.ID) && !ctx.Repo.CanWrite(models.UnitTypePullRequests) {
  334. ctx.Status(403)
  335. return
  336. }
  337. if len(form.Title) > 0 {
  338. issue.Title = form.Title
  339. }
  340. if len(form.Body) > 0 {
  341. issue.Content = form.Body
  342. }
  343. // Update Deadline
  344. var deadlineUnix util.TimeStamp
  345. if form.Deadline != nil && !form.Deadline.IsZero() {
  346. deadlineUnix = util.TimeStamp(form.Deadline.Unix())
  347. }
  348. if err := models.UpdateIssueDeadline(issue, deadlineUnix, ctx.User); err != nil {
  349. ctx.Error(500, "UpdateIssueDeadline", err)
  350. return
  351. }
  352. // Add/delete assignees
  353. // Deleting is done the GitHub way (quote from their api documentation):
  354. // https://developer.github.com/v3/issues/#edit-an-issue
  355. // "assignees" (array): Logins for Users to assign to this issue.
  356. // Pass one or more user logins to replace the set of assignees on this Issue.
  357. // Send an empty array ([]) to clear all assignees from the Issue.
  358. if ctx.Repo.CanWrite(models.UnitTypePullRequests) && (form.Assignees != nil || len(form.Assignee) > 0) {
  359. err = models.UpdateAPIAssignee(issue, form.Assignee, form.Assignees, ctx.User)
  360. if err != nil {
  361. if models.IsErrUserNotExist(err) {
  362. ctx.Error(422, "", fmt.Sprintf("Assignee does not exist: [name: %s]", err))
  363. } else {
  364. ctx.Error(500, "UpdateAPIAssignee", err)
  365. }
  366. return
  367. }
  368. }
  369. if ctx.Repo.CanWrite(models.UnitTypePullRequests) && form.Milestone != 0 &&
  370. issue.MilestoneID != form.Milestone {
  371. oldMilestoneID := issue.MilestoneID
  372. issue.MilestoneID = form.Milestone
  373. if err = models.ChangeMilestoneAssign(issue, ctx.User, oldMilestoneID); err != nil {
  374. ctx.Error(500, "ChangeMilestoneAssign", err)
  375. return
  376. }
  377. }
  378. if ctx.Repo.CanWrite(models.UnitTypePullRequests) && form.Labels != nil {
  379. labels, err := models.GetLabelsInRepoByIDs(ctx.Repo.Repository.ID, form.Labels)
  380. if err != nil {
  381. ctx.Error(500, "GetLabelsInRepoByIDsError", err)
  382. return
  383. }
  384. if err = issue.ReplaceLabels(labels, ctx.User); err != nil {
  385. ctx.Error(500, "ReplaceLabelsError", err)
  386. return
  387. }
  388. }
  389. if err = models.UpdateIssue(issue); err != nil {
  390. ctx.Error(500, "UpdateIssue", err)
  391. return
  392. }
  393. if form.State != nil {
  394. if err = issue.ChangeStatus(ctx.User, api.StateClosed == api.StateType(*form.State)); err != nil {
  395. if models.IsErrDependenciesLeft(err) {
  396. ctx.Error(http.StatusPreconditionFailed, "DependenciesLeft", "cannot close this pull request because it still has open dependencies")
  397. return
  398. }
  399. ctx.Error(500, "ChangeStatus", err)
  400. return
  401. }
  402. notification.NotifyIssueChangeStatus(ctx.User, issue, api.StateClosed == api.StateType(*form.State))
  403. }
  404. // Refetch from database
  405. pr, err = models.GetPullRequestByIndex(ctx.Repo.Repository.ID, pr.Index)
  406. if err != nil {
  407. if models.IsErrPullRequestNotExist(err) {
  408. ctx.NotFound()
  409. } else {
  410. ctx.Error(500, "GetPullRequestByIndex", err)
  411. }
  412. return
  413. }
  414. // TODO this should be 200, not 201
  415. ctx.JSON(201, pr.APIFormat())
  416. }
  417. // IsPullRequestMerged checks if a PR exists given an index
  418. func IsPullRequestMerged(ctx *context.APIContext) {
  419. // swagger:operation GET /repos/{owner}/{repo}/pulls/{index}/merge repository repoPullRequestIsMerged
  420. // ---
  421. // summary: Check if a pull request has been merged
  422. // produces:
  423. // - application/json
  424. // parameters:
  425. // - name: owner
  426. // in: path
  427. // description: owner of the repo
  428. // type: string
  429. // required: true
  430. // - name: repo
  431. // in: path
  432. // description: name of the repo
  433. // type: string
  434. // required: true
  435. // - name: index
  436. // in: path
  437. // description: index of the pull request
  438. // type: integer
  439. // format: int64
  440. // required: true
  441. // responses:
  442. // "204":
  443. // description: pull request has been merged
  444. // "404":
  445. // description: pull request has not been merged
  446. pr, err := models.GetPullRequestByIndex(ctx.Repo.Repository.ID, ctx.ParamsInt64(":index"))
  447. if err != nil {
  448. if models.IsErrPullRequestNotExist(err) {
  449. ctx.NotFound()
  450. } else {
  451. ctx.Error(500, "GetPullRequestByIndex", err)
  452. }
  453. return
  454. }
  455. if pr.HasMerged {
  456. ctx.Status(204)
  457. }
  458. ctx.NotFound()
  459. }
  460. // MergePullRequest merges a PR given an index
  461. func MergePullRequest(ctx *context.APIContext, form auth.MergePullRequestForm) {
  462. // swagger:operation POST /repos/{owner}/{repo}/pulls/{index}/merge repository repoMergePullRequest
  463. // ---
  464. // summary: Merge a pull request
  465. // produces:
  466. // - application/json
  467. // parameters:
  468. // - name: owner
  469. // in: path
  470. // description: owner of the repo
  471. // type: string
  472. // required: true
  473. // - name: repo
  474. // in: path
  475. // description: name of the repo
  476. // type: string
  477. // required: true
  478. // - name: index
  479. // in: path
  480. // description: index of the pull request to merge
  481. // type: integer
  482. // format: int64
  483. // required: true
  484. // - name: body
  485. // in: body
  486. // schema:
  487. // $ref: "#/definitions/MergePullRequestOption"
  488. // responses:
  489. // "200":
  490. // "$ref": "#/responses/empty"
  491. // "405":
  492. // "$ref": "#/responses/empty"
  493. pr, err := models.GetPullRequestByIndex(ctx.Repo.Repository.ID, ctx.ParamsInt64(":index"))
  494. if err != nil {
  495. if models.IsErrPullRequestNotExist(err) {
  496. ctx.NotFound("GetPullRequestByIndex", err)
  497. } else {
  498. ctx.Error(500, "GetPullRequestByIndex", err)
  499. }
  500. return
  501. }
  502. if err = pr.GetHeadRepo(); err != nil {
  503. ctx.ServerError("GetHeadRepo", err)
  504. return
  505. }
  506. pr.LoadIssue()
  507. pr.Issue.Repo = ctx.Repo.Repository
  508. if ctx.IsSigned {
  509. // Update issue-user.
  510. if err = pr.Issue.ReadBy(ctx.User.ID); err != nil {
  511. ctx.Error(500, "ReadBy", err)
  512. return
  513. }
  514. }
  515. if pr.Issue.IsClosed {
  516. ctx.NotFound()
  517. return
  518. }
  519. if !pr.CanAutoMerge() || pr.HasMerged || pr.IsWorkInProgress() {
  520. ctx.Status(405)
  521. return
  522. }
  523. if len(form.Do) == 0 {
  524. form.Do = string(models.MergeStyleMerge)
  525. }
  526. message := strings.TrimSpace(form.MergeTitleField)
  527. if len(message) == 0 {
  528. if models.MergeStyle(form.Do) == models.MergeStyleMerge {
  529. message = pr.GetDefaultMergeMessage()
  530. }
  531. if models.MergeStyle(form.Do) == models.MergeStyleSquash {
  532. message = pr.GetDefaultSquashMessage()
  533. }
  534. }
  535. form.MergeMessageField = strings.TrimSpace(form.MergeMessageField)
  536. if len(form.MergeMessageField) > 0 {
  537. message += "\n\n" + form.MergeMessageField
  538. }
  539. if err := pr.Merge(ctx.User, ctx.Repo.GitRepo, models.MergeStyle(form.Do), message); err != nil {
  540. if models.IsErrInvalidMergeStyle(err) {
  541. ctx.Status(405)
  542. return
  543. }
  544. ctx.Error(500, "Merge", err)
  545. return
  546. }
  547. log.Trace("Pull request merged: %d", pr.ID)
  548. ctx.Status(200)
  549. }
  550. func parseCompareInfo(ctx *context.APIContext, form api.CreatePullRequestOption) (*models.User, *models.Repository, *git.Repository, *git.PullRequestInfo, string, string) {
  551. baseRepo := ctx.Repo.Repository
  552. // Get compared branches information
  553. // format: <base branch>...[<head repo>:]<head branch>
  554. // base<-head: master...head:feature
  555. // same repo: master...feature
  556. // TODO: Validate form first?
  557. baseBranch := form.Base
  558. var (
  559. headUser *models.User
  560. headBranch string
  561. isSameRepo bool
  562. err error
  563. )
  564. // If there is no head repository, it means pull request between same repository.
  565. headInfos := strings.Split(form.Head, ":")
  566. if len(headInfos) == 1 {
  567. isSameRepo = true
  568. headUser = ctx.Repo.Owner
  569. headBranch = headInfos[0]
  570. } else if len(headInfos) == 2 {
  571. headUser, err = models.GetUserByName(headInfos[0])
  572. if err != nil {
  573. if models.IsErrUserNotExist(err) {
  574. ctx.NotFound("GetUserByName")
  575. } else {
  576. ctx.ServerError("GetUserByName", err)
  577. }
  578. return nil, nil, nil, nil, "", ""
  579. }
  580. headBranch = headInfos[1]
  581. } else {
  582. ctx.NotFound()
  583. return nil, nil, nil, nil, "", ""
  584. }
  585. ctx.Repo.PullRequest.SameRepo = isSameRepo
  586. log.Info("Base branch: %s", baseBranch)
  587. log.Info("Repo path: %s", ctx.Repo.GitRepo.Path)
  588. // Check if base branch is valid.
  589. if !ctx.Repo.GitRepo.IsBranchExist(baseBranch) {
  590. ctx.NotFound("IsBranchExist")
  591. return nil, nil, nil, nil, "", ""
  592. }
  593. // Check if current user has fork of repository or in the same repository.
  594. headRepo, has := models.HasForkedRepo(headUser.ID, baseRepo.ID)
  595. if !has && !isSameRepo {
  596. log.Trace("parseCompareInfo[%d]: does not have fork or in same repository", baseRepo.ID)
  597. ctx.NotFound("HasForkedRepo")
  598. return nil, nil, nil, nil, "", ""
  599. }
  600. var headGitRepo *git.Repository
  601. if isSameRepo {
  602. headRepo = ctx.Repo.Repository
  603. headGitRepo = ctx.Repo.GitRepo
  604. } else {
  605. headGitRepo, err = git.OpenRepository(models.RepoPath(headUser.Name, headRepo.Name))
  606. if err != nil {
  607. ctx.Error(500, "OpenRepository", err)
  608. return nil, nil, nil, nil, "", ""
  609. }
  610. }
  611. // user should have permission to read baseRepo's codes and pulls, NOT headRepo's
  612. permBase, err := models.GetUserRepoPermission(baseRepo, ctx.User)
  613. if err != nil {
  614. ctx.ServerError("GetUserRepoPermission", err)
  615. return nil, nil, nil, nil, "", ""
  616. }
  617. if !permBase.CanReadIssuesOrPulls(true) || !permBase.CanRead(models.UnitTypeCode) {
  618. if log.IsTrace() {
  619. log.Trace("Permission Denied: User %-v cannot create/read pull requests or cannot read code in Repo %-v\nUser in baseRepo has Permissions: %-+v",
  620. ctx.User,
  621. baseRepo,
  622. permBase)
  623. }
  624. ctx.NotFound("Can't read pulls or can't read UnitTypeCode")
  625. return nil, nil, nil, nil, "", ""
  626. }
  627. // user should have permission to read headrepo's codes
  628. permHead, err := models.GetUserRepoPermission(headRepo, ctx.User)
  629. if err != nil {
  630. ctx.ServerError("GetUserRepoPermission", err)
  631. return nil, nil, nil, nil, "", ""
  632. }
  633. if !permHead.CanRead(models.UnitTypeCode) {
  634. if log.IsTrace() {
  635. log.Trace("Permission Denied: User: %-v cannot read code in Repo: %-v\nUser in headRepo has Permissions: %-+v",
  636. ctx.User,
  637. headRepo,
  638. permHead)
  639. }
  640. ctx.NotFound("Can't read headRepo UnitTypeCode")
  641. return nil, nil, nil, nil, "", ""
  642. }
  643. // Check if head branch is valid.
  644. if !headGitRepo.IsBranchExist(headBranch) {
  645. ctx.NotFound()
  646. return nil, nil, nil, nil, "", ""
  647. }
  648. prInfo, err := headGitRepo.GetPullRequestInfo(models.RepoPath(baseRepo.Owner.Name, baseRepo.Name), baseBranch, headBranch)
  649. if err != nil {
  650. ctx.Error(500, "GetPullRequestInfo", err)
  651. return nil, nil, nil, nil, "", ""
  652. }
  653. return headUser, headRepo, headGitRepo, prInfo, baseBranch, headBranch
  654. }