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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244
  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. "errors"
  7. "fmt"
  8. "math"
  9. "net/http"
  10. "strconv"
  11. "strings"
  12. "time"
  13. "code.gitea.io/gitea/models"
  14. "code.gitea.io/gitea/modules/context"
  15. "code.gitea.io/gitea/modules/convert"
  16. "code.gitea.io/gitea/modules/git"
  17. "code.gitea.io/gitea/modules/log"
  18. "code.gitea.io/gitea/modules/notification"
  19. api "code.gitea.io/gitea/modules/structs"
  20. "code.gitea.io/gitea/modules/timeutil"
  21. "code.gitea.io/gitea/modules/web"
  22. "code.gitea.io/gitea/routers/api/v1/utils"
  23. "code.gitea.io/gitea/services/forms"
  24. issue_service "code.gitea.io/gitea/services/issue"
  25. pull_service "code.gitea.io/gitea/services/pull"
  26. repo_service "code.gitea.io/gitea/services/repository"
  27. )
  28. // ListPullRequests returns a list of all PRs
  29. func ListPullRequests(ctx *context.APIContext) {
  30. // swagger:operation GET /repos/{owner}/{repo}/pulls repository repoListPullRequests
  31. // ---
  32. // summary: List a repo's pull requests
  33. // produces:
  34. // - application/json
  35. // parameters:
  36. // - name: owner
  37. // in: path
  38. // description: owner of the repo
  39. // type: string
  40. // required: true
  41. // - name: repo
  42. // in: path
  43. // description: name of the repo
  44. // type: string
  45. // required: true
  46. // - name: state
  47. // in: query
  48. // description: "State of pull request: open or closed (optional)"
  49. // type: string
  50. // enum: [closed, open, all]
  51. // - name: sort
  52. // in: query
  53. // description: "Type of sort"
  54. // type: string
  55. // enum: [oldest, recentupdate, leastupdate, mostcomment, leastcomment, priority]
  56. // - name: milestone
  57. // in: query
  58. // description: "ID of the milestone"
  59. // type: integer
  60. // format: int64
  61. // - name: labels
  62. // in: query
  63. // description: "Label IDs"
  64. // type: array
  65. // collectionFormat: multi
  66. // items:
  67. // type: integer
  68. // format: int64
  69. // - name: page
  70. // in: query
  71. // description: page number of results to return (1-based)
  72. // type: integer
  73. // - name: limit
  74. // in: query
  75. // description: page size of results
  76. // type: integer
  77. // responses:
  78. // "200":
  79. // "$ref": "#/responses/PullRequestList"
  80. listOptions := utils.GetListOptions(ctx)
  81. prs, maxResults, err := models.PullRequests(ctx.Repo.Repository.ID, &models.PullRequestsOptions{
  82. ListOptions: listOptions,
  83. State: ctx.FormTrim("state"),
  84. SortType: ctx.FormTrim("sort"),
  85. Labels: ctx.FormStrings("labels"),
  86. MilestoneID: ctx.FormInt64("milestone"),
  87. })
  88. if err != nil {
  89. ctx.Error(http.StatusInternalServerError, "PullRequests", err)
  90. return
  91. }
  92. apiPrs := make([]*api.PullRequest, len(prs))
  93. for i := range prs {
  94. if err = prs[i].LoadIssue(); err != nil {
  95. ctx.Error(http.StatusInternalServerError, "LoadIssue", err)
  96. return
  97. }
  98. if err = prs[i].LoadAttributes(); err != nil {
  99. ctx.Error(http.StatusInternalServerError, "LoadAttributes", err)
  100. return
  101. }
  102. if err = prs[i].LoadBaseRepo(); err != nil {
  103. ctx.Error(http.StatusInternalServerError, "LoadBaseRepo", err)
  104. return
  105. }
  106. if err = prs[i].LoadHeadRepo(); err != nil {
  107. ctx.Error(http.StatusInternalServerError, "LoadHeadRepo", err)
  108. return
  109. }
  110. apiPrs[i] = convert.ToAPIPullRequest(prs[i])
  111. }
  112. ctx.SetLinkHeader(int(maxResults), listOptions.PageSize)
  113. ctx.SetTotalCountHeader(maxResults)
  114. ctx.JSON(http.StatusOK, &apiPrs)
  115. }
  116. // GetPullRequest returns a single PR based on index
  117. func GetPullRequest(ctx *context.APIContext) {
  118. // swagger:operation GET /repos/{owner}/{repo}/pulls/{index} repository repoGetPullRequest
  119. // ---
  120. // summary: Get a pull request
  121. // produces:
  122. // - application/json
  123. // parameters:
  124. // - name: owner
  125. // in: path
  126. // description: owner of the repo
  127. // type: string
  128. // required: true
  129. // - name: repo
  130. // in: path
  131. // description: name of the repo
  132. // type: string
  133. // required: true
  134. // - name: index
  135. // in: path
  136. // description: index of the pull request to get
  137. // type: integer
  138. // format: int64
  139. // required: true
  140. // responses:
  141. // "200":
  142. // "$ref": "#/responses/PullRequest"
  143. // "404":
  144. // "$ref": "#/responses/notFound"
  145. pr, err := models.GetPullRequestByIndex(ctx.Repo.Repository.ID, ctx.ParamsInt64(":index"))
  146. if err != nil {
  147. if models.IsErrPullRequestNotExist(err) {
  148. ctx.NotFound()
  149. } else {
  150. ctx.Error(http.StatusInternalServerError, "GetPullRequestByIndex", err)
  151. }
  152. return
  153. }
  154. if err = pr.LoadBaseRepo(); err != nil {
  155. ctx.Error(http.StatusInternalServerError, "LoadBaseRepo", err)
  156. return
  157. }
  158. if err = pr.LoadHeadRepo(); err != nil {
  159. ctx.Error(http.StatusInternalServerError, "LoadHeadRepo", err)
  160. return
  161. }
  162. ctx.JSON(http.StatusOK, convert.ToAPIPullRequest(pr))
  163. }
  164. // DownloadPullDiff render a pull's raw diff
  165. func DownloadPullDiff(ctx *context.APIContext) {
  166. // swagger:operation GET /repos/{owner}/{repo}/pulls/{index}.diff repository repoDownloadPullDiff
  167. // ---
  168. // summary: Get a pull request diff
  169. // produces:
  170. // - text/plain
  171. // parameters:
  172. // - name: owner
  173. // in: path
  174. // description: owner of the repo
  175. // type: string
  176. // required: true
  177. // - name: repo
  178. // in: path
  179. // description: name of the repo
  180. // type: string
  181. // required: true
  182. // - name: index
  183. // in: path
  184. // description: index of the pull request to get
  185. // type: integer
  186. // format: int64
  187. // required: true
  188. // responses:
  189. // "200":
  190. // "$ref": "#/responses/string"
  191. // "404":
  192. // "$ref": "#/responses/notFound"
  193. DownloadPullDiffOrPatch(ctx, false)
  194. }
  195. // DownloadPullPatch render a pull's raw patch
  196. func DownloadPullPatch(ctx *context.APIContext) {
  197. // swagger:operation GET /repos/{owner}/{repo}/pulls/{index}.patch repository repoDownloadPullPatch
  198. // ---
  199. // summary: Get a pull request patch file
  200. // produces:
  201. // - text/plain
  202. // parameters:
  203. // - name: owner
  204. // in: path
  205. // description: owner of the repo
  206. // type: string
  207. // required: true
  208. // - name: repo
  209. // in: path
  210. // description: name of the repo
  211. // type: string
  212. // required: true
  213. // - name: index
  214. // in: path
  215. // description: index of the pull request to get
  216. // type: integer
  217. // format: int64
  218. // required: true
  219. // responses:
  220. // "200":
  221. // "$ref": "#/responses/string"
  222. // "404":
  223. // "$ref": "#/responses/notFound"
  224. DownloadPullDiffOrPatch(ctx, true)
  225. }
  226. // DownloadPullDiffOrPatch render a pull's raw diff or patch
  227. func DownloadPullDiffOrPatch(ctx *context.APIContext, patch bool) {
  228. pr, err := models.GetPullRequestByIndex(ctx.Repo.Repository.ID, ctx.ParamsInt64(":index"))
  229. if err != nil {
  230. if models.IsErrPullRequestNotExist(err) {
  231. ctx.NotFound()
  232. } else {
  233. ctx.InternalServerError(err)
  234. }
  235. return
  236. }
  237. if err := pull_service.DownloadDiffOrPatch(pr, ctx, patch); err != nil {
  238. ctx.InternalServerError(err)
  239. return
  240. }
  241. }
  242. // CreatePullRequest does what it says
  243. func CreatePullRequest(ctx *context.APIContext) {
  244. // swagger:operation POST /repos/{owner}/{repo}/pulls repository repoCreatePullRequest
  245. // ---
  246. // summary: Create a pull request
  247. // consumes:
  248. // - application/json
  249. // produces:
  250. // - application/json
  251. // parameters:
  252. // - name: owner
  253. // in: path
  254. // description: owner of the repo
  255. // type: string
  256. // required: true
  257. // - name: repo
  258. // in: path
  259. // description: name of the repo
  260. // type: string
  261. // required: true
  262. // - name: body
  263. // in: body
  264. // schema:
  265. // "$ref": "#/definitions/CreatePullRequestOption"
  266. // responses:
  267. // "201":
  268. // "$ref": "#/responses/PullRequest"
  269. // "409":
  270. // "$ref": "#/responses/error"
  271. // "422":
  272. // "$ref": "#/responses/validationError"
  273. form := *web.GetForm(ctx).(*api.CreatePullRequestOption)
  274. if form.Head == form.Base {
  275. ctx.Error(http.StatusUnprocessableEntity, "BaseHeadSame",
  276. "Invalid PullRequest: There are no changes between the head and the base")
  277. return
  278. }
  279. var (
  280. repo = ctx.Repo.Repository
  281. labelIDs []int64
  282. milestoneID int64
  283. )
  284. // Get repo/branch information
  285. _, headRepo, headGitRepo, compareInfo, baseBranch, headBranch := parseCompareInfo(ctx, form)
  286. if ctx.Written() {
  287. return
  288. }
  289. defer headGitRepo.Close()
  290. // Check if another PR exists with the same targets
  291. existingPr, err := models.GetUnmergedPullRequest(headRepo.ID, ctx.Repo.Repository.ID, headBranch, baseBranch, models.PullRequestFlowGithub)
  292. if err != nil {
  293. if !models.IsErrPullRequestNotExist(err) {
  294. ctx.Error(http.StatusInternalServerError, "GetUnmergedPullRequest", err)
  295. return
  296. }
  297. } else {
  298. err = models.ErrPullRequestAlreadyExists{
  299. ID: existingPr.ID,
  300. IssueID: existingPr.Index,
  301. HeadRepoID: existingPr.HeadRepoID,
  302. BaseRepoID: existingPr.BaseRepoID,
  303. HeadBranch: existingPr.HeadBranch,
  304. BaseBranch: existingPr.BaseBranch,
  305. }
  306. ctx.Error(http.StatusConflict, "GetUnmergedPullRequest", err)
  307. return
  308. }
  309. if len(form.Labels) > 0 {
  310. labels, err := models.GetLabelsInRepoByIDs(ctx.Repo.Repository.ID, form.Labels)
  311. if err != nil {
  312. ctx.Error(http.StatusInternalServerError, "GetLabelsInRepoByIDs", err)
  313. return
  314. }
  315. labelIDs = make([]int64, len(form.Labels))
  316. orgLabelIDs := make([]int64, len(form.Labels))
  317. for i := range labels {
  318. labelIDs[i] = labels[i].ID
  319. }
  320. if ctx.Repo.Owner.IsOrganization() {
  321. orgLabels, err := models.GetLabelsInOrgByIDs(ctx.Repo.Owner.ID, form.Labels)
  322. if err != nil {
  323. ctx.Error(http.StatusInternalServerError, "GetLabelsInOrgByIDs", err)
  324. return
  325. }
  326. for i := range orgLabels {
  327. orgLabelIDs[i] = orgLabels[i].ID
  328. }
  329. }
  330. labelIDs = append(labelIDs, orgLabelIDs...)
  331. }
  332. if form.Milestone > 0 {
  333. milestone, err := models.GetMilestoneByRepoID(ctx.Repo.Repository.ID, form.Milestone)
  334. if err != nil {
  335. if models.IsErrMilestoneNotExist(err) {
  336. ctx.NotFound()
  337. } else {
  338. ctx.Error(http.StatusInternalServerError, "GetMilestoneByRepoID", err)
  339. }
  340. return
  341. }
  342. milestoneID = milestone.ID
  343. }
  344. var deadlineUnix timeutil.TimeStamp
  345. if form.Deadline != nil {
  346. deadlineUnix = timeutil.TimeStamp(form.Deadline.Unix())
  347. }
  348. prIssue := &models.Issue{
  349. RepoID: repo.ID,
  350. Title: form.Title,
  351. PosterID: ctx.User.ID,
  352. Poster: ctx.User,
  353. MilestoneID: milestoneID,
  354. IsPull: true,
  355. Content: form.Body,
  356. DeadlineUnix: deadlineUnix,
  357. }
  358. pr := &models.PullRequest{
  359. HeadRepoID: headRepo.ID,
  360. BaseRepoID: repo.ID,
  361. HeadBranch: headBranch,
  362. BaseBranch: baseBranch,
  363. HeadRepo: headRepo,
  364. BaseRepo: repo,
  365. MergeBase: compareInfo.MergeBase,
  366. Type: models.PullRequestGitea,
  367. }
  368. // Get all assignee IDs
  369. assigneeIDs, err := models.MakeIDsFromAPIAssigneesToAdd(form.Assignee, form.Assignees)
  370. if err != nil {
  371. if models.IsErrUserNotExist(err) {
  372. ctx.Error(http.StatusUnprocessableEntity, "", fmt.Sprintf("Assignee does not exist: [name: %s]", err))
  373. } else {
  374. ctx.Error(http.StatusInternalServerError, "AddAssigneeByName", err)
  375. }
  376. return
  377. }
  378. // Check if the passed assignees is assignable
  379. for _, aID := range assigneeIDs {
  380. assignee, err := models.GetUserByID(aID)
  381. if err != nil {
  382. ctx.Error(http.StatusInternalServerError, "GetUserByID", err)
  383. return
  384. }
  385. valid, err := models.CanBeAssigned(assignee, repo, true)
  386. if err != nil {
  387. ctx.Error(http.StatusInternalServerError, "canBeAssigned", err)
  388. return
  389. }
  390. if !valid {
  391. ctx.Error(http.StatusUnprocessableEntity, "canBeAssigned", models.ErrUserDoesNotHaveAccessToRepo{UserID: aID, RepoName: repo.Name})
  392. return
  393. }
  394. }
  395. if err := pull_service.NewPullRequest(repo, prIssue, labelIDs, []string{}, pr, assigneeIDs); err != nil {
  396. if models.IsErrUserDoesNotHaveAccessToRepo(err) {
  397. ctx.Error(http.StatusBadRequest, "UserDoesNotHaveAccessToRepo", err)
  398. return
  399. }
  400. ctx.Error(http.StatusInternalServerError, "NewPullRequest", err)
  401. return
  402. }
  403. log.Trace("Pull request created: %d/%d", repo.ID, prIssue.ID)
  404. ctx.JSON(http.StatusCreated, convert.ToAPIPullRequest(pr))
  405. }
  406. // EditPullRequest does what it says
  407. func EditPullRequest(ctx *context.APIContext) {
  408. // swagger:operation PATCH /repos/{owner}/{repo}/pulls/{index} repository repoEditPullRequest
  409. // ---
  410. // summary: Update a pull request. If using deadline only the date will be taken into account, and time of day ignored.
  411. // consumes:
  412. // - application/json
  413. // produces:
  414. // - application/json
  415. // parameters:
  416. // - name: owner
  417. // in: path
  418. // description: owner of the repo
  419. // type: string
  420. // required: true
  421. // - name: repo
  422. // in: path
  423. // description: name of the repo
  424. // type: string
  425. // required: true
  426. // - name: index
  427. // in: path
  428. // description: index of the pull request to edit
  429. // type: integer
  430. // format: int64
  431. // required: true
  432. // - name: body
  433. // in: body
  434. // schema:
  435. // "$ref": "#/definitions/EditPullRequestOption"
  436. // responses:
  437. // "201":
  438. // "$ref": "#/responses/PullRequest"
  439. // "403":
  440. // "$ref": "#/responses/forbidden"
  441. // "409":
  442. // "$ref": "#/responses/error"
  443. // "412":
  444. // "$ref": "#/responses/error"
  445. // "422":
  446. // "$ref": "#/responses/validationError"
  447. form := web.GetForm(ctx).(*api.EditPullRequestOption)
  448. pr, err := models.GetPullRequestByIndex(ctx.Repo.Repository.ID, ctx.ParamsInt64(":index"))
  449. if err != nil {
  450. if models.IsErrPullRequestNotExist(err) {
  451. ctx.NotFound()
  452. } else {
  453. ctx.Error(http.StatusInternalServerError, "GetPullRequestByIndex", err)
  454. }
  455. return
  456. }
  457. err = pr.LoadIssue()
  458. if err != nil {
  459. ctx.Error(http.StatusInternalServerError, "LoadIssue", err)
  460. return
  461. }
  462. issue := pr.Issue
  463. issue.Repo = ctx.Repo.Repository
  464. if !issue.IsPoster(ctx.User.ID) && !ctx.Repo.CanWrite(models.UnitTypePullRequests) {
  465. ctx.Status(http.StatusForbidden)
  466. return
  467. }
  468. oldTitle := issue.Title
  469. if len(form.Title) > 0 {
  470. issue.Title = form.Title
  471. }
  472. if len(form.Body) > 0 {
  473. issue.Content = form.Body
  474. }
  475. // Update or remove deadline if set
  476. if form.Deadline != nil || form.RemoveDeadline != nil {
  477. var deadlineUnix timeutil.TimeStamp
  478. if (form.RemoveDeadline == nil || !*form.RemoveDeadline) && !form.Deadline.IsZero() {
  479. deadline := time.Date(form.Deadline.Year(), form.Deadline.Month(), form.Deadline.Day(),
  480. 23, 59, 59, 0, form.Deadline.Location())
  481. deadlineUnix = timeutil.TimeStamp(deadline.Unix())
  482. }
  483. if err := models.UpdateIssueDeadline(issue, deadlineUnix, ctx.User); err != nil {
  484. ctx.Error(http.StatusInternalServerError, "UpdateIssueDeadline", err)
  485. return
  486. }
  487. issue.DeadlineUnix = deadlineUnix
  488. }
  489. // Add/delete assignees
  490. // Deleting is done the GitHub way (quote from their api documentation):
  491. // https://developer.github.com/v3/issues/#edit-an-issue
  492. // "assignees" (array): Logins for Users to assign to this issue.
  493. // Pass one or more user logins to replace the set of assignees on this Issue.
  494. // Send an empty array ([]) to clear all assignees from the Issue.
  495. if ctx.Repo.CanWrite(models.UnitTypePullRequests) && (form.Assignees != nil || len(form.Assignee) > 0) {
  496. err = issue_service.UpdateAssignees(issue, form.Assignee, form.Assignees, ctx.User)
  497. if err != nil {
  498. if models.IsErrUserNotExist(err) {
  499. ctx.Error(http.StatusUnprocessableEntity, "", fmt.Sprintf("Assignee does not exist: [name: %s]", err))
  500. } else {
  501. ctx.Error(http.StatusInternalServerError, "UpdateAssignees", err)
  502. }
  503. return
  504. }
  505. }
  506. if ctx.Repo.CanWrite(models.UnitTypePullRequests) && form.Milestone != 0 &&
  507. issue.MilestoneID != form.Milestone {
  508. oldMilestoneID := issue.MilestoneID
  509. issue.MilestoneID = form.Milestone
  510. if err = issue_service.ChangeMilestoneAssign(issue, ctx.User, oldMilestoneID); err != nil {
  511. ctx.Error(http.StatusInternalServerError, "ChangeMilestoneAssign", err)
  512. return
  513. }
  514. }
  515. if ctx.Repo.CanWrite(models.UnitTypePullRequests) && form.Labels != nil {
  516. labels, err := models.GetLabelsInRepoByIDs(ctx.Repo.Repository.ID, form.Labels)
  517. if err != nil {
  518. ctx.Error(http.StatusInternalServerError, "GetLabelsInRepoByIDsError", err)
  519. return
  520. }
  521. if ctx.Repo.Owner.IsOrganization() {
  522. orgLabels, err := models.GetLabelsInOrgByIDs(ctx.Repo.Owner.ID, form.Labels)
  523. if err != nil {
  524. ctx.Error(http.StatusInternalServerError, "GetLabelsInOrgByIDs", err)
  525. return
  526. }
  527. labels = append(labels, orgLabels...)
  528. }
  529. if err = issue.ReplaceLabels(labels, ctx.User); err != nil {
  530. ctx.Error(http.StatusInternalServerError, "ReplaceLabelsError", err)
  531. return
  532. }
  533. }
  534. if form.State != nil {
  535. issue.IsClosed = api.StateClosed == api.StateType(*form.State)
  536. }
  537. statusChangeComment, titleChanged, err := models.UpdateIssueByAPI(issue, ctx.User)
  538. if err != nil {
  539. if models.IsErrDependenciesLeft(err) {
  540. ctx.Error(http.StatusPreconditionFailed, "DependenciesLeft", "cannot close this pull request because it still has open dependencies")
  541. return
  542. }
  543. ctx.Error(http.StatusInternalServerError, "UpdateIssueByAPI", err)
  544. return
  545. }
  546. if titleChanged {
  547. notification.NotifyIssueChangeTitle(ctx.User, issue, oldTitle)
  548. }
  549. if statusChangeComment != nil {
  550. notification.NotifyIssueChangeStatus(ctx.User, issue, statusChangeComment, issue.IsClosed)
  551. }
  552. // change pull target branch
  553. if len(form.Base) != 0 && form.Base != pr.BaseBranch {
  554. if !ctx.Repo.GitRepo.IsBranchExist(form.Base) {
  555. ctx.Error(http.StatusNotFound, "NewBaseBranchNotExist", fmt.Errorf("new base '%s' not exist", form.Base))
  556. return
  557. }
  558. if err := pull_service.ChangeTargetBranch(pr, ctx.User, form.Base); err != nil {
  559. if models.IsErrPullRequestAlreadyExists(err) {
  560. ctx.Error(http.StatusConflict, "IsErrPullRequestAlreadyExists", err)
  561. return
  562. } else if models.IsErrIssueIsClosed(err) {
  563. ctx.Error(http.StatusUnprocessableEntity, "IsErrIssueIsClosed", err)
  564. return
  565. } else if models.IsErrPullRequestHasMerged(err) {
  566. ctx.Error(http.StatusConflict, "IsErrPullRequestHasMerged", err)
  567. return
  568. } else {
  569. ctx.InternalServerError(err)
  570. }
  571. return
  572. }
  573. notification.NotifyPullRequestChangeTargetBranch(ctx.User, pr, form.Base)
  574. }
  575. // Refetch from database
  576. pr, err = models.GetPullRequestByIndex(ctx.Repo.Repository.ID, pr.Index)
  577. if err != nil {
  578. if models.IsErrPullRequestNotExist(err) {
  579. ctx.NotFound()
  580. } else {
  581. ctx.Error(http.StatusInternalServerError, "GetPullRequestByIndex", err)
  582. }
  583. return
  584. }
  585. // TODO this should be 200, not 201
  586. ctx.JSON(http.StatusCreated, convert.ToAPIPullRequest(pr))
  587. }
  588. // IsPullRequestMerged checks if a PR exists given an index
  589. func IsPullRequestMerged(ctx *context.APIContext) {
  590. // swagger:operation GET /repos/{owner}/{repo}/pulls/{index}/merge repository repoPullRequestIsMerged
  591. // ---
  592. // summary: Check if a pull request has been merged
  593. // produces:
  594. // - application/json
  595. // parameters:
  596. // - name: owner
  597. // in: path
  598. // description: owner of the repo
  599. // type: string
  600. // required: true
  601. // - name: repo
  602. // in: path
  603. // description: name of the repo
  604. // type: string
  605. // required: true
  606. // - name: index
  607. // in: path
  608. // description: index of the pull request
  609. // type: integer
  610. // format: int64
  611. // required: true
  612. // responses:
  613. // "204":
  614. // description: pull request has been merged
  615. // "404":
  616. // description: pull request has not been merged
  617. pr, err := models.GetPullRequestByIndex(ctx.Repo.Repository.ID, ctx.ParamsInt64(":index"))
  618. if err != nil {
  619. if models.IsErrPullRequestNotExist(err) {
  620. ctx.NotFound()
  621. } else {
  622. ctx.Error(http.StatusInternalServerError, "GetPullRequestByIndex", err)
  623. }
  624. return
  625. }
  626. if pr.HasMerged {
  627. ctx.Status(http.StatusNoContent)
  628. }
  629. ctx.NotFound()
  630. }
  631. // MergePullRequest merges a PR given an index
  632. func MergePullRequest(ctx *context.APIContext) {
  633. // swagger:operation POST /repos/{owner}/{repo}/pulls/{index}/merge repository repoMergePullRequest
  634. // ---
  635. // summary: Merge a pull request
  636. // produces:
  637. // - application/json
  638. // parameters:
  639. // - name: owner
  640. // in: path
  641. // description: owner of the repo
  642. // type: string
  643. // required: true
  644. // - name: repo
  645. // in: path
  646. // description: name of the repo
  647. // type: string
  648. // required: true
  649. // - name: index
  650. // in: path
  651. // description: index of the pull request to merge
  652. // type: integer
  653. // format: int64
  654. // required: true
  655. // - name: body
  656. // in: body
  657. // schema:
  658. // $ref: "#/definitions/MergePullRequestOption"
  659. // responses:
  660. // "200":
  661. // "$ref": "#/responses/empty"
  662. // "405":
  663. // "$ref": "#/responses/empty"
  664. // "409":
  665. // "$ref": "#/responses/error"
  666. form := web.GetForm(ctx).(*forms.MergePullRequestForm)
  667. pr, err := models.GetPullRequestByIndex(ctx.Repo.Repository.ID, ctx.ParamsInt64(":index"))
  668. if err != nil {
  669. if models.IsErrPullRequestNotExist(err) {
  670. ctx.NotFound("GetPullRequestByIndex", err)
  671. } else {
  672. ctx.Error(http.StatusInternalServerError, "GetPullRequestByIndex", err)
  673. }
  674. return
  675. }
  676. if err = pr.LoadHeadRepo(); err != nil {
  677. ctx.Error(http.StatusInternalServerError, "LoadHeadRepo", err)
  678. return
  679. }
  680. err = pr.LoadIssue()
  681. if err != nil {
  682. ctx.Error(http.StatusInternalServerError, "LoadIssue", err)
  683. return
  684. }
  685. pr.Issue.Repo = ctx.Repo.Repository
  686. if ctx.IsSigned {
  687. // Update issue-user.
  688. if err = pr.Issue.ReadBy(ctx.User.ID); err != nil {
  689. ctx.Error(http.StatusInternalServerError, "ReadBy", err)
  690. return
  691. }
  692. }
  693. if pr.Issue.IsClosed {
  694. ctx.NotFound()
  695. return
  696. }
  697. allowedMerge, err := pull_service.IsUserAllowedToMerge(pr, ctx.Repo.Permission, ctx.User)
  698. if err != nil {
  699. ctx.Error(http.StatusInternalServerError, "IsUSerAllowedToMerge", err)
  700. return
  701. }
  702. if !allowedMerge {
  703. ctx.Error(http.StatusMethodNotAllowed, "Merge", "User not allowed to merge PR")
  704. return
  705. }
  706. if pr.HasMerged {
  707. ctx.Error(http.StatusMethodNotAllowed, "PR already merged", "")
  708. return
  709. }
  710. // handle manually-merged mark
  711. if models.MergeStyle(form.Do) == models.MergeStyleManuallyMerged {
  712. if err = pull_service.MergedManually(pr, ctx.User, ctx.Repo.GitRepo, form.MergeCommitID); err != nil {
  713. if models.IsErrInvalidMergeStyle(err) {
  714. ctx.Error(http.StatusMethodNotAllowed, "Invalid merge style", fmt.Errorf("%s is not allowed an allowed merge style for this repository", models.MergeStyle(form.Do)))
  715. return
  716. }
  717. if strings.Contains(err.Error(), "Wrong commit ID") {
  718. ctx.JSON(http.StatusConflict, err)
  719. return
  720. }
  721. ctx.Error(http.StatusInternalServerError, "Manually-Merged", err)
  722. return
  723. }
  724. ctx.Status(http.StatusOK)
  725. return
  726. }
  727. if !pr.CanAutoMerge() {
  728. ctx.Error(http.StatusMethodNotAllowed, "PR not in mergeable state", "Please try again later")
  729. return
  730. }
  731. if pr.IsWorkInProgress() {
  732. ctx.Error(http.StatusMethodNotAllowed, "PR is a work in progress", "Work in progress PRs cannot be merged")
  733. return
  734. }
  735. if err := pull_service.CheckPRReadyToMerge(pr, false); err != nil {
  736. if !models.IsErrNotAllowedToMerge(err) {
  737. ctx.Error(http.StatusInternalServerError, "CheckPRReadyToMerge", err)
  738. return
  739. }
  740. if form.ForceMerge != nil && *form.ForceMerge {
  741. if isRepoAdmin, err := models.IsUserRepoAdmin(pr.BaseRepo, ctx.User); err != nil {
  742. ctx.Error(http.StatusInternalServerError, "IsUserRepoAdmin", err)
  743. return
  744. } else if !isRepoAdmin {
  745. ctx.Error(http.StatusMethodNotAllowed, "Merge", "Only repository admin can merge if not all checks are ok (force merge)")
  746. }
  747. } else {
  748. ctx.Error(http.StatusMethodNotAllowed, "PR is not ready to be merged", err)
  749. return
  750. }
  751. }
  752. if _, err := pull_service.IsSignedIfRequired(pr, ctx.User); err != nil {
  753. if !models.IsErrWontSign(err) {
  754. ctx.Error(http.StatusInternalServerError, "IsSignedIfRequired", err)
  755. return
  756. }
  757. ctx.Error(http.StatusMethodNotAllowed, fmt.Sprintf("Protected branch %s requires signed commits but this merge would not be signed", pr.BaseBranch), err)
  758. return
  759. }
  760. if len(form.Do) == 0 {
  761. form.Do = string(models.MergeStyleMerge)
  762. }
  763. message := strings.TrimSpace(form.MergeTitleField)
  764. if len(message) == 0 {
  765. if models.MergeStyle(form.Do) == models.MergeStyleMerge {
  766. message = pr.GetDefaultMergeMessage()
  767. }
  768. if models.MergeStyle(form.Do) == models.MergeStyleSquash {
  769. message = pr.GetDefaultSquashMessage()
  770. }
  771. }
  772. form.MergeMessageField = strings.TrimSpace(form.MergeMessageField)
  773. if len(form.MergeMessageField) > 0 {
  774. message += "\n\n" + form.MergeMessageField
  775. }
  776. if err := pull_service.Merge(pr, ctx.User, ctx.Repo.GitRepo, models.MergeStyle(form.Do), message); err != nil {
  777. if models.IsErrInvalidMergeStyle(err) {
  778. ctx.Error(http.StatusMethodNotAllowed, "Invalid merge style", fmt.Errorf("%s is not allowed an allowed merge style for this repository", models.MergeStyle(form.Do)))
  779. return
  780. } else if models.IsErrMergeConflicts(err) {
  781. conflictError := err.(models.ErrMergeConflicts)
  782. ctx.JSON(http.StatusConflict, conflictError)
  783. } else if models.IsErrRebaseConflicts(err) {
  784. conflictError := err.(models.ErrRebaseConflicts)
  785. ctx.JSON(http.StatusConflict, conflictError)
  786. } else if models.IsErrMergeUnrelatedHistories(err) {
  787. conflictError := err.(models.ErrMergeUnrelatedHistories)
  788. ctx.JSON(http.StatusConflict, conflictError)
  789. } else if git.IsErrPushOutOfDate(err) {
  790. ctx.Error(http.StatusConflict, "Merge", "merge push out of date")
  791. return
  792. } else if git.IsErrPushRejected(err) {
  793. errPushRej := err.(*git.ErrPushRejected)
  794. if len(errPushRej.Message) == 0 {
  795. ctx.Error(http.StatusConflict, "Merge", "PushRejected without remote error message")
  796. return
  797. }
  798. ctx.Error(http.StatusConflict, "Merge", "PushRejected with remote message: "+errPushRej.Message)
  799. return
  800. }
  801. ctx.Error(http.StatusInternalServerError, "Merge", err)
  802. return
  803. }
  804. log.Trace("Pull request merged: %d", pr.ID)
  805. if form.DeleteBranchAfterMerge {
  806. var headRepo *git.Repository
  807. if ctx.Repo != nil && ctx.Repo.Repository != nil && ctx.Repo.Repository.ID == pr.HeadRepoID && ctx.Repo.GitRepo != nil {
  808. headRepo = ctx.Repo.GitRepo
  809. } else {
  810. headRepo, err = git.OpenRepository(pr.HeadRepo.RepoPath())
  811. if err != nil {
  812. ctx.ServerError(fmt.Sprintf("OpenRepository[%s]", pr.HeadRepo.RepoPath()), err)
  813. return
  814. }
  815. defer headRepo.Close()
  816. }
  817. if err := repo_service.DeleteBranch(ctx.User, pr.HeadRepo, headRepo, pr.HeadBranch); err != nil {
  818. switch {
  819. case git.IsErrBranchNotExist(err):
  820. ctx.NotFound(err)
  821. case errors.Is(err, repo_service.ErrBranchIsDefault):
  822. ctx.Error(http.StatusForbidden, "DefaultBranch", fmt.Errorf("can not delete default branch"))
  823. case errors.Is(err, repo_service.ErrBranchIsProtected):
  824. ctx.Error(http.StatusForbidden, "IsProtectedBranch", fmt.Errorf("branch protected"))
  825. default:
  826. ctx.Error(http.StatusInternalServerError, "DeleteBranch", err)
  827. }
  828. return
  829. }
  830. if err := models.AddDeletePRBranchComment(ctx.User, pr.BaseRepo, pr.Issue.ID, pr.HeadBranch); err != nil {
  831. // Do not fail here as branch has already been deleted
  832. log.Error("DeleteBranch: %v", err)
  833. }
  834. }
  835. ctx.Status(http.StatusOK)
  836. }
  837. func parseCompareInfo(ctx *context.APIContext, form api.CreatePullRequestOption) (*models.User, *models.Repository, *git.Repository, *git.CompareInfo, string, string) {
  838. baseRepo := ctx.Repo.Repository
  839. // Get compared branches information
  840. // format: <base branch>...[<head repo>:]<head branch>
  841. // base<-head: master...head:feature
  842. // same repo: master...feature
  843. // TODO: Validate form first?
  844. baseBranch := form.Base
  845. var (
  846. headUser *models.User
  847. headBranch string
  848. isSameRepo bool
  849. err error
  850. )
  851. // If there is no head repository, it means pull request between same repository.
  852. headInfos := strings.Split(form.Head, ":")
  853. if len(headInfos) == 1 {
  854. isSameRepo = true
  855. headUser = ctx.Repo.Owner
  856. headBranch = headInfos[0]
  857. } else if len(headInfos) == 2 {
  858. headUser, err = models.GetUserByName(headInfos[0])
  859. if err != nil {
  860. if models.IsErrUserNotExist(err) {
  861. ctx.NotFound("GetUserByName")
  862. } else {
  863. ctx.Error(http.StatusInternalServerError, "GetUserByName", err)
  864. }
  865. return nil, nil, nil, nil, "", ""
  866. }
  867. headBranch = headInfos[1]
  868. } else {
  869. ctx.NotFound()
  870. return nil, nil, nil, nil, "", ""
  871. }
  872. ctx.Repo.PullRequest.SameRepo = isSameRepo
  873. log.Info("Base branch: %s", baseBranch)
  874. log.Info("Repo path: %s", ctx.Repo.GitRepo.Path)
  875. // Check if base branch is valid.
  876. if !ctx.Repo.GitRepo.IsBranchExist(baseBranch) {
  877. ctx.NotFound("IsBranchExist")
  878. return nil, nil, nil, nil, "", ""
  879. }
  880. // Check if current user has fork of repository or in the same repository.
  881. headRepo, has := models.HasForkedRepo(headUser.ID, baseRepo.ID)
  882. if !has && !isSameRepo {
  883. log.Trace("parseCompareInfo[%d]: does not have fork or in same repository", baseRepo.ID)
  884. ctx.NotFound("HasForkedRepo")
  885. return nil, nil, nil, nil, "", ""
  886. }
  887. var headGitRepo *git.Repository
  888. if isSameRepo {
  889. headRepo = ctx.Repo.Repository
  890. headGitRepo = ctx.Repo.GitRepo
  891. } else {
  892. headGitRepo, err = git.OpenRepository(models.RepoPath(headUser.Name, headRepo.Name))
  893. if err != nil {
  894. ctx.Error(http.StatusInternalServerError, "OpenRepository", err)
  895. return nil, nil, nil, nil, "", ""
  896. }
  897. }
  898. // user should have permission to read baseRepo's codes and pulls, NOT headRepo's
  899. permBase, err := models.GetUserRepoPermission(baseRepo, ctx.User)
  900. if err != nil {
  901. headGitRepo.Close()
  902. ctx.Error(http.StatusInternalServerError, "GetUserRepoPermission", err)
  903. return nil, nil, nil, nil, "", ""
  904. }
  905. if !permBase.CanReadIssuesOrPulls(true) || !permBase.CanRead(models.UnitTypeCode) {
  906. if log.IsTrace() {
  907. log.Trace("Permission Denied: User %-v cannot create/read pull requests or cannot read code in Repo %-v\nUser in baseRepo has Permissions: %-+v",
  908. ctx.User,
  909. baseRepo,
  910. permBase)
  911. }
  912. headGitRepo.Close()
  913. ctx.NotFound("Can't read pulls or can't read UnitTypeCode")
  914. return nil, nil, nil, nil, "", ""
  915. }
  916. // user should have permission to read headrepo's codes
  917. permHead, err := models.GetUserRepoPermission(headRepo, ctx.User)
  918. if err != nil {
  919. headGitRepo.Close()
  920. ctx.Error(http.StatusInternalServerError, "GetUserRepoPermission", err)
  921. return nil, nil, nil, nil, "", ""
  922. }
  923. if !permHead.CanRead(models.UnitTypeCode) {
  924. if log.IsTrace() {
  925. log.Trace("Permission Denied: User: %-v cannot read code in Repo: %-v\nUser in headRepo has Permissions: %-+v",
  926. ctx.User,
  927. headRepo,
  928. permHead)
  929. }
  930. headGitRepo.Close()
  931. ctx.NotFound("Can't read headRepo UnitTypeCode")
  932. return nil, nil, nil, nil, "", ""
  933. }
  934. // Check if head branch is valid.
  935. if !headGitRepo.IsBranchExist(headBranch) {
  936. headGitRepo.Close()
  937. ctx.NotFound()
  938. return nil, nil, nil, nil, "", ""
  939. }
  940. compareInfo, err := headGitRepo.GetCompareInfo(models.RepoPath(baseRepo.Owner.Name, baseRepo.Name), baseBranch, headBranch)
  941. if err != nil {
  942. headGitRepo.Close()
  943. ctx.Error(http.StatusInternalServerError, "GetCompareInfo", err)
  944. return nil, nil, nil, nil, "", ""
  945. }
  946. return headUser, headRepo, headGitRepo, compareInfo, baseBranch, headBranch
  947. }
  948. // UpdatePullRequest merge PR's baseBranch into headBranch
  949. func UpdatePullRequest(ctx *context.APIContext) {
  950. // swagger:operation POST /repos/{owner}/{repo}/pulls/{index}/update repository repoUpdatePullRequest
  951. // ---
  952. // summary: Merge PR's baseBranch into headBranch
  953. // produces:
  954. // - application/json
  955. // parameters:
  956. // - name: owner
  957. // in: path
  958. // description: owner of the repo
  959. // type: string
  960. // required: true
  961. // - name: repo
  962. // in: path
  963. // description: name of the repo
  964. // type: string
  965. // required: true
  966. // - name: index
  967. // in: path
  968. // description: index of the pull request to get
  969. // type: integer
  970. // format: int64
  971. // required: true
  972. // responses:
  973. // "200":
  974. // "$ref": "#/responses/empty"
  975. // "403":
  976. // "$ref": "#/responses/forbidden"
  977. // "404":
  978. // "$ref": "#/responses/notFound"
  979. // "409":
  980. // "$ref": "#/responses/error"
  981. // "422":
  982. // "$ref": "#/responses/validationError"
  983. pr, err := models.GetPullRequestByIndex(ctx.Repo.Repository.ID, ctx.ParamsInt64(":index"))
  984. if err != nil {
  985. if models.IsErrPullRequestNotExist(err) {
  986. ctx.NotFound()
  987. } else {
  988. ctx.Error(http.StatusInternalServerError, "GetPullRequestByIndex", err)
  989. }
  990. return
  991. }
  992. if pr.HasMerged {
  993. ctx.Error(http.StatusUnprocessableEntity, "UpdatePullRequest", err)
  994. return
  995. }
  996. if err = pr.LoadIssue(); err != nil {
  997. ctx.Error(http.StatusInternalServerError, "LoadIssue", err)
  998. return
  999. }
  1000. if pr.Issue.IsClosed {
  1001. ctx.Error(http.StatusUnprocessableEntity, "UpdatePullRequest", err)
  1002. return
  1003. }
  1004. if err = pr.LoadBaseRepo(); err != nil {
  1005. ctx.Error(http.StatusInternalServerError, "LoadBaseRepo", err)
  1006. return
  1007. }
  1008. if err = pr.LoadHeadRepo(); err != nil {
  1009. ctx.Error(http.StatusInternalServerError, "LoadHeadRepo", err)
  1010. return
  1011. }
  1012. allowedUpdate, err := pull_service.IsUserAllowedToUpdate(pr, ctx.User)
  1013. if err != nil {
  1014. ctx.Error(http.StatusInternalServerError, "IsUserAllowedToMerge", err)
  1015. return
  1016. }
  1017. if !allowedUpdate {
  1018. ctx.Status(http.StatusForbidden)
  1019. return
  1020. }
  1021. // default merge commit message
  1022. message := fmt.Sprintf("Merge branch '%s' into %s", pr.BaseBranch, pr.HeadBranch)
  1023. if err = pull_service.Update(pr, ctx.User, message); err != nil {
  1024. if models.IsErrMergeConflicts(err) {
  1025. ctx.Error(http.StatusConflict, "Update", "merge failed because of conflict")
  1026. return
  1027. }
  1028. ctx.Error(http.StatusInternalServerError, "pull_service.Update", err)
  1029. return
  1030. }
  1031. ctx.Status(http.StatusOK)
  1032. }
  1033. // GetPullRequestCommits gets all commits associated with a given PR
  1034. func GetPullRequestCommits(ctx *context.APIContext) {
  1035. // swagger:operation GET /repos/{owner}/{repo}/pulls/{index}/commits repository repoGetPullRequestCommits
  1036. // ---
  1037. // summary: Get commits for a pull request
  1038. // produces:
  1039. // - application/json
  1040. // parameters:
  1041. // - name: owner
  1042. // in: path
  1043. // description: owner of the repo
  1044. // type: string
  1045. // required: true
  1046. // - name: repo
  1047. // in: path
  1048. // description: name of the repo
  1049. // type: string
  1050. // required: true
  1051. // - name: index
  1052. // in: path
  1053. // description: index of the pull request to get
  1054. // type: integer
  1055. // format: int64
  1056. // required: true
  1057. // - name: page
  1058. // in: query
  1059. // description: page number of results to return (1-based)
  1060. // type: integer
  1061. // - name: limit
  1062. // in: query
  1063. // description: page size of results
  1064. // type: integer
  1065. // responses:
  1066. // "200":
  1067. // "$ref": "#/responses/CommitList"
  1068. // "404":
  1069. // "$ref": "#/responses/notFound"
  1070. pr, err := models.GetPullRequestByIndex(ctx.Repo.Repository.ID, ctx.ParamsInt64(":index"))
  1071. if err != nil {
  1072. if models.IsErrPullRequestNotExist(err) {
  1073. ctx.NotFound()
  1074. } else {
  1075. ctx.Error(http.StatusInternalServerError, "GetPullRequestByIndex", err)
  1076. }
  1077. return
  1078. }
  1079. if err := pr.LoadBaseRepo(); err != nil {
  1080. ctx.InternalServerError(err)
  1081. return
  1082. }
  1083. var prInfo *git.CompareInfo
  1084. baseGitRepo, err := git.OpenRepository(pr.BaseRepo.RepoPath())
  1085. if err != nil {
  1086. ctx.ServerError("OpenRepository", err)
  1087. return
  1088. }
  1089. defer baseGitRepo.Close()
  1090. if pr.HasMerged {
  1091. prInfo, err = baseGitRepo.GetCompareInfo(pr.BaseRepo.RepoPath(), pr.MergeBase, pr.GetGitRefName())
  1092. } else {
  1093. prInfo, err = baseGitRepo.GetCompareInfo(pr.BaseRepo.RepoPath(), pr.BaseBranch, pr.GetGitRefName())
  1094. }
  1095. if err != nil {
  1096. ctx.ServerError("GetCompareInfo", err)
  1097. return
  1098. }
  1099. commits := prInfo.Commits
  1100. listOptions := utils.GetListOptions(ctx)
  1101. totalNumberOfCommits := len(commits)
  1102. totalNumberOfPages := int(math.Ceil(float64(totalNumberOfCommits) / float64(listOptions.PageSize)))
  1103. userCache := make(map[string]*models.User)
  1104. start, end := listOptions.GetStartEnd()
  1105. if end > totalNumberOfCommits {
  1106. end = totalNumberOfCommits
  1107. }
  1108. apiCommits := make([]*api.Commit, 0, end-start)
  1109. for i := start; i < end; i++ {
  1110. apiCommit, err := convert.ToCommit(ctx.Repo.Repository, commits[i], userCache)
  1111. if err != nil {
  1112. ctx.ServerError("toCommit", err)
  1113. return
  1114. }
  1115. apiCommits = append(apiCommits, apiCommit)
  1116. }
  1117. ctx.SetLinkHeader(totalNumberOfCommits, listOptions.PageSize)
  1118. ctx.SetTotalCountHeader(int64(totalNumberOfCommits))
  1119. ctx.Header().Set("X-Page", strconv.Itoa(listOptions.Page))
  1120. ctx.Header().Set("X-PerPage", strconv.Itoa(listOptions.PageSize))
  1121. ctx.Header().Set("X-PageCount", strconv.Itoa(totalNumberOfPages))
  1122. ctx.Header().Set("X-HasMore", strconv.FormatBool(listOptions.Page < totalNumberOfPages))
  1123. ctx.AppendAccessControlExposeHeaders("X-Page", "X-PerPage", "X-PageCount", "X-HasMore")
  1124. ctx.JSON(http.StatusOK, &apiCommits)
  1125. }