gitea源码

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