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