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.

636 lines
16 KiB

Issue due date (#3794) * Started adding deadline to ui * Implemented basic issue due date managing * Improved UI for due date managing * Added at least write access to the repo in order to modify issue due dates * Ui improvements * Added issue comments creation when adding/modifying/removing a due date * Show due date in issue list * Added api support for issue due dates * Fixed lint suggestions * Added deadline to sdk * Updated css * Added support for adding/modifiying deadlines for pull requests via api * Fixed comments not created when updating or removing a deadline * update sdk (will do properly once go-gitea/go-sdk#103 is merged) * enhanced updateIssueDeadline * Removed unnessecary Issue.DeadlineString * UI improvements * Small improvments to comment creation + ui & validation improvements * Check if an issue is overdue is now a seperate function * Updated go-sdk with govendor as it was merged * Simplified isOverdue method * removed unessecary deadline to 0 set * Update swagger definitions * Added missing return * Added an explanary comment * Improved updateIssueDeadline method so it'll only update `deadline_unix` * Small changes and improvements * no need to explicitly load the issue when updating a deadline, just use whats already there * small optimisations * Added check if a deadline was modified before updating it * Moved comment creating logic into its own function * Code cleanup for creating deadline comment * locale improvement * When modifying a deadline, the old deadline is saved with the comment * small improvments to xorm session handling when updating an issue deadline + style nitpicks * style nitpicks * Moved checking for if the user has write acces to middleware
6 years ago
Issue due date (#3794) * Started adding deadline to ui * Implemented basic issue due date managing * Improved UI for due date managing * Added at least write access to the repo in order to modify issue due dates * Ui improvements * Added issue comments creation when adding/modifying/removing a due date * Show due date in issue list * Added api support for issue due dates * Fixed lint suggestions * Added deadline to sdk * Updated css * Added support for adding/modifiying deadlines for pull requests via api * Fixed comments not created when updating or removing a deadline * update sdk (will do properly once go-gitea/go-sdk#103 is merged) * enhanced updateIssueDeadline * Removed unnessecary Issue.DeadlineString * UI improvements * Small improvments to comment creation + ui & validation improvements * Check if an issue is overdue is now a seperate function * Updated go-sdk with govendor as it was merged * Simplified isOverdue method * removed unessecary deadline to 0 set * Update swagger definitions * Added missing return * Added an explanary comment * Improved updateIssueDeadline method so it'll only update `deadline_unix` * Small changes and improvements * no need to explicitly load the issue when updating a deadline, just use whats already there * small optimisations * Added check if a deadline was modified before updating it * Moved comment creating logic into its own function * Code cleanup for creating deadline comment * locale improvement * When modifying a deadline, the old deadline is saved with the comment * small improvments to xorm session handling when updating an issue deadline + style nitpicks * style nitpicks * Moved checking for if the user has write acces to middleware
6 years ago
Issue due date (#3794) * Started adding deadline to ui * Implemented basic issue due date managing * Improved UI for due date managing * Added at least write access to the repo in order to modify issue due dates * Ui improvements * Added issue comments creation when adding/modifying/removing a due date * Show due date in issue list * Added api support for issue due dates * Fixed lint suggestions * Added deadline to sdk * Updated css * Added support for adding/modifiying deadlines for pull requests via api * Fixed comments not created when updating or removing a deadline * update sdk (will do properly once go-gitea/go-sdk#103 is merged) * enhanced updateIssueDeadline * Removed unnessecary Issue.DeadlineString * UI improvements * Small improvments to comment creation + ui & validation improvements * Check if an issue is overdue is now a seperate function * Updated go-sdk with govendor as it was merged * Simplified isOverdue method * removed unessecary deadline to 0 set * Update swagger definitions * Added missing return * Added an explanary comment * Improved updateIssueDeadline method so it'll only update `deadline_unix` * Small changes and improvements * no need to explicitly load the issue when updating a deadline, just use whats already there * small optimisations * Added check if a deadline was modified before updating it * Moved comment creating logic into its own function * Code cleanup for creating deadline comment * locale improvement * When modifying a deadline, the old deadline is saved with the comment * small improvments to xorm session handling when updating an issue deadline + style nitpicks * style nitpicks * Moved checking for if the user has write acces to middleware
6 years ago
Issue due date (#3794) * Started adding deadline to ui * Implemented basic issue due date managing * Improved UI for due date managing * Added at least write access to the repo in order to modify issue due dates * Ui improvements * Added issue comments creation when adding/modifying/removing a due date * Show due date in issue list * Added api support for issue due dates * Fixed lint suggestions * Added deadline to sdk * Updated css * Added support for adding/modifiying deadlines for pull requests via api * Fixed comments not created when updating or removing a deadline * update sdk (will do properly once go-gitea/go-sdk#103 is merged) * enhanced updateIssueDeadline * Removed unnessecary Issue.DeadlineString * UI improvements * Small improvments to comment creation + ui & validation improvements * Check if an issue is overdue is now a seperate function * Updated go-sdk with govendor as it was merged * Simplified isOverdue method * removed unessecary deadline to 0 set * Update swagger definitions * Added missing return * Added an explanary comment * Improved updateIssueDeadline method so it'll only update `deadline_unix` * Small changes and improvements * no need to explicitly load the issue when updating a deadline, just use whats already there * small optimisations * Added check if a deadline was modified before updating it * Moved comment creating logic into its own function * Code cleanup for creating deadline comment * locale improvement * When modifying a deadline, the old deadline is saved with the comment * small improvments to xorm session handling when updating an issue deadline + style nitpicks * style nitpicks * Moved checking for if the user has write acces to middleware
6 years ago
  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. "strings"
  8. "code.gitea.io/git"
  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/log"
  13. "code.gitea.io/gitea/modules/util"
  14. api "code.gitea.io/sdk/gitea"
  15. )
  16. // ListPullRequests returns a list of all PRs
  17. func ListPullRequests(ctx *context.APIContext, form api.ListPullRequestsOptions) {
  18. // swagger:operation GET /repos/{owner}/{repo}/pulls repository repoListPullRequests
  19. // ---
  20. // summary: List a repo's pull requests
  21. // produces:
  22. // - application/json
  23. // parameters:
  24. // - name: owner
  25. // in: path
  26. // description: owner of the repo
  27. // type: string
  28. // required: true
  29. // - name: repo
  30. // in: path
  31. // description: name of the repo
  32. // type: string
  33. // required: true
  34. // responses:
  35. // "200":
  36. // "$ref": "#/responses/PullRequestList"
  37. prs, maxResults, err := models.PullRequests(ctx.Repo.Repository.ID, &models.PullRequestsOptions{
  38. Page: ctx.QueryInt("page"),
  39. State: ctx.QueryTrim("state"),
  40. SortType: ctx.QueryTrim("sort"),
  41. Labels: ctx.QueryStrings("labels"),
  42. MilestoneID: ctx.QueryInt64("milestone"),
  43. })
  44. if err != nil {
  45. ctx.Error(500, "PullRequests", err)
  46. return
  47. }
  48. apiPrs := make([]*api.PullRequest, len(prs))
  49. for i := range prs {
  50. if err = prs[i].LoadIssue(); err != nil {
  51. ctx.Error(500, "LoadIssue", err)
  52. return
  53. }
  54. if err = prs[i].LoadAttributes(); err != nil {
  55. ctx.Error(500, "LoadAttributes", err)
  56. return
  57. }
  58. if err = prs[i].GetBaseRepo(); err != nil {
  59. ctx.Error(500, "GetBaseRepo", err)
  60. return
  61. }
  62. if err = prs[i].GetHeadRepo(); err != nil {
  63. ctx.Error(500, "GetHeadRepo", err)
  64. return
  65. }
  66. apiPrs[i] = prs[i].APIFormat()
  67. }
  68. ctx.SetLinkHeader(int(maxResults), models.ItemsPerPage)
  69. ctx.JSON(200, &apiPrs)
  70. }
  71. // GetPullRequest returns a single PR based on index
  72. func GetPullRequest(ctx *context.APIContext) {
  73. // swagger:operation GET /repos/{owner}/{repo}/pulls/{index} repository repoGetPullRequest
  74. // ---
  75. // summary: Get a pull request
  76. // produces:
  77. // - application/json
  78. // parameters:
  79. // - name: owner
  80. // in: path
  81. // description: owner of the repo
  82. // type: string
  83. // required: true
  84. // - name: repo
  85. // in: path
  86. // description: name of the repo
  87. // type: string
  88. // required: true
  89. // - name: index
  90. // in: path
  91. // description: index of the pull request to get
  92. // type: integer
  93. // required: true
  94. // responses:
  95. // "200":
  96. // "$ref": "#/responses/PullRequest"
  97. pr, err := models.GetPullRequestByIndex(ctx.Repo.Repository.ID, ctx.ParamsInt64(":index"))
  98. if err != nil {
  99. if models.IsErrPullRequestNotExist(err) {
  100. ctx.Status(404)
  101. } else {
  102. ctx.Error(500, "GetPullRequestByIndex", err)
  103. }
  104. return
  105. }
  106. if err = pr.GetBaseRepo(); err != nil {
  107. ctx.Error(500, "GetBaseRepo", err)
  108. return
  109. }
  110. if err = pr.GetHeadRepo(); err != nil {
  111. ctx.Error(500, "GetHeadRepo", err)
  112. return
  113. }
  114. ctx.JSON(200, pr.APIFormat())
  115. }
  116. // CreatePullRequest does what it says
  117. func CreatePullRequest(ctx *context.APIContext, form api.CreatePullRequestOption) {
  118. // swagger:operation POST /repos/{owner}/{repo}/pulls repository repoCreatePullRequest
  119. // ---
  120. // summary: Create a pull request
  121. // consumes:
  122. // - application/json
  123. // produces:
  124. // - application/json
  125. // parameters:
  126. // - name: owner
  127. // in: path
  128. // description: owner of the repo
  129. // type: string
  130. // required: true
  131. // - name: repo
  132. // in: path
  133. // description: name of the repo
  134. // type: string
  135. // required: true
  136. // - name: body
  137. // in: body
  138. // schema:
  139. // "$ref": "#/definitions/CreatePullRequestOption"
  140. // responses:
  141. // "201":
  142. // "$ref": "#/responses/PullRequest"
  143. var (
  144. repo = ctx.Repo.Repository
  145. labelIDs []int64
  146. assigneeID int64
  147. milestoneID int64
  148. )
  149. // Get repo/branch information
  150. headUser, headRepo, headGitRepo, prInfo, baseBranch, headBranch := parseCompareInfo(ctx, form)
  151. if ctx.Written() {
  152. return
  153. }
  154. // Check if another PR exists with the same targets
  155. existingPr, err := models.GetUnmergedPullRequest(headRepo.ID, ctx.Repo.Repository.ID, headBranch, baseBranch)
  156. if err != nil {
  157. if !models.IsErrPullRequestNotExist(err) {
  158. ctx.Error(500, "GetUnmergedPullRequest", err)
  159. return
  160. }
  161. } else {
  162. err = models.ErrPullRequestAlreadyExists{
  163. ID: existingPr.ID,
  164. IssueID: existingPr.Index,
  165. HeadRepoID: existingPr.HeadRepoID,
  166. BaseRepoID: existingPr.BaseRepoID,
  167. HeadBranch: existingPr.HeadBranch,
  168. BaseBranch: existingPr.BaseBranch,
  169. }
  170. ctx.Error(409, "GetUnmergedPullRequest", err)
  171. return
  172. }
  173. if len(form.Labels) > 0 {
  174. labels, err := models.GetLabelsInRepoByIDs(ctx.Repo.Repository.ID, form.Labels)
  175. if err != nil {
  176. ctx.Error(500, "GetLabelsInRepoByIDs", err)
  177. return
  178. }
  179. labelIDs = make([]int64, len(labels))
  180. for i := range labels {
  181. labelIDs[i] = labels[i].ID
  182. }
  183. }
  184. if form.Milestone > 0 {
  185. milestone, err := models.GetMilestoneByRepoID(ctx.Repo.Repository.ID, milestoneID)
  186. if err != nil {
  187. if models.IsErrMilestoneNotExist(err) {
  188. ctx.Status(404)
  189. } else {
  190. ctx.Error(500, "GetMilestoneByRepoID", err)
  191. }
  192. return
  193. }
  194. milestoneID = milestone.ID
  195. }
  196. patch, err := headGitRepo.GetPatch(prInfo.MergeBase, headBranch)
  197. if err != nil {
  198. ctx.Error(500, "GetPatch", err)
  199. return
  200. }
  201. var deadlineUnix util.TimeStamp
  202. if form.Deadline != nil {
  203. deadlineUnix = util.TimeStamp(form.Deadline.Unix())
  204. }
  205. prIssue := &models.Issue{
  206. RepoID: repo.ID,
  207. Index: repo.NextIssueIndex(),
  208. Title: form.Title,
  209. PosterID: ctx.User.ID,
  210. Poster: ctx.User,
  211. MilestoneID: milestoneID,
  212. AssigneeID: assigneeID,
  213. IsPull: true,
  214. Content: form.Body,
  215. DeadlineUnix: deadlineUnix,
  216. }
  217. pr := &models.PullRequest{
  218. HeadRepoID: headRepo.ID,
  219. BaseRepoID: repo.ID,
  220. HeadUserName: headUser.Name,
  221. HeadBranch: headBranch,
  222. BaseBranch: baseBranch,
  223. HeadRepo: headRepo,
  224. BaseRepo: repo,
  225. MergeBase: prInfo.MergeBase,
  226. Type: models.PullRequestGitea,
  227. }
  228. // Get all assignee IDs
  229. assigneeIDs, err := models.MakeIDsFromAPIAssigneesToAdd(form.Assignee, form.Assignees)
  230. if err != nil {
  231. if models.IsErrUserNotExist(err) {
  232. ctx.Error(422, "", fmt.Sprintf("Assignee does not exist: [name: %s]", err))
  233. } else {
  234. ctx.Error(500, "AddAssigneeByName", err)
  235. }
  236. return
  237. }
  238. if err := models.NewPullRequest(repo, prIssue, labelIDs, []string{}, pr, patch, assigneeIDs); err != nil {
  239. if models.IsErrUserDoesNotHaveAccessToRepo(err) {
  240. ctx.Error(400, "UserDoesNotHaveAccessToRepo", err)
  241. return
  242. }
  243. ctx.Error(500, "NewPullRequest", err)
  244. return
  245. } else if err := pr.PushToBaseRepo(); err != nil {
  246. ctx.Error(500, "PushToBaseRepo", err)
  247. return
  248. }
  249. log.Trace("Pull request created: %d/%d", repo.ID, prIssue.ID)
  250. ctx.JSON(201, pr.APIFormat())
  251. }
  252. // EditPullRequest does what it says
  253. func EditPullRequest(ctx *context.APIContext, form api.EditPullRequestOption) {
  254. // swagger:operation PATCH /repos/{owner}/{repo}/pulls/{index} repository repoEditPullRequest
  255. // ---
  256. // summary: Update a pull request
  257. // consumes:
  258. // - application/json
  259. // produces:
  260. // - application/json
  261. // parameters:
  262. // - name: owner
  263. // in: path
  264. // description: owner of the repo
  265. // type: string
  266. // required: true
  267. // - name: repo
  268. // in: path
  269. // description: name of the repo
  270. // type: string
  271. // required: true
  272. // - name: index
  273. // in: path
  274. // description: index of the pull request to edit
  275. // type: integer
  276. // required: true
  277. // - name: body
  278. // in: body
  279. // schema:
  280. // "$ref": "#/definitions/EditPullRequestOption"
  281. // responses:
  282. // "201":
  283. // "$ref": "#/responses/PullRequest"
  284. pr, err := models.GetPullRequestByIndex(ctx.Repo.Repository.ID, ctx.ParamsInt64(":index"))
  285. if err != nil {
  286. if models.IsErrPullRequestNotExist(err) {
  287. ctx.Status(404)
  288. } else {
  289. ctx.Error(500, "GetPullRequestByIndex", err)
  290. }
  291. return
  292. }
  293. pr.LoadIssue()
  294. issue := pr.Issue
  295. if !issue.IsPoster(ctx.User.ID) && !ctx.Repo.IsWriter() {
  296. ctx.Status(403)
  297. return
  298. }
  299. if len(form.Title) > 0 {
  300. issue.Title = form.Title
  301. }
  302. if len(form.Body) > 0 {
  303. issue.Content = form.Body
  304. }
  305. // Update Deadline
  306. var deadlineUnix util.TimeStamp
  307. if form.Deadline != nil && !form.Deadline.IsZero() {
  308. deadlineUnix = util.TimeStamp(form.Deadline.Unix())
  309. }
  310. if err := models.UpdateIssueDeadline(issue, deadlineUnix, ctx.User); err != nil {
  311. ctx.Error(500, "UpdateIssueDeadline", err)
  312. return
  313. }
  314. // Add/delete assignees
  315. // Deleting is done the Github way (quote from their api documentation):
  316. // https://developer.github.com/v3/issues/#edit-an-issue
  317. // "assignees" (array): Logins for Users to assign to this issue.
  318. // Pass one or more user logins to replace the set of assignees on this Issue.
  319. // Send an empty array ([]) to clear all assignees from the Issue.
  320. if ctx.Repo.IsWriter() && (form.Assignees != nil || len(form.Assignee) > 0) {
  321. err = models.UpdateAPIAssignee(issue, form.Assignee, form.Assignees, ctx.User)
  322. if err != nil {
  323. if models.IsErrUserNotExist(err) {
  324. ctx.Error(422, "", fmt.Sprintf("Assignee does not exist: [name: %s]", err))
  325. } else {
  326. ctx.Error(500, "UpdateAPIAssignee", err)
  327. }
  328. return
  329. }
  330. }
  331. if ctx.Repo.IsWriter() && form.Milestone != 0 &&
  332. issue.MilestoneID != form.Milestone {
  333. oldMilestoneID := issue.MilestoneID
  334. issue.MilestoneID = form.Milestone
  335. if err = models.ChangeMilestoneAssign(issue, ctx.User, oldMilestoneID); err != nil {
  336. ctx.Error(500, "ChangeMilestoneAssign", err)
  337. return
  338. }
  339. }
  340. if err = models.UpdateIssue(issue); err != nil {
  341. ctx.Error(500, "UpdateIssue", err)
  342. return
  343. }
  344. if form.State != nil {
  345. if err = issue.ChangeStatus(ctx.User, ctx.Repo.Repository, api.StateClosed == api.StateType(*form.State)); err != nil {
  346. ctx.Error(500, "ChangeStatus", err)
  347. return
  348. }
  349. }
  350. // Refetch from database
  351. pr, err = models.GetPullRequestByIndex(ctx.Repo.Repository.ID, pr.Index)
  352. if err != nil {
  353. if models.IsErrPullRequestNotExist(err) {
  354. ctx.Status(404)
  355. } else {
  356. ctx.Error(500, "GetPullRequestByIndex", err)
  357. }
  358. return
  359. }
  360. // TODO this should be 200, not 201
  361. ctx.JSON(201, pr.APIFormat())
  362. }
  363. // IsPullRequestMerged checks if a PR exists given an index
  364. func IsPullRequestMerged(ctx *context.APIContext) {
  365. // swagger:operation GET /repos/{owner}/{repo}/pulls/{index}/merge repository repoPullRequestIsMerged
  366. // ---
  367. // summary: Check if a pull request has been merged
  368. // produces:
  369. // - application/json
  370. // parameters:
  371. // - name: owner
  372. // in: path
  373. // description: owner of the repo
  374. // type: string
  375. // required: true
  376. // - name: repo
  377. // in: path
  378. // description: name of the repo
  379. // type: string
  380. // required: true
  381. // - name: index
  382. // in: path
  383. // description: index of the pull request
  384. // type: integer
  385. // required: true
  386. // responses:
  387. // "204":
  388. // description: pull request has been merged
  389. // schema:
  390. // "$ref": "#/responses/empty"
  391. // "404":
  392. // description: pull request has not been merged
  393. // schema:
  394. // "$ref": "#/responses/empty"
  395. pr, err := models.GetPullRequestByIndex(ctx.Repo.Repository.ID, ctx.ParamsInt64(":index"))
  396. if err != nil {
  397. if models.IsErrPullRequestNotExist(err) {
  398. ctx.Status(404)
  399. } else {
  400. ctx.Error(500, "GetPullRequestByIndex", err)
  401. }
  402. return
  403. }
  404. if pr.HasMerged {
  405. ctx.Status(204)
  406. }
  407. ctx.Status(404)
  408. }
  409. // MergePullRequest merges a PR given an index
  410. func MergePullRequest(ctx *context.APIContext, form auth.MergePullRequestForm) {
  411. // swagger:operation POST /repos/{owner}/{repo}/pulls/{index}/merge repository repoMergePullRequest
  412. // ---
  413. // summary: Merge a pull request
  414. // produces:
  415. // - application/json
  416. // parameters:
  417. // - name: owner
  418. // in: path
  419. // description: owner of the repo
  420. // type: string
  421. // required: true
  422. // - name: repo
  423. // in: path
  424. // description: name of the repo
  425. // type: string
  426. // required: true
  427. // - name: index
  428. // in: path
  429. // description: index of the pull request to merge
  430. // type: integer
  431. // required: true
  432. // responses:
  433. // "200":
  434. // "$ref": "#/responses/empty"
  435. // "405":
  436. // "$ref": "#/responses/empty"
  437. pr, err := models.GetPullRequestByIndex(ctx.Repo.Repository.ID, ctx.ParamsInt64(":index"))
  438. if err != nil {
  439. if models.IsErrPullRequestNotExist(err) {
  440. ctx.NotFound("GetPullRequestByIndex", err)
  441. } else {
  442. ctx.Error(500, "GetPullRequestByIndex", err)
  443. }
  444. return
  445. }
  446. if err = pr.GetHeadRepo(); err != nil {
  447. ctx.ServerError("GetHeadRepo", err)
  448. return
  449. }
  450. pr.LoadIssue()
  451. pr.Issue.Repo = ctx.Repo.Repository
  452. if ctx.IsSigned {
  453. // Update issue-user.
  454. if err = pr.Issue.ReadBy(ctx.User.ID); err != nil {
  455. ctx.Error(500, "ReadBy", err)
  456. return
  457. }
  458. }
  459. if pr.Issue.IsClosed {
  460. ctx.Status(404)
  461. return
  462. }
  463. if !pr.CanAutoMerge() || pr.HasMerged {
  464. ctx.Status(405)
  465. return
  466. }
  467. if len(form.Do) == 0 {
  468. form.Do = string(models.MergeStyleMerge)
  469. }
  470. message := strings.TrimSpace(form.MergeTitleField)
  471. if len(message) == 0 {
  472. if models.MergeStyle(form.Do) == models.MergeStyleMerge {
  473. message = pr.GetDefaultMergeMessage()
  474. }
  475. if models.MergeStyle(form.Do) == models.MergeStyleSquash {
  476. message = pr.GetDefaultSquashMessage()
  477. }
  478. }
  479. form.MergeMessageField = strings.TrimSpace(form.MergeMessageField)
  480. if len(form.MergeMessageField) > 0 {
  481. message += "\n\n" + form.MergeMessageField
  482. }
  483. if err := pr.Merge(ctx.User, ctx.Repo.GitRepo, models.MergeStyle(form.Do), message); err != nil {
  484. if models.IsErrInvalidMergeStyle(err) {
  485. ctx.Status(405)
  486. return
  487. }
  488. ctx.Error(500, "Merge", err)
  489. return
  490. }
  491. log.Trace("Pull request merged: %d", pr.ID)
  492. ctx.Status(200)
  493. }
  494. func parseCompareInfo(ctx *context.APIContext, form api.CreatePullRequestOption) (*models.User, *models.Repository, *git.Repository, *git.PullRequestInfo, string, string) {
  495. baseRepo := ctx.Repo.Repository
  496. // Get compared branches information
  497. // format: <base branch>...[<head repo>:]<head branch>
  498. // base<-head: master...head:feature
  499. // same repo: master...feature
  500. // TODO: Validate form first?
  501. baseBranch := form.Base
  502. var (
  503. headUser *models.User
  504. headBranch string
  505. isSameRepo bool
  506. err error
  507. )
  508. // If there is no head repository, it means pull request between same repository.
  509. headInfos := strings.Split(form.Head, ":")
  510. if len(headInfos) == 1 {
  511. isSameRepo = true
  512. headUser = ctx.Repo.Owner
  513. headBranch = headInfos[0]
  514. } else if len(headInfos) == 2 {
  515. headUser, err = models.GetUserByName(headInfos[0])
  516. if err != nil {
  517. if models.IsErrUserNotExist(err) {
  518. ctx.NotFound("GetUserByName", nil)
  519. } else {
  520. ctx.ServerError("GetUserByName", err)
  521. }
  522. return nil, nil, nil, nil, "", ""
  523. }
  524. headBranch = headInfos[1]
  525. } else {
  526. ctx.Status(404)
  527. return nil, nil, nil, nil, "", ""
  528. }
  529. ctx.Repo.PullRequest.SameRepo = isSameRepo
  530. log.Info("Base branch: %s", baseBranch)
  531. log.Info("Repo path: %s", ctx.Repo.GitRepo.Path)
  532. // Check if base branch is valid.
  533. if !ctx.Repo.GitRepo.IsBranchExist(baseBranch) {
  534. ctx.Status(404)
  535. return nil, nil, nil, nil, "", ""
  536. }
  537. // Check if current user has fork of repository or in the same repository.
  538. headRepo, has := models.HasForkedRepo(headUser.ID, baseRepo.ID)
  539. if !has && !isSameRepo {
  540. log.Trace("parseCompareInfo[%d]: does not have fork or in same repository", baseRepo.ID)
  541. ctx.Status(404)
  542. return nil, nil, nil, nil, "", ""
  543. }
  544. var headGitRepo *git.Repository
  545. if isSameRepo {
  546. headRepo = ctx.Repo.Repository
  547. headGitRepo = ctx.Repo.GitRepo
  548. } else {
  549. headGitRepo, err = git.OpenRepository(models.RepoPath(headUser.Name, headRepo.Name))
  550. if err != nil {
  551. ctx.Error(500, "OpenRepository", err)
  552. return nil, nil, nil, nil, "", ""
  553. }
  554. }
  555. if !ctx.User.IsWriterOfRepo(headRepo) && !ctx.User.IsAdmin {
  556. log.Trace("ParseCompareInfo[%d]: does not have write access or site admin", baseRepo.ID)
  557. ctx.Status(404)
  558. return nil, nil, nil, nil, "", ""
  559. }
  560. // Check if head branch is valid.
  561. if !headGitRepo.IsBranchExist(headBranch) {
  562. ctx.Status(404)
  563. return nil, nil, nil, nil, "", ""
  564. }
  565. prInfo, err := headGitRepo.GetPullRequestInfo(models.RepoPath(baseRepo.Owner.Name, baseRepo.Name), baseBranch, headBranch)
  566. if err != nil {
  567. ctx.Error(500, "GetPullRequestInfo", err)
  568. return nil, nil, nil, nil, "", ""
  569. }
  570. return headUser, headRepo, headGitRepo, prInfo, baseBranch, headBranch
  571. }