You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

pull.go 18 kB

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