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

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