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 20 kB

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