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

pull.go 48KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597
  1. // Copyright 2016 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package repo
  4. import (
  5. "errors"
  6. "fmt"
  7. "math"
  8. "net/http"
  9. "strconv"
  10. "strings"
  11. "time"
  12. "code.gitea.io/gitea/models"
  13. activities_model "code.gitea.io/gitea/models/activities"
  14. git_model "code.gitea.io/gitea/models/git"
  15. issues_model "code.gitea.io/gitea/models/issues"
  16. access_model "code.gitea.io/gitea/models/perm/access"
  17. pull_model "code.gitea.io/gitea/models/pull"
  18. repo_model "code.gitea.io/gitea/models/repo"
  19. "code.gitea.io/gitea/models/unit"
  20. user_model "code.gitea.io/gitea/models/user"
  21. "code.gitea.io/gitea/modules/base"
  22. "code.gitea.io/gitea/modules/git"
  23. "code.gitea.io/gitea/modules/gitrepo"
  24. "code.gitea.io/gitea/modules/log"
  25. "code.gitea.io/gitea/modules/setting"
  26. api "code.gitea.io/gitea/modules/structs"
  27. "code.gitea.io/gitea/modules/timeutil"
  28. "code.gitea.io/gitea/modules/web"
  29. "code.gitea.io/gitea/routers/api/v1/utils"
  30. asymkey_service "code.gitea.io/gitea/services/asymkey"
  31. "code.gitea.io/gitea/services/automerge"
  32. "code.gitea.io/gitea/services/context"
  33. "code.gitea.io/gitea/services/convert"
  34. "code.gitea.io/gitea/services/forms"
  35. "code.gitea.io/gitea/services/gitdiff"
  36. issue_service "code.gitea.io/gitea/services/issue"
  37. notify_service "code.gitea.io/gitea/services/notify"
  38. pull_service "code.gitea.io/gitea/services/pull"
  39. repo_service "code.gitea.io/gitea/services/repository"
  40. )
  41. // ListPullRequests returns a list of all PRs
  42. func ListPullRequests(ctx *context.APIContext) {
  43. // swagger:operation GET /repos/{owner}/{repo}/pulls repository repoListPullRequests
  44. // ---
  45. // summary: List a repo's pull requests
  46. // produces:
  47. // - application/json
  48. // parameters:
  49. // - name: owner
  50. // in: path
  51. // description: owner of the repo
  52. // type: string
  53. // required: true
  54. // - name: repo
  55. // in: path
  56. // description: name of the repo
  57. // type: string
  58. // required: true
  59. // - name: state
  60. // in: query
  61. // description: "State of pull request: open or closed (optional)"
  62. // type: string
  63. // enum: [closed, open, all]
  64. // - name: sort
  65. // in: query
  66. // description: "Type of sort"
  67. // type: string
  68. // enum: [oldest, recentupdate, leastupdate, mostcomment, leastcomment, priority]
  69. // - name: milestone
  70. // in: query
  71. // description: "ID of the milestone"
  72. // type: integer
  73. // format: int64
  74. // - name: labels
  75. // in: query
  76. // description: "Label IDs"
  77. // type: array
  78. // collectionFormat: multi
  79. // items:
  80. // type: integer
  81. // format: int64
  82. // - name: page
  83. // in: query
  84. // description: page number of results to return (1-based)
  85. // type: integer
  86. // - name: limit
  87. // in: query
  88. // description: page size of results
  89. // type: integer
  90. // responses:
  91. // "200":
  92. // "$ref": "#/responses/PullRequestList"
  93. // "404":
  94. // "$ref": "#/responses/notFound"
  95. labelIDs, err := base.StringsToInt64s(ctx.FormStrings("labels"))
  96. if err != nil {
  97. ctx.Error(http.StatusInternalServerError, "PullRequests", err)
  98. return
  99. }
  100. listOptions := utils.GetListOptions(ctx)
  101. prs, maxResults, err := issues_model.PullRequests(ctx, ctx.Repo.Repository.ID, &issues_model.PullRequestsOptions{
  102. ListOptions: listOptions,
  103. State: ctx.FormTrim("state"),
  104. SortType: ctx.FormTrim("sort"),
  105. Labels: labelIDs,
  106. MilestoneID: ctx.FormInt64("milestone"),
  107. })
  108. if err != nil {
  109. ctx.Error(http.StatusInternalServerError, "PullRequests", err)
  110. return
  111. }
  112. apiPrs := make([]*api.PullRequest, len(prs))
  113. for i := range prs {
  114. if err = prs[i].LoadIssue(ctx); err != nil {
  115. ctx.Error(http.StatusInternalServerError, "LoadIssue", err)
  116. return
  117. }
  118. if err = prs[i].LoadAttributes(ctx); err != nil {
  119. ctx.Error(http.StatusInternalServerError, "LoadAttributes", err)
  120. return
  121. }
  122. if err = prs[i].LoadBaseRepo(ctx); err != nil {
  123. ctx.Error(http.StatusInternalServerError, "LoadBaseRepo", err)
  124. return
  125. }
  126. if err = prs[i].LoadHeadRepo(ctx); err != nil {
  127. ctx.Error(http.StatusInternalServerError, "LoadHeadRepo", err)
  128. return
  129. }
  130. apiPrs[i] = convert.ToAPIPullRequest(ctx, prs[i], ctx.Doer)
  131. }
  132. ctx.SetLinkHeader(int(maxResults), listOptions.PageSize)
  133. ctx.SetTotalCountHeader(maxResults)
  134. ctx.JSON(http.StatusOK, &apiPrs)
  135. }
  136. // GetPullRequest returns a single PR based on index
  137. func GetPullRequest(ctx *context.APIContext) {
  138. // swagger:operation GET /repos/{owner}/{repo}/pulls/{index} repository repoGetPullRequest
  139. // ---
  140. // summary: Get a pull request
  141. // produces:
  142. // - application/json
  143. // parameters:
  144. // - name: owner
  145. // in: path
  146. // description: owner of the repo
  147. // type: string
  148. // required: true
  149. // - name: repo
  150. // in: path
  151. // description: name of the repo
  152. // type: string
  153. // required: true
  154. // - name: index
  155. // in: path
  156. // description: index of the pull request to get
  157. // type: integer
  158. // format: int64
  159. // required: true
  160. // responses:
  161. // "200":
  162. // "$ref": "#/responses/PullRequest"
  163. // "404":
  164. // "$ref": "#/responses/notFound"
  165. pr, err := issues_model.GetPullRequestByIndex(ctx, ctx.Repo.Repository.ID, ctx.ParamsInt64(":index"))
  166. if err != nil {
  167. if issues_model.IsErrPullRequestNotExist(err) {
  168. ctx.NotFound()
  169. } else {
  170. ctx.Error(http.StatusInternalServerError, "GetPullRequestByIndex", err)
  171. }
  172. return
  173. }
  174. if err = pr.LoadBaseRepo(ctx); err != nil {
  175. ctx.Error(http.StatusInternalServerError, "LoadBaseRepo", err)
  176. return
  177. }
  178. if err = pr.LoadHeadRepo(ctx); err != nil {
  179. ctx.Error(http.StatusInternalServerError, "LoadHeadRepo", err)
  180. return
  181. }
  182. ctx.JSON(http.StatusOK, convert.ToAPIPullRequest(ctx, pr, ctx.Doer))
  183. }
  184. // GetPullRequest returns a single PR based on index
  185. func GetPullRequestByBaseHead(ctx *context.APIContext) {
  186. // swagger:operation GET /repos/{owner}/{repo}/pulls/{base}/{head} repository repoGetPullRequestByBaseHead
  187. // ---
  188. // summary: Get a pull request by base and head
  189. // produces:
  190. // - application/json
  191. // parameters:
  192. // - name: owner
  193. // in: path
  194. // description: owner of the repo
  195. // type: string
  196. // required: true
  197. // - name: repo
  198. // in: path
  199. // description: name of the repo
  200. // type: string
  201. // required: true
  202. // - name: base
  203. // in: path
  204. // description: base of the pull request to get
  205. // type: string
  206. // required: true
  207. // - name: head
  208. // in: path
  209. // description: head of the pull request to get
  210. // type: string
  211. // required: true
  212. // responses:
  213. // "200":
  214. // "$ref": "#/responses/PullRequest"
  215. // "404":
  216. // "$ref": "#/responses/notFound"
  217. var headRepoID int64
  218. var headBranch string
  219. head := ctx.Params("*")
  220. if strings.Contains(head, ":") {
  221. split := strings.SplitN(head, ":", 2)
  222. headBranch = split[1]
  223. var owner, name string
  224. if strings.Contains(split[0], "/") {
  225. split = strings.Split(split[0], "/")
  226. owner = split[0]
  227. name = split[1]
  228. } else {
  229. owner = split[0]
  230. name = ctx.Repo.Repository.Name
  231. }
  232. repo, err := repo_model.GetRepositoryByOwnerAndName(ctx, owner, name)
  233. if err != nil {
  234. if repo_model.IsErrRepoNotExist(err) {
  235. ctx.NotFound()
  236. } else {
  237. ctx.Error(http.StatusInternalServerError, "GetRepositoryByOwnerName", err)
  238. }
  239. return
  240. }
  241. headRepoID = repo.ID
  242. } else {
  243. headRepoID = ctx.Repo.Repository.ID
  244. headBranch = head
  245. }
  246. pr, err := issues_model.GetPullRequestByBaseHeadInfo(ctx, ctx.Repo.Repository.ID, headRepoID, ctx.Params(":base"), headBranch)
  247. if err != nil {
  248. if issues_model.IsErrPullRequestNotExist(err) {
  249. ctx.NotFound()
  250. } else {
  251. ctx.Error(http.StatusInternalServerError, "GetPullRequestByBaseHeadInfo", err)
  252. }
  253. return
  254. }
  255. if err = pr.LoadBaseRepo(ctx); err != nil {
  256. ctx.Error(http.StatusInternalServerError, "LoadBaseRepo", err)
  257. return
  258. }
  259. if err = pr.LoadHeadRepo(ctx); err != nil {
  260. ctx.Error(http.StatusInternalServerError, "LoadHeadRepo", err)
  261. return
  262. }
  263. ctx.JSON(http.StatusOK, convert.ToAPIPullRequest(ctx, pr, ctx.Doer))
  264. }
  265. // DownloadPullDiffOrPatch render a pull's raw diff or patch
  266. func DownloadPullDiffOrPatch(ctx *context.APIContext) {
  267. // swagger:operation GET /repos/{owner}/{repo}/pulls/{index}.{diffType} repository repoDownloadPullDiffOrPatch
  268. // ---
  269. // summary: Get a pull request diff or patch
  270. // produces:
  271. // - text/plain
  272. // parameters:
  273. // - name: owner
  274. // in: path
  275. // description: owner of the repo
  276. // type: string
  277. // required: true
  278. // - name: repo
  279. // in: path
  280. // description: name of the repo
  281. // type: string
  282. // required: true
  283. // - name: index
  284. // in: path
  285. // description: index of the pull request to get
  286. // type: integer
  287. // format: int64
  288. // required: true
  289. // - name: diffType
  290. // in: path
  291. // description: whether the output is diff or patch
  292. // type: string
  293. // enum: [diff, patch]
  294. // required: true
  295. // - name: binary
  296. // in: query
  297. // description: whether to include binary file changes. if true, the diff is applicable with `git apply`
  298. // type: boolean
  299. // responses:
  300. // "200":
  301. // "$ref": "#/responses/string"
  302. // "404":
  303. // "$ref": "#/responses/notFound"
  304. pr, err := issues_model.GetPullRequestByIndex(ctx, ctx.Repo.Repository.ID, ctx.ParamsInt64(":index"))
  305. if err != nil {
  306. if issues_model.IsErrPullRequestNotExist(err) {
  307. ctx.NotFound()
  308. } else {
  309. ctx.InternalServerError(err)
  310. }
  311. return
  312. }
  313. var patch bool
  314. if ctx.Params(":diffType") == "diff" {
  315. patch = false
  316. } else {
  317. patch = true
  318. }
  319. binary := ctx.FormBool("binary")
  320. if err := pull_service.DownloadDiffOrPatch(ctx, pr, ctx, patch, binary); err != nil {
  321. ctx.InternalServerError(err)
  322. return
  323. }
  324. }
  325. // CreatePullRequest does what it says
  326. func CreatePullRequest(ctx *context.APIContext) {
  327. // swagger:operation POST /repos/{owner}/{repo}/pulls repository repoCreatePullRequest
  328. // ---
  329. // summary: Create a pull request
  330. // consumes:
  331. // - application/json
  332. // produces:
  333. // - application/json
  334. // parameters:
  335. // - name: owner
  336. // in: path
  337. // description: owner of the repo
  338. // type: string
  339. // required: true
  340. // - name: repo
  341. // in: path
  342. // description: name of the repo
  343. // type: string
  344. // required: true
  345. // - name: body
  346. // in: body
  347. // schema:
  348. // "$ref": "#/definitions/CreatePullRequestOption"
  349. // responses:
  350. // "201":
  351. // "$ref": "#/responses/PullRequest"
  352. // "403":
  353. // "$ref": "#/responses/forbidden"
  354. // "404":
  355. // "$ref": "#/responses/notFound"
  356. // "409":
  357. // "$ref": "#/responses/error"
  358. // "422":
  359. // "$ref": "#/responses/validationError"
  360. // "423":
  361. // "$ref": "#/responses/repoArchivedError"
  362. form := *web.GetForm(ctx).(*api.CreatePullRequestOption)
  363. if form.Head == form.Base {
  364. ctx.Error(http.StatusUnprocessableEntity, "BaseHeadSame",
  365. "Invalid PullRequest: There are no changes between the head and the base")
  366. return
  367. }
  368. var (
  369. repo = ctx.Repo.Repository
  370. labelIDs []int64
  371. milestoneID int64
  372. )
  373. // Get repo/branch information
  374. _, headRepo, headGitRepo, compareInfo, baseBranch, headBranch := parseCompareInfo(ctx, form)
  375. if ctx.Written() {
  376. return
  377. }
  378. defer headGitRepo.Close()
  379. // Check if another PR exists with the same targets
  380. existingPr, err := issues_model.GetUnmergedPullRequest(ctx, headRepo.ID, ctx.Repo.Repository.ID, headBranch, baseBranch, issues_model.PullRequestFlowGithub)
  381. if err != nil {
  382. if !issues_model.IsErrPullRequestNotExist(err) {
  383. ctx.Error(http.StatusInternalServerError, "GetUnmergedPullRequest", err)
  384. return
  385. }
  386. } else {
  387. err = issues_model.ErrPullRequestAlreadyExists{
  388. ID: existingPr.ID,
  389. IssueID: existingPr.Index,
  390. HeadRepoID: existingPr.HeadRepoID,
  391. BaseRepoID: existingPr.BaseRepoID,
  392. HeadBranch: existingPr.HeadBranch,
  393. BaseBranch: existingPr.BaseBranch,
  394. }
  395. ctx.Error(http.StatusConflict, "GetUnmergedPullRequest", err)
  396. return
  397. }
  398. if len(form.Labels) > 0 {
  399. labels, err := issues_model.GetLabelsInRepoByIDs(ctx, ctx.Repo.Repository.ID, form.Labels)
  400. if err != nil {
  401. ctx.Error(http.StatusInternalServerError, "GetLabelsInRepoByIDs", err)
  402. return
  403. }
  404. labelIDs = make([]int64, 0, len(labels))
  405. for _, label := range labels {
  406. labelIDs = append(labelIDs, label.ID)
  407. }
  408. if ctx.Repo.Owner.IsOrganization() {
  409. orgLabels, err := issues_model.GetLabelsInOrgByIDs(ctx, ctx.Repo.Owner.ID, form.Labels)
  410. if err != nil {
  411. ctx.Error(http.StatusInternalServerError, "GetLabelsInOrgByIDs", err)
  412. return
  413. }
  414. orgLabelIDs := make([]int64, 0, len(orgLabels))
  415. for _, orgLabel := range orgLabels {
  416. orgLabelIDs = append(orgLabelIDs, orgLabel.ID)
  417. }
  418. labelIDs = append(labelIDs, orgLabelIDs...)
  419. }
  420. }
  421. if form.Milestone > 0 {
  422. milestone, err := issues_model.GetMilestoneByRepoID(ctx, ctx.Repo.Repository.ID, form.Milestone)
  423. if err != nil {
  424. if issues_model.IsErrMilestoneNotExist(err) {
  425. ctx.NotFound()
  426. } else {
  427. ctx.Error(http.StatusInternalServerError, "GetMilestoneByRepoID", err)
  428. }
  429. return
  430. }
  431. milestoneID = milestone.ID
  432. }
  433. var deadlineUnix timeutil.TimeStamp
  434. if form.Deadline != nil {
  435. deadlineUnix = timeutil.TimeStamp(form.Deadline.Unix())
  436. }
  437. prIssue := &issues_model.Issue{
  438. RepoID: repo.ID,
  439. Title: form.Title,
  440. PosterID: ctx.Doer.ID,
  441. Poster: ctx.Doer,
  442. MilestoneID: milestoneID,
  443. IsPull: true,
  444. Content: form.Body,
  445. DeadlineUnix: deadlineUnix,
  446. }
  447. pr := &issues_model.PullRequest{
  448. HeadRepoID: headRepo.ID,
  449. BaseRepoID: repo.ID,
  450. HeadBranch: headBranch,
  451. BaseBranch: baseBranch,
  452. HeadRepo: headRepo,
  453. BaseRepo: repo,
  454. MergeBase: compareInfo.MergeBase,
  455. Type: issues_model.PullRequestGitea,
  456. }
  457. // Get all assignee IDs
  458. assigneeIDs, err := issues_model.MakeIDsFromAPIAssigneesToAdd(ctx, form.Assignee, form.Assignees)
  459. if err != nil {
  460. if user_model.IsErrUserNotExist(err) {
  461. ctx.Error(http.StatusUnprocessableEntity, "", fmt.Sprintf("Assignee does not exist: [name: %s]", err))
  462. } else {
  463. ctx.Error(http.StatusInternalServerError, "AddAssigneeByName", err)
  464. }
  465. return
  466. }
  467. // Check if the passed assignees is assignable
  468. for _, aID := range assigneeIDs {
  469. assignee, err := user_model.GetUserByID(ctx, aID)
  470. if err != nil {
  471. ctx.Error(http.StatusInternalServerError, "GetUserByID", err)
  472. return
  473. }
  474. valid, err := access_model.CanBeAssigned(ctx, assignee, repo, true)
  475. if err != nil {
  476. ctx.Error(http.StatusInternalServerError, "canBeAssigned", err)
  477. return
  478. }
  479. if !valid {
  480. ctx.Error(http.StatusUnprocessableEntity, "canBeAssigned", repo_model.ErrUserDoesNotHaveAccessToRepo{UserID: aID, RepoName: repo.Name})
  481. return
  482. }
  483. }
  484. if err := pull_service.NewPullRequest(ctx, repo, prIssue, labelIDs, []string{}, pr, assigneeIDs); err != nil {
  485. if repo_model.IsErrUserDoesNotHaveAccessToRepo(err) {
  486. ctx.Error(http.StatusBadRequest, "UserDoesNotHaveAccessToRepo", err)
  487. } else if errors.Is(err, user_model.ErrBlockedUser) {
  488. ctx.Error(http.StatusForbidden, "BlockedUser", err)
  489. } else {
  490. ctx.Error(http.StatusInternalServerError, "NewPullRequest", err)
  491. }
  492. return
  493. }
  494. log.Trace("Pull request created: %d/%d", repo.ID, prIssue.ID)
  495. ctx.JSON(http.StatusCreated, convert.ToAPIPullRequest(ctx, pr, ctx.Doer))
  496. }
  497. // EditPullRequest does what it says
  498. func EditPullRequest(ctx *context.APIContext) {
  499. // swagger:operation PATCH /repos/{owner}/{repo}/pulls/{index} repository repoEditPullRequest
  500. // ---
  501. // summary: Update a pull request. If using deadline only the date will be taken into account, and time of day ignored.
  502. // consumes:
  503. // - application/json
  504. // produces:
  505. // - application/json
  506. // parameters:
  507. // - name: owner
  508. // in: path
  509. // description: owner of the repo
  510. // type: string
  511. // required: true
  512. // - name: repo
  513. // in: path
  514. // description: name of the repo
  515. // type: string
  516. // required: true
  517. // - name: index
  518. // in: path
  519. // description: index of the pull request to edit
  520. // type: integer
  521. // format: int64
  522. // required: true
  523. // - name: body
  524. // in: body
  525. // schema:
  526. // "$ref": "#/definitions/EditPullRequestOption"
  527. // responses:
  528. // "201":
  529. // "$ref": "#/responses/PullRequest"
  530. // "403":
  531. // "$ref": "#/responses/forbidden"
  532. // "404":
  533. // "$ref": "#/responses/notFound"
  534. // "409":
  535. // "$ref": "#/responses/error"
  536. // "412":
  537. // "$ref": "#/responses/error"
  538. // "422":
  539. // "$ref": "#/responses/validationError"
  540. form := web.GetForm(ctx).(*api.EditPullRequestOption)
  541. pr, err := issues_model.GetPullRequestByIndex(ctx, ctx.Repo.Repository.ID, ctx.ParamsInt64(":index"))
  542. if err != nil {
  543. if issues_model.IsErrPullRequestNotExist(err) {
  544. ctx.NotFound()
  545. } else {
  546. ctx.Error(http.StatusInternalServerError, "GetPullRequestByIndex", err)
  547. }
  548. return
  549. }
  550. err = pr.LoadIssue(ctx)
  551. if err != nil {
  552. ctx.Error(http.StatusInternalServerError, "LoadIssue", err)
  553. return
  554. }
  555. issue := pr.Issue
  556. issue.Repo = ctx.Repo.Repository
  557. if err := issue.LoadAttributes(ctx); err != nil {
  558. ctx.Error(http.StatusInternalServerError, "LoadAttributes", err)
  559. return
  560. }
  561. if !issue.IsPoster(ctx.Doer.ID) && !ctx.Repo.CanWrite(unit.TypePullRequests) {
  562. ctx.Status(http.StatusForbidden)
  563. return
  564. }
  565. if len(form.Title) > 0 {
  566. err = issue_service.ChangeTitle(ctx, issue, ctx.Doer, form.Title)
  567. if err != nil {
  568. ctx.Error(http.StatusInternalServerError, "ChangeTitle", err)
  569. return
  570. }
  571. }
  572. if form.Body != nil {
  573. err = issue_service.ChangeContent(ctx, issue, ctx.Doer, *form.Body)
  574. if err != nil {
  575. ctx.Error(http.StatusInternalServerError, "ChangeContent", err)
  576. return
  577. }
  578. }
  579. // Update or remove deadline if set
  580. if form.Deadline != nil || form.RemoveDeadline != nil {
  581. var deadlineUnix timeutil.TimeStamp
  582. if (form.RemoveDeadline == nil || !*form.RemoveDeadline) && !form.Deadline.IsZero() {
  583. deadline := time.Date(form.Deadline.Year(), form.Deadline.Month(), form.Deadline.Day(),
  584. 23, 59, 59, 0, form.Deadline.Location())
  585. deadlineUnix = timeutil.TimeStamp(deadline.Unix())
  586. }
  587. if err := issues_model.UpdateIssueDeadline(ctx, issue, deadlineUnix, ctx.Doer); err != nil {
  588. ctx.Error(http.StatusInternalServerError, "UpdateIssueDeadline", err)
  589. return
  590. }
  591. issue.DeadlineUnix = deadlineUnix
  592. }
  593. // Add/delete assignees
  594. // Deleting is done the GitHub way (quote from their api documentation):
  595. // https://developer.github.com/v3/issues/#edit-an-issue
  596. // "assignees" (array): Logins for Users to assign to this issue.
  597. // Pass one or more user logins to replace the set of assignees on this Issue.
  598. // Send an empty array ([]) to clear all assignees from the Issue.
  599. if ctx.Repo.CanWrite(unit.TypePullRequests) && (form.Assignees != nil || len(form.Assignee) > 0) {
  600. err = issue_service.UpdateAssignees(ctx, issue, form.Assignee, form.Assignees, ctx.Doer)
  601. if err != nil {
  602. if user_model.IsErrUserNotExist(err) {
  603. ctx.Error(http.StatusUnprocessableEntity, "", fmt.Sprintf("Assignee does not exist: [name: %s]", err))
  604. } else if errors.Is(err, user_model.ErrBlockedUser) {
  605. ctx.Error(http.StatusForbidden, "UpdateAssignees", err)
  606. } else {
  607. ctx.Error(http.StatusInternalServerError, "UpdateAssignees", err)
  608. }
  609. return
  610. }
  611. }
  612. if ctx.Repo.CanWrite(unit.TypePullRequests) && form.Milestone != 0 &&
  613. issue.MilestoneID != form.Milestone {
  614. oldMilestoneID := issue.MilestoneID
  615. issue.MilestoneID = form.Milestone
  616. if err = issue_service.ChangeMilestoneAssign(ctx, issue, ctx.Doer, oldMilestoneID); err != nil {
  617. ctx.Error(http.StatusInternalServerError, "ChangeMilestoneAssign", err)
  618. return
  619. }
  620. }
  621. if ctx.Repo.CanWrite(unit.TypePullRequests) && form.Labels != nil {
  622. labels, err := issues_model.GetLabelsInRepoByIDs(ctx, ctx.Repo.Repository.ID, form.Labels)
  623. if err != nil {
  624. ctx.Error(http.StatusInternalServerError, "GetLabelsInRepoByIDsError", err)
  625. return
  626. }
  627. if ctx.Repo.Owner.IsOrganization() {
  628. orgLabels, err := issues_model.GetLabelsInOrgByIDs(ctx, ctx.Repo.Owner.ID, form.Labels)
  629. if err != nil {
  630. ctx.Error(http.StatusInternalServerError, "GetLabelsInOrgByIDs", err)
  631. return
  632. }
  633. labels = append(labels, orgLabels...)
  634. }
  635. if err = issues_model.ReplaceIssueLabels(ctx, issue, labels, ctx.Doer); err != nil {
  636. ctx.Error(http.StatusInternalServerError, "ReplaceLabelsError", err)
  637. return
  638. }
  639. }
  640. if form.State != nil {
  641. if pr.HasMerged {
  642. ctx.Error(http.StatusPreconditionFailed, "MergedPRState", "cannot change state of this pull request, it was already merged")
  643. return
  644. }
  645. if err := issue_service.ChangeStatus(ctx, issue, ctx.Doer, "", api.StateClosed == api.StateType(*form.State)); err != nil {
  646. if issues_model.IsErrDependenciesLeft(err) {
  647. ctx.Error(http.StatusPreconditionFailed, "DependenciesLeft", "cannot close this pull request because it still has open dependencies")
  648. return
  649. }
  650. ctx.Error(http.StatusInternalServerError, "ChangeStatus", err)
  651. return
  652. }
  653. }
  654. // change pull target branch
  655. if !pr.HasMerged && len(form.Base) != 0 && form.Base != pr.BaseBranch {
  656. if !ctx.Repo.GitRepo.IsBranchExist(form.Base) {
  657. ctx.Error(http.StatusNotFound, "NewBaseBranchNotExist", fmt.Errorf("new base '%s' not exist", form.Base))
  658. return
  659. }
  660. if err := pull_service.ChangeTargetBranch(ctx, pr, ctx.Doer, form.Base); err != nil {
  661. if issues_model.IsErrPullRequestAlreadyExists(err) {
  662. ctx.Error(http.StatusConflict, "IsErrPullRequestAlreadyExists", err)
  663. return
  664. } else if issues_model.IsErrIssueIsClosed(err) {
  665. ctx.Error(http.StatusUnprocessableEntity, "IsErrIssueIsClosed", err)
  666. return
  667. } else if models.IsErrPullRequestHasMerged(err) {
  668. ctx.Error(http.StatusConflict, "IsErrPullRequestHasMerged", err)
  669. return
  670. }
  671. ctx.InternalServerError(err)
  672. return
  673. }
  674. notify_service.PullRequestChangeTargetBranch(ctx, ctx.Doer, pr, form.Base)
  675. }
  676. // update allow edits
  677. if form.AllowMaintainerEdit != nil {
  678. if err := pull_service.SetAllowEdits(ctx, ctx.Doer, pr, *form.AllowMaintainerEdit); err != nil {
  679. if errors.Is(pull_service.ErrUserHasNoPermissionForAction, err) {
  680. ctx.Error(http.StatusForbidden, "SetAllowEdits", fmt.Sprintf("SetAllowEdits: %s", err))
  681. return
  682. }
  683. ctx.ServerError("SetAllowEdits", err)
  684. return
  685. }
  686. }
  687. // Refetch from database
  688. pr, err = issues_model.GetPullRequestByIndex(ctx, ctx.Repo.Repository.ID, pr.Index)
  689. if err != nil {
  690. if issues_model.IsErrPullRequestNotExist(err) {
  691. ctx.NotFound()
  692. } else {
  693. ctx.Error(http.StatusInternalServerError, "GetPullRequestByIndex", err)
  694. }
  695. return
  696. }
  697. // TODO this should be 200, not 201
  698. ctx.JSON(http.StatusCreated, convert.ToAPIPullRequest(ctx, pr, ctx.Doer))
  699. }
  700. // IsPullRequestMerged checks if a PR exists given an index
  701. func IsPullRequestMerged(ctx *context.APIContext) {
  702. // swagger:operation GET /repos/{owner}/{repo}/pulls/{index}/merge repository repoPullRequestIsMerged
  703. // ---
  704. // summary: Check if a pull request has been merged
  705. // produces:
  706. // - application/json
  707. // parameters:
  708. // - name: owner
  709. // in: path
  710. // description: owner of the repo
  711. // type: string
  712. // required: true
  713. // - name: repo
  714. // in: path
  715. // description: name of the repo
  716. // type: string
  717. // required: true
  718. // - name: index
  719. // in: path
  720. // description: index of the pull request
  721. // type: integer
  722. // format: int64
  723. // required: true
  724. // responses:
  725. // "204":
  726. // description: pull request has been merged
  727. // "404":
  728. // description: pull request has not been merged
  729. pr, err := issues_model.GetPullRequestByIndex(ctx, ctx.Repo.Repository.ID, ctx.ParamsInt64(":index"))
  730. if err != nil {
  731. if issues_model.IsErrPullRequestNotExist(err) {
  732. ctx.NotFound()
  733. } else {
  734. ctx.Error(http.StatusInternalServerError, "GetPullRequestByIndex", err)
  735. }
  736. return
  737. }
  738. if pr.HasMerged {
  739. ctx.Status(http.StatusNoContent)
  740. }
  741. ctx.NotFound()
  742. }
  743. // MergePullRequest merges a PR given an index
  744. func MergePullRequest(ctx *context.APIContext) {
  745. // swagger:operation POST /repos/{owner}/{repo}/pulls/{index}/merge repository repoMergePullRequest
  746. // ---
  747. // summary: Merge a pull request
  748. // produces:
  749. // - application/json
  750. // parameters:
  751. // - name: owner
  752. // in: path
  753. // description: owner of the repo
  754. // type: string
  755. // required: true
  756. // - name: repo
  757. // in: path
  758. // description: name of the repo
  759. // type: string
  760. // required: true
  761. // - name: index
  762. // in: path
  763. // description: index of the pull request to merge
  764. // type: integer
  765. // format: int64
  766. // required: true
  767. // - name: body
  768. // in: body
  769. // schema:
  770. // $ref: "#/definitions/MergePullRequestOption"
  771. // responses:
  772. // "200":
  773. // "$ref": "#/responses/empty"
  774. // "404":
  775. // "$ref": "#/responses/notFound"
  776. // "405":
  777. // "$ref": "#/responses/empty"
  778. // "409":
  779. // "$ref": "#/responses/error"
  780. // "423":
  781. // "$ref": "#/responses/repoArchivedError"
  782. form := web.GetForm(ctx).(*forms.MergePullRequestForm)
  783. pr, err := issues_model.GetPullRequestByIndex(ctx, ctx.Repo.Repository.ID, ctx.ParamsInt64(":index"))
  784. if err != nil {
  785. if issues_model.IsErrPullRequestNotExist(err) {
  786. ctx.NotFound("GetPullRequestByIndex", err)
  787. } else {
  788. ctx.Error(http.StatusInternalServerError, "GetPullRequestByIndex", err)
  789. }
  790. return
  791. }
  792. if err := pr.LoadHeadRepo(ctx); err != nil {
  793. ctx.Error(http.StatusInternalServerError, "LoadHeadRepo", err)
  794. return
  795. }
  796. if err := pr.LoadIssue(ctx); err != nil {
  797. ctx.Error(http.StatusInternalServerError, "LoadIssue", err)
  798. return
  799. }
  800. pr.Issue.Repo = ctx.Repo.Repository
  801. if ctx.IsSigned {
  802. // Update issue-user.
  803. if err = activities_model.SetIssueReadBy(ctx, pr.Issue.ID, ctx.Doer.ID); err != nil {
  804. ctx.Error(http.StatusInternalServerError, "ReadBy", err)
  805. return
  806. }
  807. }
  808. manuallyMerged := repo_model.MergeStyle(form.Do) == repo_model.MergeStyleManuallyMerged
  809. mergeCheckType := pull_service.MergeCheckTypeGeneral
  810. if form.MergeWhenChecksSucceed {
  811. mergeCheckType = pull_service.MergeCheckTypeAuto
  812. }
  813. if manuallyMerged {
  814. mergeCheckType = pull_service.MergeCheckTypeManually
  815. }
  816. // start with merging by checking
  817. if err := pull_service.CheckPullMergable(ctx, ctx.Doer, &ctx.Repo.Permission, pr, mergeCheckType, form.ForceMerge); err != nil {
  818. if errors.Is(err, pull_service.ErrIsClosed) {
  819. ctx.NotFound()
  820. } else if errors.Is(err, pull_service.ErrUserNotAllowedToMerge) {
  821. ctx.Error(http.StatusMethodNotAllowed, "Merge", "User not allowed to merge PR")
  822. } else if errors.Is(err, pull_service.ErrHasMerged) {
  823. ctx.Error(http.StatusMethodNotAllowed, "PR already merged", "")
  824. } else if errors.Is(err, pull_service.ErrIsWorkInProgress) {
  825. ctx.Error(http.StatusMethodNotAllowed, "PR is a work in progress", "Work in progress PRs cannot be merged")
  826. } else if errors.Is(err, pull_service.ErrNotMergableState) {
  827. ctx.Error(http.StatusMethodNotAllowed, "PR not in mergeable state", "Please try again later")
  828. } else if models.IsErrDisallowedToMerge(err) {
  829. ctx.Error(http.StatusMethodNotAllowed, "PR is not ready to be merged", err)
  830. } else if asymkey_service.IsErrWontSign(err) {
  831. ctx.Error(http.StatusMethodNotAllowed, fmt.Sprintf("Protected branch %s requires signed commits but this merge would not be signed", pr.BaseBranch), err)
  832. } else {
  833. ctx.InternalServerError(err)
  834. }
  835. return
  836. }
  837. // handle manually-merged mark
  838. if manuallyMerged {
  839. if err := pull_service.MergedManually(ctx, pr, ctx.Doer, ctx.Repo.GitRepo, form.MergeCommitID); err != nil {
  840. if models.IsErrInvalidMergeStyle(err) {
  841. ctx.Error(http.StatusMethodNotAllowed, "Invalid merge style", fmt.Errorf("%s is not allowed an allowed merge style for this repository", repo_model.MergeStyle(form.Do)))
  842. return
  843. }
  844. if strings.Contains(err.Error(), "Wrong commit ID") {
  845. ctx.JSON(http.StatusConflict, err)
  846. return
  847. }
  848. ctx.Error(http.StatusInternalServerError, "Manually-Merged", err)
  849. return
  850. }
  851. ctx.Status(http.StatusOK)
  852. return
  853. }
  854. if len(form.Do) == 0 {
  855. form.Do = string(repo_model.MergeStyleMerge)
  856. }
  857. message := strings.TrimSpace(form.MergeTitleField)
  858. if len(message) == 0 {
  859. message, _, err = pull_service.GetDefaultMergeMessage(ctx, ctx.Repo.GitRepo, pr, repo_model.MergeStyle(form.Do))
  860. if err != nil {
  861. ctx.Error(http.StatusInternalServerError, "GetDefaultMergeMessage", err)
  862. return
  863. }
  864. }
  865. form.MergeMessageField = strings.TrimSpace(form.MergeMessageField)
  866. if len(form.MergeMessageField) > 0 {
  867. message += "\n\n" + form.MergeMessageField
  868. }
  869. if form.MergeWhenChecksSucceed {
  870. scheduled, err := automerge.ScheduleAutoMerge(ctx, ctx.Doer, pr, repo_model.MergeStyle(form.Do), message)
  871. if err != nil {
  872. if pull_model.IsErrAlreadyScheduledToAutoMerge(err) {
  873. ctx.Error(http.StatusConflict, "ScheduleAutoMerge", err)
  874. return
  875. }
  876. ctx.Error(http.StatusInternalServerError, "ScheduleAutoMerge", err)
  877. return
  878. } else if scheduled {
  879. // nothing more to do ...
  880. ctx.Status(http.StatusCreated)
  881. return
  882. }
  883. }
  884. if err := pull_service.Merge(ctx, pr, ctx.Doer, ctx.Repo.GitRepo, repo_model.MergeStyle(form.Do), form.HeadCommitID, message, false); err != nil {
  885. if models.IsErrInvalidMergeStyle(err) {
  886. ctx.Error(http.StatusMethodNotAllowed, "Invalid merge style", fmt.Errorf("%s is not allowed an allowed merge style for this repository", repo_model.MergeStyle(form.Do)))
  887. } else if models.IsErrMergeConflicts(err) {
  888. conflictError := err.(models.ErrMergeConflicts)
  889. ctx.JSON(http.StatusConflict, conflictError)
  890. } else if models.IsErrRebaseConflicts(err) {
  891. conflictError := err.(models.ErrRebaseConflicts)
  892. ctx.JSON(http.StatusConflict, conflictError)
  893. } else if models.IsErrMergeUnrelatedHistories(err) {
  894. conflictError := err.(models.ErrMergeUnrelatedHistories)
  895. ctx.JSON(http.StatusConflict, conflictError)
  896. } else if git.IsErrPushOutOfDate(err) {
  897. ctx.Error(http.StatusConflict, "Merge", "merge push out of date")
  898. } else if models.IsErrSHADoesNotMatch(err) {
  899. ctx.Error(http.StatusConflict, "Merge", "head out of date")
  900. } else if git.IsErrPushRejected(err) {
  901. errPushRej := err.(*git.ErrPushRejected)
  902. if len(errPushRej.Message) == 0 {
  903. ctx.Error(http.StatusConflict, "Merge", "PushRejected without remote error message")
  904. } else {
  905. ctx.Error(http.StatusConflict, "Merge", "PushRejected with remote message: "+errPushRej.Message)
  906. }
  907. } else {
  908. ctx.Error(http.StatusInternalServerError, "Merge", err)
  909. }
  910. return
  911. }
  912. log.Trace("Pull request merged: %d", pr.ID)
  913. if form.DeleteBranchAfterMerge {
  914. // Don't cleanup when there are other PR's that use this branch as head branch.
  915. exist, err := issues_model.HasUnmergedPullRequestsByHeadInfo(ctx, pr.HeadRepoID, pr.HeadBranch)
  916. if err != nil {
  917. ctx.ServerError("HasUnmergedPullRequestsByHeadInfo", err)
  918. return
  919. }
  920. if exist {
  921. ctx.Status(http.StatusOK)
  922. return
  923. }
  924. var headRepo *git.Repository
  925. if ctx.Repo != nil && ctx.Repo.Repository != nil && ctx.Repo.Repository.ID == pr.HeadRepoID && ctx.Repo.GitRepo != nil {
  926. headRepo = ctx.Repo.GitRepo
  927. } else {
  928. headRepo, err = gitrepo.OpenRepository(ctx, pr.HeadRepo)
  929. if err != nil {
  930. ctx.ServerError(fmt.Sprintf("OpenRepository[%s]", pr.HeadRepo.FullName()), err)
  931. return
  932. }
  933. defer headRepo.Close()
  934. }
  935. if err := pull_service.RetargetChildrenOnMerge(ctx, ctx.Doer, pr); err != nil {
  936. ctx.Error(http.StatusInternalServerError, "RetargetChildrenOnMerge", err)
  937. return
  938. }
  939. if err := repo_service.DeleteBranch(ctx, ctx.Doer, pr.HeadRepo, headRepo, pr.HeadBranch); err != nil {
  940. switch {
  941. case git.IsErrBranchNotExist(err):
  942. ctx.NotFound(err)
  943. case errors.Is(err, repo_service.ErrBranchIsDefault):
  944. ctx.Error(http.StatusForbidden, "DefaultBranch", fmt.Errorf("can not delete default branch"))
  945. case errors.Is(err, git_model.ErrBranchIsProtected):
  946. ctx.Error(http.StatusForbidden, "IsProtectedBranch", fmt.Errorf("branch protected"))
  947. default:
  948. ctx.Error(http.StatusInternalServerError, "DeleteBranch", err)
  949. }
  950. return
  951. }
  952. if err := issues_model.AddDeletePRBranchComment(ctx, ctx.Doer, pr.BaseRepo, pr.Issue.ID, pr.HeadBranch); err != nil {
  953. // Do not fail here as branch has already been deleted
  954. log.Error("DeleteBranch: %v", err)
  955. }
  956. }
  957. ctx.Status(http.StatusOK)
  958. }
  959. func parseCompareInfo(ctx *context.APIContext, form api.CreatePullRequestOption) (*user_model.User, *repo_model.Repository, *git.Repository, *git.CompareInfo, string, string) {
  960. baseRepo := ctx.Repo.Repository
  961. // Get compared branches information
  962. // format: <base branch>...[<head repo>:]<head branch>
  963. // base<-head: master...head:feature
  964. // same repo: master...feature
  965. // TODO: Validate form first?
  966. baseBranch := form.Base
  967. var (
  968. headUser *user_model.User
  969. headBranch string
  970. isSameRepo bool
  971. err error
  972. )
  973. // If there is no head repository, it means pull request between same repository.
  974. headInfos := strings.Split(form.Head, ":")
  975. if len(headInfos) == 1 {
  976. isSameRepo = true
  977. headUser = ctx.Repo.Owner
  978. headBranch = headInfos[0]
  979. } else if len(headInfos) == 2 {
  980. headUser, err = user_model.GetUserByName(ctx, headInfos[0])
  981. if err != nil {
  982. if user_model.IsErrUserNotExist(err) {
  983. ctx.NotFound("GetUserByName")
  984. } else {
  985. ctx.Error(http.StatusInternalServerError, "GetUserByName", err)
  986. }
  987. return nil, nil, nil, nil, "", ""
  988. }
  989. headBranch = headInfos[1]
  990. // The head repository can also point to the same repo
  991. isSameRepo = ctx.Repo.Owner.ID == headUser.ID
  992. } else {
  993. ctx.NotFound()
  994. return nil, nil, nil, nil, "", ""
  995. }
  996. ctx.Repo.PullRequest.SameRepo = isSameRepo
  997. log.Trace("Repo path: %q, base branch: %q, head branch: %q", ctx.Repo.GitRepo.Path, baseBranch, headBranch)
  998. // Check if base branch is valid.
  999. if !ctx.Repo.GitRepo.IsBranchExist(baseBranch) && !ctx.Repo.GitRepo.IsTagExist(baseBranch) {
  1000. ctx.NotFound("BaseNotExist")
  1001. return nil, nil, nil, nil, "", ""
  1002. }
  1003. // Check if current user has fork of repository or in the same repository.
  1004. headRepo := repo_model.GetForkedRepo(ctx, headUser.ID, baseRepo.ID)
  1005. if headRepo == nil && !isSameRepo {
  1006. log.Trace("parseCompareInfo[%d]: does not have fork or in same repository", baseRepo.ID)
  1007. ctx.NotFound("GetForkedRepo")
  1008. return nil, nil, nil, nil, "", ""
  1009. }
  1010. var headGitRepo *git.Repository
  1011. if isSameRepo {
  1012. headRepo = ctx.Repo.Repository
  1013. headGitRepo = ctx.Repo.GitRepo
  1014. } else {
  1015. headGitRepo, err = gitrepo.OpenRepository(ctx, headRepo)
  1016. if err != nil {
  1017. ctx.Error(http.StatusInternalServerError, "OpenRepository", err)
  1018. return nil, nil, nil, nil, "", ""
  1019. }
  1020. }
  1021. // user should have permission to read baseRepo's codes and pulls, NOT headRepo's
  1022. permBase, err := access_model.GetUserRepoPermission(ctx, baseRepo, ctx.Doer)
  1023. if err != nil {
  1024. headGitRepo.Close()
  1025. ctx.Error(http.StatusInternalServerError, "GetUserRepoPermission", err)
  1026. return nil, nil, nil, nil, "", ""
  1027. }
  1028. if !permBase.CanReadIssuesOrPulls(true) || !permBase.CanRead(unit.TypeCode) {
  1029. if log.IsTrace() {
  1030. log.Trace("Permission Denied: User %-v cannot create/read pull requests or cannot read code in Repo %-v\nUser in baseRepo has Permissions: %-+v",
  1031. ctx.Doer,
  1032. baseRepo,
  1033. permBase)
  1034. }
  1035. headGitRepo.Close()
  1036. ctx.NotFound("Can't read pulls or can't read UnitTypeCode")
  1037. return nil, nil, nil, nil, "", ""
  1038. }
  1039. // user should have permission to read headrepo's codes
  1040. permHead, err := access_model.GetUserRepoPermission(ctx, headRepo, ctx.Doer)
  1041. if err != nil {
  1042. headGitRepo.Close()
  1043. ctx.Error(http.StatusInternalServerError, "GetUserRepoPermission", err)
  1044. return nil, nil, nil, nil, "", ""
  1045. }
  1046. if !permHead.CanRead(unit.TypeCode) {
  1047. if log.IsTrace() {
  1048. log.Trace("Permission Denied: User: %-v cannot read code in Repo: %-v\nUser in headRepo has Permissions: %-+v",
  1049. ctx.Doer,
  1050. headRepo,
  1051. permHead)
  1052. }
  1053. headGitRepo.Close()
  1054. ctx.NotFound("Can't read headRepo UnitTypeCode")
  1055. return nil, nil, nil, nil, "", ""
  1056. }
  1057. // Check if head branch is valid.
  1058. if !headGitRepo.IsBranchExist(headBranch) && !headGitRepo.IsTagExist(headBranch) {
  1059. headGitRepo.Close()
  1060. ctx.NotFound()
  1061. return nil, nil, nil, nil, "", ""
  1062. }
  1063. compareInfo, err := headGitRepo.GetCompareInfo(repo_model.RepoPath(baseRepo.Owner.Name, baseRepo.Name), baseBranch, headBranch, false, false)
  1064. if err != nil {
  1065. headGitRepo.Close()
  1066. ctx.Error(http.StatusInternalServerError, "GetCompareInfo", err)
  1067. return nil, nil, nil, nil, "", ""
  1068. }
  1069. return headUser, headRepo, headGitRepo, compareInfo, baseBranch, headBranch
  1070. }
  1071. // UpdatePullRequest merge PR's baseBranch into headBranch
  1072. func UpdatePullRequest(ctx *context.APIContext) {
  1073. // swagger:operation POST /repos/{owner}/{repo}/pulls/{index}/update repository repoUpdatePullRequest
  1074. // ---
  1075. // summary: Merge PR's baseBranch into headBranch
  1076. // produces:
  1077. // - application/json
  1078. // parameters:
  1079. // - name: owner
  1080. // in: path
  1081. // description: owner of the repo
  1082. // type: string
  1083. // required: true
  1084. // - name: repo
  1085. // in: path
  1086. // description: name of the repo
  1087. // type: string
  1088. // required: true
  1089. // - name: index
  1090. // in: path
  1091. // description: index of the pull request to get
  1092. // type: integer
  1093. // format: int64
  1094. // required: true
  1095. // - name: style
  1096. // in: query
  1097. // description: how to update pull request
  1098. // type: string
  1099. // enum: [merge, rebase]
  1100. // responses:
  1101. // "200":
  1102. // "$ref": "#/responses/empty"
  1103. // "403":
  1104. // "$ref": "#/responses/forbidden"
  1105. // "404":
  1106. // "$ref": "#/responses/notFound"
  1107. // "409":
  1108. // "$ref": "#/responses/error"
  1109. // "422":
  1110. // "$ref": "#/responses/validationError"
  1111. pr, err := issues_model.GetPullRequestByIndex(ctx, ctx.Repo.Repository.ID, ctx.ParamsInt64(":index"))
  1112. if err != nil {
  1113. if issues_model.IsErrPullRequestNotExist(err) {
  1114. ctx.NotFound()
  1115. } else {
  1116. ctx.Error(http.StatusInternalServerError, "GetPullRequestByIndex", err)
  1117. }
  1118. return
  1119. }
  1120. if pr.HasMerged {
  1121. ctx.Error(http.StatusUnprocessableEntity, "UpdatePullRequest", err)
  1122. return
  1123. }
  1124. if err = pr.LoadIssue(ctx); err != nil {
  1125. ctx.Error(http.StatusInternalServerError, "LoadIssue", err)
  1126. return
  1127. }
  1128. if pr.Issue.IsClosed {
  1129. ctx.Error(http.StatusUnprocessableEntity, "UpdatePullRequest", err)
  1130. return
  1131. }
  1132. if err = pr.LoadBaseRepo(ctx); err != nil {
  1133. ctx.Error(http.StatusInternalServerError, "LoadBaseRepo", err)
  1134. return
  1135. }
  1136. if err = pr.LoadHeadRepo(ctx); err != nil {
  1137. ctx.Error(http.StatusInternalServerError, "LoadHeadRepo", err)
  1138. return
  1139. }
  1140. rebase := ctx.FormString("style") == "rebase"
  1141. allowedUpdateByMerge, allowedUpdateByRebase, err := pull_service.IsUserAllowedToUpdate(ctx, pr, ctx.Doer)
  1142. if err != nil {
  1143. ctx.Error(http.StatusInternalServerError, "IsUserAllowedToMerge", err)
  1144. return
  1145. }
  1146. if (!allowedUpdateByMerge && !rebase) || (rebase && !allowedUpdateByRebase) {
  1147. ctx.Status(http.StatusForbidden)
  1148. return
  1149. }
  1150. // default merge commit message
  1151. message := fmt.Sprintf("Merge branch '%s' into %s", pr.BaseBranch, pr.HeadBranch)
  1152. if err = pull_service.Update(ctx, pr, ctx.Doer, message, rebase); err != nil {
  1153. if models.IsErrMergeConflicts(err) {
  1154. ctx.Error(http.StatusConflict, "Update", "merge failed because of conflict")
  1155. return
  1156. } else if models.IsErrRebaseConflicts(err) {
  1157. ctx.Error(http.StatusConflict, "Update", "rebase failed because of conflict")
  1158. return
  1159. }
  1160. ctx.Error(http.StatusInternalServerError, "pull_service.Update", err)
  1161. return
  1162. }
  1163. ctx.Status(http.StatusOK)
  1164. }
  1165. // MergePullRequest cancel an auto merge scheduled for a given PullRequest by index
  1166. func CancelScheduledAutoMerge(ctx *context.APIContext) {
  1167. // swagger:operation DELETE /repos/{owner}/{repo}/pulls/{index}/merge repository repoCancelScheduledAutoMerge
  1168. // ---
  1169. // summary: Cancel the scheduled auto merge for the given pull request
  1170. // produces:
  1171. // - application/json
  1172. // parameters:
  1173. // - name: owner
  1174. // in: path
  1175. // description: owner of the repo
  1176. // type: string
  1177. // required: true
  1178. // - name: repo
  1179. // in: path
  1180. // description: name of the repo
  1181. // type: string
  1182. // required: true
  1183. // - name: index
  1184. // in: path
  1185. // description: index of the pull request to merge
  1186. // type: integer
  1187. // format: int64
  1188. // required: true
  1189. // responses:
  1190. // "204":
  1191. // "$ref": "#/responses/empty"
  1192. // "403":
  1193. // "$ref": "#/responses/forbidden"
  1194. // "404":
  1195. // "$ref": "#/responses/notFound"
  1196. // "423":
  1197. // "$ref": "#/responses/repoArchivedError"
  1198. pullIndex := ctx.ParamsInt64(":index")
  1199. pull, err := issues_model.GetPullRequestByIndex(ctx, ctx.Repo.Repository.ID, pullIndex)
  1200. if err != nil {
  1201. if issues_model.IsErrPullRequestNotExist(err) {
  1202. ctx.NotFound()
  1203. return
  1204. }
  1205. ctx.InternalServerError(err)
  1206. return
  1207. }
  1208. exist, autoMerge, err := pull_model.GetScheduledMergeByPullID(ctx, pull.ID)
  1209. if err != nil {
  1210. ctx.InternalServerError(err)
  1211. return
  1212. }
  1213. if !exist {
  1214. ctx.NotFound()
  1215. return
  1216. }
  1217. if ctx.Doer.ID != autoMerge.DoerID {
  1218. allowed, err := access_model.IsUserRepoAdmin(ctx, ctx.Repo.Repository, ctx.Doer)
  1219. if err != nil {
  1220. ctx.InternalServerError(err)
  1221. return
  1222. }
  1223. if !allowed {
  1224. ctx.Error(http.StatusForbidden, "No permission to cancel", "user has no permission to cancel the scheduled auto merge")
  1225. return
  1226. }
  1227. }
  1228. if err := automerge.RemoveScheduledAutoMerge(ctx, ctx.Doer, pull); err != nil {
  1229. ctx.InternalServerError(err)
  1230. } else {
  1231. ctx.Status(http.StatusNoContent)
  1232. }
  1233. }
  1234. // GetPullRequestCommits gets all commits associated with a given PR
  1235. func GetPullRequestCommits(ctx *context.APIContext) {
  1236. // swagger:operation GET /repos/{owner}/{repo}/pulls/{index}/commits repository repoGetPullRequestCommits
  1237. // ---
  1238. // summary: Get commits for a pull request
  1239. // produces:
  1240. // - application/json
  1241. // parameters:
  1242. // - name: owner
  1243. // in: path
  1244. // description: owner of the repo
  1245. // type: string
  1246. // required: true
  1247. // - name: repo
  1248. // in: path
  1249. // description: name of the repo
  1250. // type: string
  1251. // required: true
  1252. // - name: index
  1253. // in: path
  1254. // description: index of the pull request to get
  1255. // type: integer
  1256. // format: int64
  1257. // required: true
  1258. // - name: page
  1259. // in: query
  1260. // description: page number of results to return (1-based)
  1261. // type: integer
  1262. // - name: limit
  1263. // in: query
  1264. // description: page size of results
  1265. // type: integer
  1266. // - name: verification
  1267. // in: query
  1268. // description: include verification for every commit (disable for speedup, default 'true')
  1269. // type: boolean
  1270. // - name: files
  1271. // in: query
  1272. // description: include a list of affected files for every commit (disable for speedup, default 'true')
  1273. // type: boolean
  1274. // responses:
  1275. // "200":
  1276. // "$ref": "#/responses/CommitList"
  1277. // "404":
  1278. // "$ref": "#/responses/notFound"
  1279. pr, err := issues_model.GetPullRequestByIndex(ctx, ctx.Repo.Repository.ID, ctx.ParamsInt64(":index"))
  1280. if err != nil {
  1281. if issues_model.IsErrPullRequestNotExist(err) {
  1282. ctx.NotFound()
  1283. } else {
  1284. ctx.Error(http.StatusInternalServerError, "GetPullRequestByIndex", err)
  1285. }
  1286. return
  1287. }
  1288. if err := pr.LoadBaseRepo(ctx); err != nil {
  1289. ctx.InternalServerError(err)
  1290. return
  1291. }
  1292. var prInfo *git.CompareInfo
  1293. baseGitRepo, closer, err := gitrepo.RepositoryFromContextOrOpen(ctx, pr.BaseRepo)
  1294. if err != nil {
  1295. ctx.ServerError("OpenRepository", err)
  1296. return
  1297. }
  1298. defer closer.Close()
  1299. if pr.HasMerged {
  1300. prInfo, err = baseGitRepo.GetCompareInfo(pr.BaseRepo.RepoPath(), pr.MergeBase, pr.GetGitRefName(), false, false)
  1301. } else {
  1302. prInfo, err = baseGitRepo.GetCompareInfo(pr.BaseRepo.RepoPath(), pr.BaseBranch, pr.GetGitRefName(), false, false)
  1303. }
  1304. if err != nil {
  1305. ctx.ServerError("GetCompareInfo", err)
  1306. return
  1307. }
  1308. commits := prInfo.Commits
  1309. listOptions := utils.GetListOptions(ctx)
  1310. totalNumberOfCommits := len(commits)
  1311. totalNumberOfPages := int(math.Ceil(float64(totalNumberOfCommits) / float64(listOptions.PageSize)))
  1312. userCache := make(map[string]*user_model.User)
  1313. start, limit := listOptions.GetSkipTake()
  1314. limit = min(limit, totalNumberOfCommits-start)
  1315. limit = max(limit, 0)
  1316. verification := ctx.FormString("verification") == "" || ctx.FormBool("verification")
  1317. files := ctx.FormString("files") == "" || ctx.FormBool("files")
  1318. apiCommits := make([]*api.Commit, 0, limit)
  1319. for i := start; i < start+limit; i++ {
  1320. apiCommit, err := convert.ToCommit(ctx, ctx.Repo.Repository, baseGitRepo, commits[i], userCache,
  1321. convert.ToCommitOptions{
  1322. Stat: true,
  1323. Verification: verification,
  1324. Files: files,
  1325. })
  1326. if err != nil {
  1327. ctx.ServerError("toCommit", err)
  1328. return
  1329. }
  1330. apiCommits = append(apiCommits, apiCommit)
  1331. }
  1332. ctx.SetLinkHeader(totalNumberOfCommits, listOptions.PageSize)
  1333. ctx.SetTotalCountHeader(int64(totalNumberOfCommits))
  1334. ctx.RespHeader().Set("X-Page", strconv.Itoa(listOptions.Page))
  1335. ctx.RespHeader().Set("X-PerPage", strconv.Itoa(listOptions.PageSize))
  1336. ctx.RespHeader().Set("X-PageCount", strconv.Itoa(totalNumberOfPages))
  1337. ctx.RespHeader().Set("X-HasMore", strconv.FormatBool(listOptions.Page < totalNumberOfPages))
  1338. ctx.AppendAccessControlExposeHeaders("X-Page", "X-PerPage", "X-PageCount", "X-HasMore")
  1339. ctx.JSON(http.StatusOK, &apiCommits)
  1340. }
  1341. // GetPullRequestFiles gets all changed files associated with a given PR
  1342. func GetPullRequestFiles(ctx *context.APIContext) {
  1343. // swagger:operation GET /repos/{owner}/{repo}/pulls/{index}/files repository repoGetPullRequestFiles
  1344. // ---
  1345. // summary: Get changed files for a pull request
  1346. // produces:
  1347. // - application/json
  1348. // parameters:
  1349. // - name: owner
  1350. // in: path
  1351. // description: owner of the repo
  1352. // type: string
  1353. // required: true
  1354. // - name: repo
  1355. // in: path
  1356. // description: name of the repo
  1357. // type: string
  1358. // required: true
  1359. // - name: index
  1360. // in: path
  1361. // description: index of the pull request to get
  1362. // type: integer
  1363. // format: int64
  1364. // required: true
  1365. // - name: skip-to
  1366. // in: query
  1367. // description: skip to given file
  1368. // type: string
  1369. // - name: whitespace
  1370. // in: query
  1371. // description: whitespace behavior
  1372. // type: string
  1373. // enum: [ignore-all, ignore-change, ignore-eol, show-all]
  1374. // - name: page
  1375. // in: query
  1376. // description: page number of results to return (1-based)
  1377. // type: integer
  1378. // - name: limit
  1379. // in: query
  1380. // description: page size of results
  1381. // type: integer
  1382. // responses:
  1383. // "200":
  1384. // "$ref": "#/responses/ChangedFileList"
  1385. // "404":
  1386. // "$ref": "#/responses/notFound"
  1387. pr, err := issues_model.GetPullRequestByIndex(ctx, ctx.Repo.Repository.ID, ctx.ParamsInt64(":index"))
  1388. if err != nil {
  1389. if issues_model.IsErrPullRequestNotExist(err) {
  1390. ctx.NotFound()
  1391. } else {
  1392. ctx.Error(http.StatusInternalServerError, "GetPullRequestByIndex", err)
  1393. }
  1394. return
  1395. }
  1396. if err := pr.LoadBaseRepo(ctx); err != nil {
  1397. ctx.InternalServerError(err)
  1398. return
  1399. }
  1400. if err := pr.LoadHeadRepo(ctx); err != nil {
  1401. ctx.InternalServerError(err)
  1402. return
  1403. }
  1404. baseGitRepo := ctx.Repo.GitRepo
  1405. var prInfo *git.CompareInfo
  1406. if pr.HasMerged {
  1407. prInfo, err = baseGitRepo.GetCompareInfo(pr.BaseRepo.RepoPath(), pr.MergeBase, pr.GetGitRefName(), true, false)
  1408. } else {
  1409. prInfo, err = baseGitRepo.GetCompareInfo(pr.BaseRepo.RepoPath(), pr.BaseBranch, pr.GetGitRefName(), true, false)
  1410. }
  1411. if err != nil {
  1412. ctx.ServerError("GetCompareInfo", err)
  1413. return
  1414. }
  1415. headCommitID, err := baseGitRepo.GetRefCommitID(pr.GetGitRefName())
  1416. if err != nil {
  1417. ctx.ServerError("GetRefCommitID", err)
  1418. return
  1419. }
  1420. startCommitID := prInfo.MergeBase
  1421. endCommitID := headCommitID
  1422. maxLines := setting.Git.MaxGitDiffLines
  1423. // FIXME: If there are too many files in the repo, may cause some unpredictable issues.
  1424. diff, err := gitdiff.GetDiff(ctx, baseGitRepo,
  1425. &gitdiff.DiffOptions{
  1426. BeforeCommitID: startCommitID,
  1427. AfterCommitID: endCommitID,
  1428. SkipTo: ctx.FormString("skip-to"),
  1429. MaxLines: maxLines,
  1430. MaxLineCharacters: setting.Git.MaxGitDiffLineCharacters,
  1431. MaxFiles: -1, // GetDiff() will return all files
  1432. WhitespaceBehavior: gitdiff.GetWhitespaceFlag(ctx.FormString("whitespace")),
  1433. })
  1434. if err != nil {
  1435. ctx.ServerError("GetDiff", err)
  1436. return
  1437. }
  1438. listOptions := utils.GetListOptions(ctx)
  1439. totalNumberOfFiles := diff.NumFiles
  1440. totalNumberOfPages := int(math.Ceil(float64(totalNumberOfFiles) / float64(listOptions.PageSize)))
  1441. start, limit := listOptions.GetSkipTake()
  1442. limit = min(limit, totalNumberOfFiles-start)
  1443. limit = max(limit, 0)
  1444. apiFiles := make([]*api.ChangedFile, 0, limit)
  1445. for i := start; i < start+limit; i++ {
  1446. apiFiles = append(apiFiles, convert.ToChangedFile(diff.Files[i], pr.HeadRepo, endCommitID))
  1447. }
  1448. ctx.SetLinkHeader(totalNumberOfFiles, listOptions.PageSize)
  1449. ctx.SetTotalCountHeader(int64(totalNumberOfFiles))
  1450. ctx.RespHeader().Set("X-Page", strconv.Itoa(listOptions.Page))
  1451. ctx.RespHeader().Set("X-PerPage", strconv.Itoa(listOptions.PageSize))
  1452. ctx.RespHeader().Set("X-PageCount", strconv.Itoa(totalNumberOfPages))
  1453. ctx.RespHeader().Set("X-HasMore", strconv.FormatBool(listOptions.Page < totalNumberOfPages))
  1454. ctx.AppendAccessControlExposeHeaders("X-Page", "X-PerPage", "X-PageCount", "X-HasMore")
  1455. ctx.JSON(http.StatusOK, &apiFiles)
  1456. }