Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597
  1. // Copyright 2018 The Gitea Authors.
  2. // Copyright 2014 The Gogs Authors.
  3. // All rights reserved.
  4. // SPDX-License-Identifier: MIT
  5. package repo
  6. import (
  7. "errors"
  8. "fmt"
  9. "html"
  10. "net/http"
  11. "strconv"
  12. "strings"
  13. "time"
  14. "code.gitea.io/gitea/models"
  15. activities_model "code.gitea.io/gitea/models/activities"
  16. "code.gitea.io/gitea/models/db"
  17. git_model "code.gitea.io/gitea/models/git"
  18. issues_model "code.gitea.io/gitea/models/issues"
  19. access_model "code.gitea.io/gitea/models/perm/access"
  20. pull_model "code.gitea.io/gitea/models/pull"
  21. repo_model "code.gitea.io/gitea/models/repo"
  22. "code.gitea.io/gitea/models/unit"
  23. user_model "code.gitea.io/gitea/models/user"
  24. "code.gitea.io/gitea/modules/base"
  25. "code.gitea.io/gitea/modules/emoji"
  26. "code.gitea.io/gitea/modules/git"
  27. "code.gitea.io/gitea/modules/gitrepo"
  28. issue_template "code.gitea.io/gitea/modules/issue/template"
  29. "code.gitea.io/gitea/modules/log"
  30. "code.gitea.io/gitea/modules/setting"
  31. "code.gitea.io/gitea/modules/util"
  32. "code.gitea.io/gitea/modules/web"
  33. "code.gitea.io/gitea/routers/utils"
  34. asymkey_service "code.gitea.io/gitea/services/asymkey"
  35. "code.gitea.io/gitea/services/automerge"
  36. "code.gitea.io/gitea/services/context"
  37. "code.gitea.io/gitea/services/context/upload"
  38. "code.gitea.io/gitea/services/forms"
  39. "code.gitea.io/gitea/services/gitdiff"
  40. notify_service "code.gitea.io/gitea/services/notify"
  41. pull_service "code.gitea.io/gitea/services/pull"
  42. repo_service "code.gitea.io/gitea/services/repository"
  43. user_service "code.gitea.io/gitea/services/user"
  44. "github.com/gobwas/glob"
  45. )
  46. const (
  47. tplCompareDiff base.TplName = "repo/diff/compare"
  48. tplPullCommits base.TplName = "repo/pulls/commits"
  49. tplPullFiles base.TplName = "repo/pulls/files"
  50. pullRequestTemplateKey = "PullRequestTemplate"
  51. )
  52. var pullRequestTemplateCandidates = []string{
  53. "PULL_REQUEST_TEMPLATE.md",
  54. "PULL_REQUEST_TEMPLATE.yaml",
  55. "PULL_REQUEST_TEMPLATE.yml",
  56. "pull_request_template.md",
  57. "pull_request_template.yaml",
  58. "pull_request_template.yml",
  59. ".gitea/PULL_REQUEST_TEMPLATE.md",
  60. ".gitea/PULL_REQUEST_TEMPLATE.yaml",
  61. ".gitea/PULL_REQUEST_TEMPLATE.yml",
  62. ".gitea/pull_request_template.md",
  63. ".gitea/pull_request_template.yaml",
  64. ".gitea/pull_request_template.yml",
  65. ".github/PULL_REQUEST_TEMPLATE.md",
  66. ".github/PULL_REQUEST_TEMPLATE.yaml",
  67. ".github/PULL_REQUEST_TEMPLATE.yml",
  68. ".github/pull_request_template.md",
  69. ".github/pull_request_template.yaml",
  70. ".github/pull_request_template.yml",
  71. }
  72. func getRepository(ctx *context.Context, repoID int64) *repo_model.Repository {
  73. repo, err := repo_model.GetRepositoryByID(ctx, repoID)
  74. if err != nil {
  75. if repo_model.IsErrRepoNotExist(err) {
  76. ctx.NotFound("GetRepositoryByID", nil)
  77. } else {
  78. ctx.ServerError("GetRepositoryByID", err)
  79. }
  80. return nil
  81. }
  82. perm, err := access_model.GetUserRepoPermission(ctx, repo, ctx.Doer)
  83. if err != nil {
  84. ctx.ServerError("GetUserRepoPermission", err)
  85. return nil
  86. }
  87. if !perm.CanRead(unit.TypeCode) {
  88. log.Trace("Permission Denied: User %-v cannot read %-v of repo %-v\n"+
  89. "User in repo has Permissions: %-+v",
  90. ctx.Doer,
  91. unit.TypeCode,
  92. ctx.Repo,
  93. perm)
  94. ctx.NotFound("getRepository", nil)
  95. return nil
  96. }
  97. return repo
  98. }
  99. func getPullInfo(ctx *context.Context) (issue *issues_model.Issue, ok bool) {
  100. issue, err := issues_model.GetIssueByIndex(ctx, ctx.Repo.Repository.ID, ctx.ParamsInt64(":index"))
  101. if err != nil {
  102. if issues_model.IsErrIssueNotExist(err) {
  103. ctx.NotFound("GetIssueByIndex", err)
  104. } else {
  105. ctx.ServerError("GetIssueByIndex", err)
  106. }
  107. return nil, false
  108. }
  109. if err = issue.LoadPoster(ctx); err != nil {
  110. ctx.ServerError("LoadPoster", err)
  111. return nil, false
  112. }
  113. if err := issue.LoadRepo(ctx); err != nil {
  114. ctx.ServerError("LoadRepo", err)
  115. return nil, false
  116. }
  117. ctx.Data["Title"] = fmt.Sprintf("#%d - %s", issue.Index, emoji.ReplaceAliases(issue.Title))
  118. ctx.Data["Issue"] = issue
  119. if !issue.IsPull {
  120. ctx.NotFound("ViewPullCommits", nil)
  121. return nil, false
  122. }
  123. if err = issue.LoadPullRequest(ctx); err != nil {
  124. ctx.ServerError("LoadPullRequest", err)
  125. return nil, false
  126. }
  127. if err = issue.PullRequest.LoadHeadRepo(ctx); err != nil {
  128. ctx.ServerError("LoadHeadRepo", err)
  129. return nil, false
  130. }
  131. if ctx.IsSigned {
  132. // Update issue-user.
  133. if err = activities_model.SetIssueReadBy(ctx, issue.ID, ctx.Doer.ID); err != nil {
  134. ctx.ServerError("ReadBy", err)
  135. return nil, false
  136. }
  137. }
  138. return issue, true
  139. }
  140. func setMergeTarget(ctx *context.Context, pull *issues_model.PullRequest) {
  141. if ctx.Repo.Owner.Name == pull.MustHeadUserName(ctx) {
  142. ctx.Data["HeadTarget"] = pull.HeadBranch
  143. } else if pull.HeadRepo == nil {
  144. ctx.Data["HeadTarget"] = pull.MustHeadUserName(ctx) + ":" + pull.HeadBranch
  145. } else {
  146. ctx.Data["HeadTarget"] = pull.MustHeadUserName(ctx) + "/" + pull.HeadRepo.Name + ":" + pull.HeadBranch
  147. }
  148. ctx.Data["BaseTarget"] = pull.BaseBranch
  149. ctx.Data["HeadBranchLink"] = pull.GetHeadBranchLink(ctx)
  150. ctx.Data["BaseBranchLink"] = pull.GetBaseBranchLink(ctx)
  151. }
  152. // GetPullDiffStats get Pull Requests diff stats
  153. func GetPullDiffStats(ctx *context.Context) {
  154. issue, ok := getPullInfo(ctx)
  155. if !ok {
  156. return
  157. }
  158. pull := issue.PullRequest
  159. mergeBaseCommitID := GetMergedBaseCommitID(ctx, issue)
  160. if mergeBaseCommitID == "" {
  161. ctx.NotFound("PullFiles", nil)
  162. return
  163. }
  164. headCommitID, err := ctx.Repo.GitRepo.GetRefCommitID(pull.GetGitRefName())
  165. if err != nil {
  166. ctx.ServerError("GetRefCommitID", err)
  167. return
  168. }
  169. diffOptions := &gitdiff.DiffOptions{
  170. BeforeCommitID: mergeBaseCommitID,
  171. AfterCommitID: headCommitID,
  172. MaxLines: setting.Git.MaxGitDiffLines,
  173. MaxLineCharacters: setting.Git.MaxGitDiffLineCharacters,
  174. MaxFiles: setting.Git.MaxGitDiffFiles,
  175. WhitespaceBehavior: gitdiff.GetWhitespaceFlag(ctx.Data["WhitespaceBehavior"].(string)),
  176. }
  177. diff, err := gitdiff.GetPullDiffStats(ctx.Repo.GitRepo, diffOptions)
  178. if err != nil {
  179. ctx.ServerError("GetPullDiffStats", err)
  180. return
  181. }
  182. ctx.Data["Diff"] = diff
  183. }
  184. func GetMergedBaseCommitID(ctx *context.Context, issue *issues_model.Issue) string {
  185. pull := issue.PullRequest
  186. var baseCommit string
  187. // Some migrated PR won't have any Base SHA and lose history, try to get one
  188. if pull.MergeBase == "" {
  189. var commitSHA, parentCommit string
  190. // If there is a head or a patch file, and it is readable, grab info
  191. commitSHA, err := ctx.Repo.GitRepo.GetRefCommitID(pull.GetGitRefName())
  192. if err != nil {
  193. // Head File does not exist, try the patch
  194. commitSHA, err = ctx.Repo.GitRepo.ReadPatchCommit(pull.Index)
  195. if err == nil {
  196. // Recreate pull head in files for next time
  197. if err := ctx.Repo.GitRepo.SetReference(pull.GetGitRefName(), commitSHA); err != nil {
  198. log.Error("Could not write head file", err)
  199. }
  200. } else {
  201. // There is no history available
  202. log.Trace("No history file available for PR %d", pull.Index)
  203. }
  204. }
  205. if commitSHA != "" {
  206. // Get immediate parent of the first commit in the patch, grab history back
  207. parentCommit, _, err = git.NewCommand(ctx, "rev-list", "-1", "--skip=1").AddDynamicArguments(commitSHA).RunStdString(&git.RunOpts{Dir: ctx.Repo.GitRepo.Path})
  208. if err == nil {
  209. parentCommit = strings.TrimSpace(parentCommit)
  210. }
  211. // Special case on Git < 2.25 that doesn't fail on immediate empty history
  212. if err != nil || parentCommit == "" {
  213. log.Info("No known parent commit for PR %d, error: %v", pull.Index, err)
  214. // bring at least partial history if it can work
  215. parentCommit = commitSHA
  216. }
  217. }
  218. baseCommit = parentCommit
  219. } else {
  220. // Keep an empty history or original commit
  221. baseCommit = pull.MergeBase
  222. }
  223. return baseCommit
  224. }
  225. // PrepareMergedViewPullInfo show meta information for a merged pull request view page
  226. func PrepareMergedViewPullInfo(ctx *context.Context, issue *issues_model.Issue) *git.CompareInfo {
  227. pull := issue.PullRequest
  228. setMergeTarget(ctx, pull)
  229. ctx.Data["HasMerged"] = true
  230. baseCommit := GetMergedBaseCommitID(ctx, issue)
  231. compareInfo, err := ctx.Repo.GitRepo.GetCompareInfo(ctx.Repo.Repository.RepoPath(),
  232. baseCommit, pull.GetGitRefName(), false, false)
  233. if err != nil {
  234. if strings.Contains(err.Error(), "fatal: Not a valid object name") || strings.Contains(err.Error(), "unknown revision or path not in the working tree") {
  235. ctx.Data["IsPullRequestBroken"] = true
  236. ctx.Data["BaseTarget"] = pull.BaseBranch
  237. ctx.Data["NumCommits"] = 0
  238. ctx.Data["NumFiles"] = 0
  239. return nil
  240. }
  241. ctx.ServerError("GetCompareInfo", err)
  242. return nil
  243. }
  244. ctx.Data["NumCommits"] = len(compareInfo.Commits)
  245. ctx.Data["NumFiles"] = compareInfo.NumFiles
  246. if len(compareInfo.Commits) != 0 {
  247. sha := compareInfo.Commits[0].ID.String()
  248. commitStatuses, _, err := git_model.GetLatestCommitStatus(ctx, ctx.Repo.Repository.ID, sha, db.ListOptionsAll)
  249. if err != nil {
  250. ctx.ServerError("GetLatestCommitStatus", err)
  251. return nil
  252. }
  253. if len(commitStatuses) != 0 {
  254. ctx.Data["LatestCommitStatuses"] = commitStatuses
  255. ctx.Data["LatestCommitStatus"] = git_model.CalcCommitStatus(commitStatuses)
  256. }
  257. }
  258. return compareInfo
  259. }
  260. // PrepareViewPullInfo show meta information for a pull request preview page
  261. func PrepareViewPullInfo(ctx *context.Context, issue *issues_model.Issue) *git.CompareInfo {
  262. ctx.Data["PullRequestWorkInProgressPrefixes"] = setting.Repository.PullRequest.WorkInProgressPrefixes
  263. repo := ctx.Repo.Repository
  264. pull := issue.PullRequest
  265. if err := pull.LoadHeadRepo(ctx); err != nil {
  266. ctx.ServerError("LoadHeadRepo", err)
  267. return nil
  268. }
  269. if err := pull.LoadBaseRepo(ctx); err != nil {
  270. ctx.ServerError("LoadBaseRepo", err)
  271. return nil
  272. }
  273. setMergeTarget(ctx, pull)
  274. pb, err := git_model.GetFirstMatchProtectedBranchRule(ctx, repo.ID, pull.BaseBranch)
  275. if err != nil {
  276. ctx.ServerError("LoadProtectedBranch", err)
  277. return nil
  278. }
  279. ctx.Data["EnableStatusCheck"] = pb != nil && pb.EnableStatusCheck
  280. var baseGitRepo *git.Repository
  281. if pull.BaseRepoID == ctx.Repo.Repository.ID && ctx.Repo.GitRepo != nil {
  282. baseGitRepo = ctx.Repo.GitRepo
  283. } else {
  284. baseGitRepo, err := gitrepo.OpenRepository(ctx, pull.BaseRepo)
  285. if err != nil {
  286. ctx.ServerError("OpenRepository", err)
  287. return nil
  288. }
  289. defer baseGitRepo.Close()
  290. }
  291. if !baseGitRepo.IsBranchExist(pull.BaseBranch) {
  292. ctx.Data["IsPullRequestBroken"] = true
  293. ctx.Data["BaseTarget"] = pull.BaseBranch
  294. ctx.Data["HeadTarget"] = pull.HeadBranch
  295. sha, err := baseGitRepo.GetRefCommitID(pull.GetGitRefName())
  296. if err != nil {
  297. ctx.ServerError(fmt.Sprintf("GetRefCommitID(%s)", pull.GetGitRefName()), err)
  298. return nil
  299. }
  300. commitStatuses, _, err := git_model.GetLatestCommitStatus(ctx, repo.ID, sha, db.ListOptionsAll)
  301. if err != nil {
  302. ctx.ServerError("GetLatestCommitStatus", err)
  303. return nil
  304. }
  305. if len(commitStatuses) > 0 {
  306. ctx.Data["LatestCommitStatuses"] = commitStatuses
  307. ctx.Data["LatestCommitStatus"] = git_model.CalcCommitStatus(commitStatuses)
  308. }
  309. compareInfo, err := baseGitRepo.GetCompareInfo(pull.BaseRepo.RepoPath(),
  310. pull.MergeBase, pull.GetGitRefName(), false, false)
  311. if err != nil {
  312. if strings.Contains(err.Error(), "fatal: Not a valid object name") {
  313. ctx.Data["IsPullRequestBroken"] = true
  314. ctx.Data["BaseTarget"] = pull.BaseBranch
  315. ctx.Data["NumCommits"] = 0
  316. ctx.Data["NumFiles"] = 0
  317. return nil
  318. }
  319. ctx.ServerError("GetCompareInfo", err)
  320. return nil
  321. }
  322. ctx.Data["NumCommits"] = len(compareInfo.Commits)
  323. ctx.Data["NumFiles"] = compareInfo.NumFiles
  324. return compareInfo
  325. }
  326. var headBranchExist bool
  327. var headBranchSha string
  328. // HeadRepo may be missing
  329. if pull.HeadRepo != nil {
  330. headGitRepo, err := gitrepo.OpenRepository(ctx, pull.HeadRepo)
  331. if err != nil {
  332. ctx.ServerError("OpenRepository", err)
  333. return nil
  334. }
  335. defer headGitRepo.Close()
  336. if pull.Flow == issues_model.PullRequestFlowGithub {
  337. headBranchExist = headGitRepo.IsBranchExist(pull.HeadBranch)
  338. } else {
  339. headBranchExist = git.IsReferenceExist(ctx, baseGitRepo.Path, pull.GetGitRefName())
  340. }
  341. if headBranchExist {
  342. if pull.Flow != issues_model.PullRequestFlowGithub {
  343. headBranchSha, err = baseGitRepo.GetRefCommitID(pull.GetGitRefName())
  344. } else {
  345. headBranchSha, err = headGitRepo.GetBranchCommitID(pull.HeadBranch)
  346. }
  347. if err != nil {
  348. ctx.ServerError("GetBranchCommitID", err)
  349. return nil
  350. }
  351. }
  352. }
  353. if headBranchExist {
  354. var err error
  355. ctx.Data["UpdateAllowed"], ctx.Data["UpdateByRebaseAllowed"], err = pull_service.IsUserAllowedToUpdate(ctx, pull, ctx.Doer)
  356. if err != nil {
  357. ctx.ServerError("IsUserAllowedToUpdate", err)
  358. return nil
  359. }
  360. ctx.Data["GetCommitMessages"] = pull_service.GetSquashMergeCommitMessages(ctx, pull)
  361. } else {
  362. ctx.Data["GetCommitMessages"] = ""
  363. }
  364. sha, err := baseGitRepo.GetRefCommitID(pull.GetGitRefName())
  365. if err != nil {
  366. if git.IsErrNotExist(err) {
  367. ctx.Data["IsPullRequestBroken"] = true
  368. if pull.IsSameRepo() {
  369. ctx.Data["HeadTarget"] = pull.HeadBranch
  370. } else if pull.HeadRepo == nil {
  371. ctx.Data["HeadTarget"] = ctx.Locale.Tr("repo.pull.deleted_branch", pull.HeadBranch)
  372. } else {
  373. ctx.Data["HeadTarget"] = pull.HeadRepo.OwnerName + ":" + pull.HeadBranch
  374. }
  375. ctx.Data["BaseTarget"] = pull.BaseBranch
  376. ctx.Data["NumCommits"] = 0
  377. ctx.Data["NumFiles"] = 0
  378. return nil
  379. }
  380. ctx.ServerError(fmt.Sprintf("GetRefCommitID(%s)", pull.GetGitRefName()), err)
  381. return nil
  382. }
  383. commitStatuses, _, err := git_model.GetLatestCommitStatus(ctx, repo.ID, sha, db.ListOptionsAll)
  384. if err != nil {
  385. ctx.ServerError("GetLatestCommitStatus", err)
  386. return nil
  387. }
  388. if len(commitStatuses) > 0 {
  389. ctx.Data["LatestCommitStatuses"] = commitStatuses
  390. ctx.Data["LatestCommitStatus"] = git_model.CalcCommitStatus(commitStatuses)
  391. }
  392. if pb != nil && pb.EnableStatusCheck {
  393. var missingRequiredChecks []string
  394. for _, requiredContext := range pb.StatusCheckContexts {
  395. contextFound := false
  396. matchesRequiredContext := createRequiredContextMatcher(requiredContext)
  397. for _, presentStatus := range commitStatuses {
  398. if matchesRequiredContext(presentStatus.Context) {
  399. contextFound = true
  400. break
  401. }
  402. }
  403. if !contextFound {
  404. missingRequiredChecks = append(missingRequiredChecks, requiredContext)
  405. }
  406. }
  407. ctx.Data["MissingRequiredChecks"] = missingRequiredChecks
  408. ctx.Data["is_context_required"] = func(context string) bool {
  409. for _, c := range pb.StatusCheckContexts {
  410. if c == context {
  411. return true
  412. }
  413. if gp, err := glob.Compile(c); err != nil {
  414. // All newly created status_check_contexts are checked to ensure they are valid glob expressions before being stored in the database.
  415. // But some old status_check_context created before glob was introduced may be invalid glob expressions.
  416. // So log the error here for debugging.
  417. log.Error("compile glob %q: %v", c, err)
  418. } else if gp.Match(context) {
  419. return true
  420. }
  421. }
  422. return false
  423. }
  424. ctx.Data["RequiredStatusCheckState"] = pull_service.MergeRequiredContextsCommitStatus(commitStatuses, pb.StatusCheckContexts)
  425. }
  426. ctx.Data["HeadBranchMovedOn"] = headBranchSha != sha
  427. ctx.Data["HeadBranchCommitID"] = headBranchSha
  428. ctx.Data["PullHeadCommitID"] = sha
  429. if pull.HeadRepo == nil || !headBranchExist || (!pull.Issue.IsClosed && (headBranchSha != sha)) {
  430. ctx.Data["IsPullRequestBroken"] = true
  431. if pull.IsSameRepo() {
  432. ctx.Data["HeadTarget"] = pull.HeadBranch
  433. } else if pull.HeadRepo == nil {
  434. ctx.Data["HeadTarget"] = ctx.Locale.Tr("repo.pull.deleted_branch", pull.HeadBranch)
  435. } else {
  436. ctx.Data["HeadTarget"] = pull.HeadRepo.OwnerName + ":" + pull.HeadBranch
  437. }
  438. }
  439. compareInfo, err := baseGitRepo.GetCompareInfo(pull.BaseRepo.RepoPath(),
  440. git.BranchPrefix+pull.BaseBranch, pull.GetGitRefName(), false, false)
  441. if err != nil {
  442. if strings.Contains(err.Error(), "fatal: Not a valid object name") {
  443. ctx.Data["IsPullRequestBroken"] = true
  444. ctx.Data["BaseTarget"] = pull.BaseBranch
  445. ctx.Data["NumCommits"] = 0
  446. ctx.Data["NumFiles"] = 0
  447. return nil
  448. }
  449. ctx.ServerError("GetCompareInfo", err)
  450. return nil
  451. }
  452. if compareInfo.HeadCommitID == compareInfo.MergeBase {
  453. ctx.Data["IsNothingToCompare"] = true
  454. }
  455. if pull.IsWorkInProgress(ctx) {
  456. ctx.Data["IsPullWorkInProgress"] = true
  457. ctx.Data["WorkInProgressPrefix"] = pull.GetWorkInProgressPrefix(ctx)
  458. }
  459. if pull.IsFilesConflicted() {
  460. ctx.Data["IsPullFilesConflicted"] = true
  461. ctx.Data["ConflictedFiles"] = pull.ConflictedFiles
  462. }
  463. ctx.Data["NumCommits"] = len(compareInfo.Commits)
  464. ctx.Data["NumFiles"] = compareInfo.NumFiles
  465. return compareInfo
  466. }
  467. func createRequiredContextMatcher(requiredContext string) func(string) bool {
  468. if gp, err := glob.Compile(requiredContext); err == nil {
  469. return func(contextToCheck string) bool {
  470. return gp.Match(contextToCheck)
  471. }
  472. }
  473. return func(contextToCheck string) bool {
  474. return requiredContext == contextToCheck
  475. }
  476. }
  477. type pullCommitList struct {
  478. Commits []pull_service.CommitInfo `json:"commits"`
  479. LastReviewCommitSha string `json:"last_review_commit_sha"`
  480. Locale map[string]any `json:"locale"`
  481. }
  482. // GetPullCommits get all commits for given pull request
  483. func GetPullCommits(ctx *context.Context) {
  484. issue, ok := getPullInfo(ctx)
  485. if !ok {
  486. return
  487. }
  488. resp := &pullCommitList{}
  489. commits, lastReviewCommitSha, err := pull_service.GetPullCommits(ctx, issue)
  490. if err != nil {
  491. ctx.JSON(http.StatusInternalServerError, err)
  492. return
  493. }
  494. // Get the needed locale
  495. resp.Locale = map[string]any{
  496. "lang": ctx.Locale.Language(),
  497. "show_all_commits": ctx.Tr("repo.pulls.show_all_commits"),
  498. "stats_num_commits": ctx.TrN(len(commits), "repo.activity.git_stats_commit_1", "repo.activity.git_stats_commit_n", len(commits)),
  499. "show_changes_since_your_last_review": ctx.Tr("repo.pulls.show_changes_since_your_last_review"),
  500. "select_commit_hold_shift_for_range": ctx.Tr("repo.pulls.select_commit_hold_shift_for_range"),
  501. }
  502. resp.Commits = commits
  503. resp.LastReviewCommitSha = lastReviewCommitSha
  504. ctx.JSON(http.StatusOK, resp)
  505. }
  506. // ViewPullCommits show commits for a pull request
  507. func ViewPullCommits(ctx *context.Context) {
  508. ctx.Data["PageIsPullList"] = true
  509. ctx.Data["PageIsPullCommits"] = true
  510. issue, ok := getPullInfo(ctx)
  511. if !ok {
  512. return
  513. }
  514. pull := issue.PullRequest
  515. var prInfo *git.CompareInfo
  516. if pull.HasMerged {
  517. prInfo = PrepareMergedViewPullInfo(ctx, issue)
  518. } else {
  519. prInfo = PrepareViewPullInfo(ctx, issue)
  520. }
  521. if ctx.Written() {
  522. return
  523. } else if prInfo == nil {
  524. ctx.NotFound("ViewPullCommits", nil)
  525. return
  526. }
  527. ctx.Data["Username"] = ctx.Repo.Owner.Name
  528. ctx.Data["Reponame"] = ctx.Repo.Repository.Name
  529. commits := git_model.ConvertFromGitCommit(ctx, prInfo.Commits, ctx.Repo.Repository)
  530. ctx.Data["Commits"] = commits
  531. ctx.Data["CommitCount"] = len(commits)
  532. ctx.Data["HasIssuesOrPullsWritePermission"] = ctx.Repo.CanWriteIssuesOrPulls(issue.IsPull)
  533. ctx.Data["IsIssuePoster"] = ctx.IsSigned && issue.IsPoster(ctx.Doer.ID)
  534. // For PR commits page
  535. PrepareBranchList(ctx)
  536. if ctx.Written() {
  537. return
  538. }
  539. getBranchData(ctx, issue)
  540. ctx.HTML(http.StatusOK, tplPullCommits)
  541. }
  542. // ViewPullFiles render pull request changed files list page
  543. func viewPullFiles(ctx *context.Context, specifiedStartCommit, specifiedEndCommit string, willShowSpecifiedCommitRange, willShowSpecifiedCommit bool) {
  544. ctx.Data["PageIsPullList"] = true
  545. ctx.Data["PageIsPullFiles"] = true
  546. issue, ok := getPullInfo(ctx)
  547. if !ok {
  548. return
  549. }
  550. pull := issue.PullRequest
  551. var (
  552. startCommitID string
  553. endCommitID string
  554. gitRepo = ctx.Repo.GitRepo
  555. )
  556. var prInfo *git.CompareInfo
  557. if pull.HasMerged {
  558. prInfo = PrepareMergedViewPullInfo(ctx, issue)
  559. } else {
  560. prInfo = PrepareViewPullInfo(ctx, issue)
  561. }
  562. // Validate the given commit sha to show (if any passed)
  563. if willShowSpecifiedCommit || willShowSpecifiedCommitRange {
  564. foundStartCommit := len(specifiedStartCommit) == 0
  565. foundEndCommit := len(specifiedEndCommit) == 0
  566. if !(foundStartCommit && foundEndCommit) {
  567. for _, commit := range prInfo.Commits {
  568. if commit.ID.String() == specifiedStartCommit {
  569. foundStartCommit = true
  570. }
  571. if commit.ID.String() == specifiedEndCommit {
  572. foundEndCommit = true
  573. }
  574. if foundStartCommit && foundEndCommit {
  575. break
  576. }
  577. }
  578. }
  579. if !(foundStartCommit && foundEndCommit) {
  580. ctx.NotFound("Given SHA1 not found for this PR", nil)
  581. return
  582. }
  583. }
  584. if ctx.Written() {
  585. return
  586. } else if prInfo == nil {
  587. ctx.NotFound("ViewPullFiles", nil)
  588. return
  589. }
  590. headCommitID, err := gitRepo.GetRefCommitID(pull.GetGitRefName())
  591. if err != nil {
  592. ctx.ServerError("GetRefCommitID", err)
  593. return
  594. }
  595. ctx.Data["IsShowingOnlySingleCommit"] = willShowSpecifiedCommit
  596. if willShowSpecifiedCommit || willShowSpecifiedCommitRange {
  597. if len(specifiedEndCommit) > 0 {
  598. endCommitID = specifiedEndCommit
  599. } else {
  600. endCommitID = headCommitID
  601. }
  602. if len(specifiedStartCommit) > 0 {
  603. startCommitID = specifiedStartCommit
  604. } else {
  605. startCommitID = prInfo.MergeBase
  606. }
  607. ctx.Data["IsShowingAllCommits"] = false
  608. } else {
  609. endCommitID = headCommitID
  610. startCommitID = prInfo.MergeBase
  611. ctx.Data["IsShowingAllCommits"] = true
  612. }
  613. ctx.Data["Username"] = ctx.Repo.Owner.Name
  614. ctx.Data["Reponame"] = ctx.Repo.Repository.Name
  615. ctx.Data["AfterCommitID"] = endCommitID
  616. ctx.Data["BeforeCommitID"] = startCommitID
  617. fileOnly := ctx.FormBool("file-only")
  618. maxLines, maxFiles := setting.Git.MaxGitDiffLines, setting.Git.MaxGitDiffFiles
  619. files := ctx.FormStrings("files")
  620. if fileOnly && (len(files) == 2 || len(files) == 1) {
  621. maxLines, maxFiles = -1, -1
  622. }
  623. diffOptions := &gitdiff.DiffOptions{
  624. AfterCommitID: endCommitID,
  625. SkipTo: ctx.FormString("skip-to"),
  626. MaxLines: maxLines,
  627. MaxLineCharacters: setting.Git.MaxGitDiffLineCharacters,
  628. MaxFiles: maxFiles,
  629. WhitespaceBehavior: gitdiff.GetWhitespaceFlag(ctx.Data["WhitespaceBehavior"].(string)),
  630. }
  631. if !willShowSpecifiedCommit {
  632. diffOptions.BeforeCommitID = startCommitID
  633. }
  634. var methodWithError string
  635. var diff *gitdiff.Diff
  636. // if we're not logged in or only a single commit (or commit range) is shown we
  637. // have to load only the diff and not get the viewed information
  638. // as the viewed information is designed to be loaded only on latest PR
  639. // diff and if you're signed in.
  640. if !ctx.IsSigned || willShowSpecifiedCommit || willShowSpecifiedCommitRange {
  641. diff, err = gitdiff.GetDiff(ctx, gitRepo, diffOptions, files...)
  642. methodWithError = "GetDiff"
  643. } else {
  644. diff, err = gitdiff.SyncAndGetUserSpecificDiff(ctx, ctx.Doer.ID, pull, gitRepo, diffOptions, files...)
  645. methodWithError = "SyncAndGetUserSpecificDiff"
  646. }
  647. if err != nil {
  648. ctx.ServerError(methodWithError, err)
  649. return
  650. }
  651. ctx.PageData["prReview"] = map[string]any{
  652. "numberOfFiles": diff.NumFiles,
  653. "numberOfViewedFiles": diff.NumViewedFiles,
  654. }
  655. if err = diff.LoadComments(ctx, issue, ctx.Doer, ctx.Data["ShowOutdatedComments"].(bool)); err != nil {
  656. ctx.ServerError("LoadComments", err)
  657. return
  658. }
  659. for _, file := range diff.Files {
  660. for _, section := range file.Sections {
  661. for _, line := range section.Lines {
  662. for _, comment := range line.Comments {
  663. if err := comment.LoadAttachments(ctx); err != nil {
  664. ctx.ServerError("LoadAttachments", err)
  665. return
  666. }
  667. }
  668. }
  669. }
  670. }
  671. pb, err := git_model.GetFirstMatchProtectedBranchRule(ctx, pull.BaseRepoID, pull.BaseBranch)
  672. if err != nil {
  673. ctx.ServerError("LoadProtectedBranch", err)
  674. return
  675. }
  676. if pb != nil {
  677. glob := pb.GetProtectedFilePatterns()
  678. if len(glob) != 0 {
  679. for _, file := range diff.Files {
  680. file.IsProtected = pb.IsProtectedFile(glob, file.Name)
  681. }
  682. }
  683. }
  684. ctx.Data["Diff"] = diff
  685. ctx.Data["DiffNotAvailable"] = diff.NumFiles == 0
  686. baseCommit, err := ctx.Repo.GitRepo.GetCommit(startCommitID)
  687. if err != nil {
  688. ctx.ServerError("GetCommit", err)
  689. return
  690. }
  691. commit, err := gitRepo.GetCommit(endCommitID)
  692. if err != nil {
  693. ctx.ServerError("GetCommit", err)
  694. return
  695. }
  696. if ctx.IsSigned && ctx.Doer != nil {
  697. if ctx.Data["CanMarkConversation"], err = issues_model.CanMarkConversation(ctx, issue, ctx.Doer); err != nil {
  698. ctx.ServerError("CanMarkConversation", err)
  699. return
  700. }
  701. }
  702. setCompareContext(ctx, baseCommit, commit, ctx.Repo.Owner.Name, ctx.Repo.Repository.Name)
  703. assigneeUsers, err := repo_model.GetRepoAssignees(ctx, ctx.Repo.Repository)
  704. if err != nil {
  705. ctx.ServerError("GetRepoAssignees", err)
  706. return
  707. }
  708. ctx.Data["Assignees"] = MakeSelfOnTop(ctx.Doer, assigneeUsers)
  709. handleTeamMentions(ctx)
  710. if ctx.Written() {
  711. return
  712. }
  713. currentReview, err := issues_model.GetCurrentReview(ctx, ctx.Doer, issue)
  714. if err != nil && !issues_model.IsErrReviewNotExist(err) {
  715. ctx.ServerError("GetCurrentReview", err)
  716. return
  717. }
  718. numPendingCodeComments := int64(0)
  719. if currentReview != nil {
  720. numPendingCodeComments, err = issues_model.CountComments(ctx, &issues_model.FindCommentsOptions{
  721. Type: issues_model.CommentTypeCode,
  722. ReviewID: currentReview.ID,
  723. IssueID: issue.ID,
  724. })
  725. if err != nil {
  726. ctx.ServerError("CountComments", err)
  727. return
  728. }
  729. }
  730. ctx.Data["CurrentReview"] = currentReview
  731. ctx.Data["PendingCodeCommentNumber"] = numPendingCodeComments
  732. getBranchData(ctx, issue)
  733. ctx.Data["IsIssuePoster"] = ctx.IsSigned && issue.IsPoster(ctx.Doer.ID)
  734. ctx.Data["HasIssuesOrPullsWritePermission"] = ctx.Repo.CanWriteIssuesOrPulls(issue.IsPull)
  735. ctx.Data["IsAttachmentEnabled"] = setting.Attachment.Enabled
  736. // For files changed page
  737. PrepareBranchList(ctx)
  738. if ctx.Written() {
  739. return
  740. }
  741. upload.AddUploadContext(ctx, "comment")
  742. ctx.Data["CanBlockUser"] = func(blocker, blockee *user_model.User) bool {
  743. return user_service.CanBlockUser(ctx, ctx.Doer, blocker, blockee)
  744. }
  745. if !willShowSpecifiedCommit && !willShowSpecifiedCommitRange && pull.Flow == issues_model.PullRequestFlowGithub {
  746. if err := pull.LoadHeadRepo(ctx); err != nil {
  747. ctx.ServerError("LoadHeadRepo", err)
  748. return
  749. }
  750. if pull.HeadRepo != nil {
  751. ctx.Data["SourcePath"] = pull.HeadRepo.Link() + "/src/branch/" + util.PathEscapeSegments(pull.HeadBranch)
  752. if !pull.HasMerged && ctx.Doer != nil {
  753. perm, err := access_model.GetUserRepoPermission(ctx, pull.HeadRepo, ctx.Doer)
  754. if err != nil {
  755. ctx.ServerError("GetUserRepoPermission", err)
  756. return
  757. }
  758. if perm.CanWrite(unit.TypeCode) || issues_model.CanMaintainerWriteToBranch(ctx, perm, pull.HeadBranch, ctx.Doer) {
  759. ctx.Data["CanEditFile"] = true
  760. ctx.Data["EditFileTooltip"] = ctx.Tr("repo.editor.edit_this_file")
  761. ctx.Data["HeadRepoLink"] = pull.HeadRepo.Link()
  762. ctx.Data["HeadBranchName"] = pull.HeadBranch
  763. ctx.Data["BackToLink"] = setting.AppSubURL + ctx.Req.URL.RequestURI()
  764. }
  765. }
  766. }
  767. }
  768. ctx.HTML(http.StatusOK, tplPullFiles)
  769. }
  770. func ViewPullFilesForSingleCommit(ctx *context.Context) {
  771. viewPullFiles(ctx, "", ctx.Params("sha"), true, true)
  772. }
  773. func ViewPullFilesForRange(ctx *context.Context) {
  774. viewPullFiles(ctx, ctx.Params("shaFrom"), ctx.Params("shaTo"), true, false)
  775. }
  776. func ViewPullFilesStartingFromCommit(ctx *context.Context) {
  777. viewPullFiles(ctx, "", ctx.Params("sha"), true, false)
  778. }
  779. func ViewPullFilesForAllCommitsOfPr(ctx *context.Context) {
  780. viewPullFiles(ctx, "", "", false, false)
  781. }
  782. // UpdatePullRequest merge PR's baseBranch into headBranch
  783. func UpdatePullRequest(ctx *context.Context) {
  784. issue, ok := getPullInfo(ctx)
  785. if !ok {
  786. return
  787. }
  788. if issue.IsClosed {
  789. ctx.NotFound("MergePullRequest", nil)
  790. return
  791. }
  792. if issue.PullRequest.HasMerged {
  793. ctx.NotFound("MergePullRequest", nil)
  794. return
  795. }
  796. rebase := ctx.FormString("style") == "rebase"
  797. if err := issue.PullRequest.LoadBaseRepo(ctx); err != nil {
  798. ctx.ServerError("LoadBaseRepo", err)
  799. return
  800. }
  801. if err := issue.PullRequest.LoadHeadRepo(ctx); err != nil {
  802. ctx.ServerError("LoadHeadRepo", err)
  803. return
  804. }
  805. allowedUpdateByMerge, allowedUpdateByRebase, err := pull_service.IsUserAllowedToUpdate(ctx, issue.PullRequest, ctx.Doer)
  806. if err != nil {
  807. ctx.ServerError("IsUserAllowedToMerge", err)
  808. return
  809. }
  810. // ToDo: add check if maintainers are allowed to change branch ... (need migration & co)
  811. if (!allowedUpdateByMerge && !rebase) || (rebase && !allowedUpdateByRebase) {
  812. ctx.Flash.Error(ctx.Tr("repo.pulls.update_not_allowed"))
  813. ctx.Redirect(issue.Link())
  814. return
  815. }
  816. // default merge commit message
  817. message := fmt.Sprintf("Merge branch '%s' into %s", issue.PullRequest.BaseBranch, issue.PullRequest.HeadBranch)
  818. if err = pull_service.Update(ctx, issue.PullRequest, ctx.Doer, message, rebase); err != nil {
  819. if models.IsErrMergeConflicts(err) {
  820. conflictError := err.(models.ErrMergeConflicts)
  821. flashError, err := ctx.RenderToHTML(tplAlertDetails, map[string]any{
  822. "Message": ctx.Tr("repo.pulls.merge_conflict"),
  823. "Summary": ctx.Tr("repo.pulls.merge_conflict_summary"),
  824. "Details": utils.SanitizeFlashErrorString(conflictError.StdErr) + "<br>" + utils.SanitizeFlashErrorString(conflictError.StdOut),
  825. })
  826. if err != nil {
  827. ctx.ServerError("UpdatePullRequest.HTMLString", err)
  828. return
  829. }
  830. ctx.Flash.Error(flashError)
  831. ctx.Redirect(issue.Link())
  832. return
  833. } else if models.IsErrRebaseConflicts(err) {
  834. conflictError := err.(models.ErrRebaseConflicts)
  835. flashError, err := ctx.RenderToHTML(tplAlertDetails, map[string]any{
  836. "Message": ctx.Tr("repo.pulls.rebase_conflict", utils.SanitizeFlashErrorString(conflictError.CommitSHA)),
  837. "Summary": ctx.Tr("repo.pulls.rebase_conflict_summary"),
  838. "Details": utils.SanitizeFlashErrorString(conflictError.StdErr) + "<br>" + utils.SanitizeFlashErrorString(conflictError.StdOut),
  839. })
  840. if err != nil {
  841. ctx.ServerError("UpdatePullRequest.HTMLString", err)
  842. return
  843. }
  844. ctx.Flash.Error(flashError)
  845. ctx.Redirect(issue.Link())
  846. return
  847. }
  848. ctx.Flash.Error(err.Error())
  849. ctx.Redirect(issue.Link())
  850. return
  851. }
  852. time.Sleep(1 * time.Second)
  853. ctx.Flash.Success(ctx.Tr("repo.pulls.update_branch_success"))
  854. ctx.Redirect(issue.Link())
  855. }
  856. // MergePullRequest response for merging pull request
  857. func MergePullRequest(ctx *context.Context) {
  858. form := web.GetForm(ctx).(*forms.MergePullRequestForm)
  859. issue, ok := getPullInfo(ctx)
  860. if !ok {
  861. return
  862. }
  863. pr := issue.PullRequest
  864. pr.Issue = issue
  865. pr.Issue.Repo = ctx.Repo.Repository
  866. manuallyMerged := repo_model.MergeStyle(form.Do) == repo_model.MergeStyleManuallyMerged
  867. mergeCheckType := pull_service.MergeCheckTypeGeneral
  868. if form.MergeWhenChecksSucceed {
  869. mergeCheckType = pull_service.MergeCheckTypeAuto
  870. }
  871. if manuallyMerged {
  872. mergeCheckType = pull_service.MergeCheckTypeManually
  873. }
  874. // start with merging by checking
  875. if err := pull_service.CheckPullMergable(ctx, ctx.Doer, &ctx.Repo.Permission, pr, mergeCheckType, form.ForceMerge); err != nil {
  876. switch {
  877. case errors.Is(err, pull_service.ErrIsClosed):
  878. if issue.IsPull {
  879. ctx.JSONError(ctx.Tr("repo.pulls.is_closed"))
  880. } else {
  881. ctx.JSONError(ctx.Tr("repo.issues.closed_title"))
  882. }
  883. case errors.Is(err, pull_service.ErrUserNotAllowedToMerge):
  884. ctx.JSONError(ctx.Tr("repo.pulls.update_not_allowed"))
  885. case errors.Is(err, pull_service.ErrHasMerged):
  886. ctx.JSONError(ctx.Tr("repo.pulls.has_merged"))
  887. case errors.Is(err, pull_service.ErrIsWorkInProgress):
  888. ctx.JSONError(ctx.Tr("repo.pulls.no_merge_wip"))
  889. case errors.Is(err, pull_service.ErrNotMergableState):
  890. ctx.JSONError(ctx.Tr("repo.pulls.no_merge_not_ready"))
  891. case models.IsErrDisallowedToMerge(err):
  892. ctx.JSONError(ctx.Tr("repo.pulls.no_merge_not_ready"))
  893. case asymkey_service.IsErrWontSign(err):
  894. ctx.JSONError(err.Error()) // has no translation ...
  895. case errors.Is(err, pull_service.ErrDependenciesLeft):
  896. ctx.JSONError(ctx.Tr("repo.issues.dependency.pr_close_blocked"))
  897. default:
  898. ctx.ServerError("WebCheck", err)
  899. }
  900. return
  901. }
  902. // handle manually-merged mark
  903. if manuallyMerged {
  904. if err := pull_service.MergedManually(ctx, pr, ctx.Doer, ctx.Repo.GitRepo, form.MergeCommitID); err != nil {
  905. switch {
  906. case models.IsErrInvalidMergeStyle(err):
  907. ctx.JSONError(ctx.Tr("repo.pulls.invalid_merge_option"))
  908. case strings.Contains(err.Error(), "Wrong commit ID"):
  909. ctx.JSONError(ctx.Tr("repo.pulls.wrong_commit_id"))
  910. default:
  911. ctx.ServerError("MergedManually", err)
  912. }
  913. return
  914. }
  915. ctx.JSONRedirect(issue.Link())
  916. return
  917. }
  918. message := strings.TrimSpace(form.MergeTitleField)
  919. if len(message) == 0 {
  920. var err error
  921. message, _, err = pull_service.GetDefaultMergeMessage(ctx, ctx.Repo.GitRepo, pr, repo_model.MergeStyle(form.Do))
  922. if err != nil {
  923. ctx.ServerError("GetDefaultMergeMessage", err)
  924. return
  925. }
  926. }
  927. form.MergeMessageField = strings.TrimSpace(form.MergeMessageField)
  928. if len(form.MergeMessageField) > 0 {
  929. message += "\n\n" + form.MergeMessageField
  930. }
  931. if form.MergeWhenChecksSucceed {
  932. // delete all scheduled auto merges
  933. _ = pull_model.DeleteScheduledAutoMerge(ctx, pr.ID)
  934. // schedule auto merge
  935. scheduled, err := automerge.ScheduleAutoMerge(ctx, ctx.Doer, pr, repo_model.MergeStyle(form.Do), message)
  936. if err != nil {
  937. ctx.ServerError("ScheduleAutoMerge", err)
  938. return
  939. } else if scheduled {
  940. // nothing more to do ...
  941. ctx.Flash.Success(ctx.Tr("repo.pulls.auto_merge_newly_scheduled"))
  942. ctx.JSONRedirect(fmt.Sprintf("%s/pulls/%d", ctx.Repo.RepoLink, pr.Index))
  943. return
  944. }
  945. }
  946. if err := pull_service.Merge(ctx, pr, ctx.Doer, ctx.Repo.GitRepo, repo_model.MergeStyle(form.Do), form.HeadCommitID, message, false); err != nil {
  947. if models.IsErrInvalidMergeStyle(err) {
  948. ctx.JSONError(ctx.Tr("repo.pulls.invalid_merge_option"))
  949. } else if models.IsErrMergeConflicts(err) {
  950. conflictError := err.(models.ErrMergeConflicts)
  951. flashError, err := ctx.RenderToHTML(tplAlertDetails, map[string]any{
  952. "Message": ctx.Tr("repo.editor.merge_conflict"),
  953. "Summary": ctx.Tr("repo.editor.merge_conflict_summary"),
  954. "Details": utils.SanitizeFlashErrorString(conflictError.StdErr) + "<br>" + utils.SanitizeFlashErrorString(conflictError.StdOut),
  955. })
  956. if err != nil {
  957. ctx.ServerError("MergePullRequest.HTMLString", err)
  958. return
  959. }
  960. ctx.Flash.Error(flashError)
  961. ctx.JSONRedirect(issue.Link())
  962. } else if models.IsErrRebaseConflicts(err) {
  963. conflictError := err.(models.ErrRebaseConflicts)
  964. flashError, err := ctx.RenderToHTML(tplAlertDetails, map[string]any{
  965. "Message": ctx.Tr("repo.pulls.rebase_conflict", utils.SanitizeFlashErrorString(conflictError.CommitSHA)),
  966. "Summary": ctx.Tr("repo.pulls.rebase_conflict_summary"),
  967. "Details": utils.SanitizeFlashErrorString(conflictError.StdErr) + "<br>" + utils.SanitizeFlashErrorString(conflictError.StdOut),
  968. })
  969. if err != nil {
  970. ctx.ServerError("MergePullRequest.HTMLString", err)
  971. return
  972. }
  973. ctx.Flash.Error(flashError)
  974. ctx.JSONRedirect(issue.Link())
  975. } else if models.IsErrMergeUnrelatedHistories(err) {
  976. log.Debug("MergeUnrelatedHistories error: %v", err)
  977. ctx.Flash.Error(ctx.Tr("repo.pulls.unrelated_histories"))
  978. ctx.JSONRedirect(issue.Link())
  979. } else if git.IsErrPushOutOfDate(err) {
  980. log.Debug("MergePushOutOfDate error: %v", err)
  981. ctx.Flash.Error(ctx.Tr("repo.pulls.merge_out_of_date"))
  982. ctx.JSONRedirect(issue.Link())
  983. } else if models.IsErrSHADoesNotMatch(err) {
  984. log.Debug("MergeHeadOutOfDate error: %v", err)
  985. ctx.Flash.Error(ctx.Tr("repo.pulls.head_out_of_date"))
  986. ctx.JSONRedirect(issue.Link())
  987. } else if git.IsErrPushRejected(err) {
  988. log.Debug("MergePushRejected error: %v", err)
  989. pushrejErr := err.(*git.ErrPushRejected)
  990. message := pushrejErr.Message
  991. if len(message) == 0 {
  992. ctx.Flash.Error(ctx.Tr("repo.pulls.push_rejected_no_message"))
  993. } else {
  994. flashError, err := ctx.RenderToHTML(tplAlertDetails, map[string]any{
  995. "Message": ctx.Tr("repo.pulls.push_rejected"),
  996. "Summary": ctx.Tr("repo.pulls.push_rejected_summary"),
  997. "Details": utils.SanitizeFlashErrorString(pushrejErr.Message),
  998. })
  999. if err != nil {
  1000. ctx.ServerError("MergePullRequest.HTMLString", err)
  1001. return
  1002. }
  1003. ctx.Flash.Error(flashError)
  1004. }
  1005. ctx.JSONRedirect(issue.Link())
  1006. } else {
  1007. ctx.ServerError("Merge", err)
  1008. }
  1009. return
  1010. }
  1011. log.Trace("Pull request merged: %d", pr.ID)
  1012. if form.DeleteBranchAfterMerge {
  1013. // Don't cleanup when other pr use this branch as head branch
  1014. exist, err := issues_model.HasUnmergedPullRequestsByHeadInfo(ctx, pr.HeadRepoID, pr.HeadBranch)
  1015. if err != nil {
  1016. ctx.ServerError("HasUnmergedPullRequestsByHeadInfo", err)
  1017. return
  1018. }
  1019. if exist {
  1020. ctx.JSONRedirect(issue.Link())
  1021. return
  1022. }
  1023. var headRepo *git.Repository
  1024. if ctx.Repo != nil && ctx.Repo.Repository != nil && pr.HeadRepoID == ctx.Repo.Repository.ID && ctx.Repo.GitRepo != nil {
  1025. headRepo = ctx.Repo.GitRepo
  1026. } else {
  1027. headRepo, err = gitrepo.OpenRepository(ctx, pr.HeadRepo)
  1028. if err != nil {
  1029. ctx.ServerError(fmt.Sprintf("OpenRepository[%s]", pr.HeadRepo.FullName()), err)
  1030. return
  1031. }
  1032. defer headRepo.Close()
  1033. }
  1034. deleteBranch(ctx, pr, headRepo)
  1035. }
  1036. ctx.JSONRedirect(issue.Link())
  1037. }
  1038. // CancelAutoMergePullRequest cancels a scheduled pr
  1039. func CancelAutoMergePullRequest(ctx *context.Context) {
  1040. issue, ok := getPullInfo(ctx)
  1041. if !ok {
  1042. return
  1043. }
  1044. if err := automerge.RemoveScheduledAutoMerge(ctx, ctx.Doer, issue.PullRequest); err != nil {
  1045. if db.IsErrNotExist(err) {
  1046. ctx.Flash.Error(ctx.Tr("repo.pulls.auto_merge_not_scheduled"))
  1047. ctx.Redirect(fmt.Sprintf("%s/pulls/%d", ctx.Repo.RepoLink, issue.Index))
  1048. return
  1049. }
  1050. ctx.ServerError("RemoveScheduledAutoMerge", err)
  1051. return
  1052. }
  1053. ctx.Flash.Success(ctx.Tr("repo.pulls.auto_merge_canceled_schedule"))
  1054. ctx.Redirect(fmt.Sprintf("%s/pulls/%d", ctx.Repo.RepoLink, issue.Index))
  1055. }
  1056. // CompareAndPullRequestPost response for creating pull request
  1057. func CompareAndPullRequestPost(ctx *context.Context) {
  1058. form := web.GetForm(ctx).(*forms.CreateIssueForm)
  1059. ctx.Data["Title"] = ctx.Tr("repo.pulls.compare_changes")
  1060. ctx.Data["PageIsComparePull"] = true
  1061. ctx.Data["IsDiffCompare"] = true
  1062. ctx.Data["IsRepoToolbarCommits"] = true
  1063. ctx.Data["PullRequestWorkInProgressPrefixes"] = setting.Repository.PullRequest.WorkInProgressPrefixes
  1064. ctx.Data["IsAttachmentEnabled"] = setting.Attachment.Enabled
  1065. upload.AddUploadContext(ctx, "comment")
  1066. ctx.Data["HasIssuesOrPullsWritePermission"] = ctx.Repo.CanWrite(unit.TypePullRequests)
  1067. var (
  1068. repo = ctx.Repo.Repository
  1069. attachments []string
  1070. )
  1071. ci := ParseCompareInfo(ctx)
  1072. defer func() {
  1073. if ci != nil && ci.HeadGitRepo != nil {
  1074. ci.HeadGitRepo.Close()
  1075. }
  1076. }()
  1077. if ctx.Written() {
  1078. return
  1079. }
  1080. labelIDs, assigneeIDs, milestoneID, projectID := ValidateRepoMetas(ctx, *form, true)
  1081. if ctx.Written() {
  1082. return
  1083. }
  1084. if setting.Attachment.Enabled {
  1085. attachments = form.Files
  1086. }
  1087. if ctx.HasError() {
  1088. ctx.JSONError(ctx.GetErrMsg())
  1089. return
  1090. }
  1091. if util.IsEmptyString(form.Title) {
  1092. ctx.JSONError(ctx.Tr("repo.issues.new.title_empty"))
  1093. return
  1094. }
  1095. content := form.Content
  1096. if filename := ctx.Req.Form.Get("template-file"); filename != "" {
  1097. if template, err := issue_template.UnmarshalFromRepo(ctx.Repo.GitRepo, ctx.Repo.Repository.DefaultBranch, filename); err == nil {
  1098. content = issue_template.RenderToMarkdown(template, ctx.Req.Form)
  1099. }
  1100. }
  1101. pullIssue := &issues_model.Issue{
  1102. RepoID: repo.ID,
  1103. Repo: repo,
  1104. Title: form.Title,
  1105. PosterID: ctx.Doer.ID,
  1106. Poster: ctx.Doer,
  1107. MilestoneID: milestoneID,
  1108. IsPull: true,
  1109. Content: content,
  1110. }
  1111. pullRequest := &issues_model.PullRequest{
  1112. HeadRepoID: ci.HeadRepo.ID,
  1113. BaseRepoID: repo.ID,
  1114. HeadBranch: ci.HeadBranch,
  1115. BaseBranch: ci.BaseBranch,
  1116. HeadRepo: ci.HeadRepo,
  1117. BaseRepo: repo,
  1118. MergeBase: ci.CompareInfo.MergeBase,
  1119. Type: issues_model.PullRequestGitea,
  1120. AllowMaintainerEdit: form.AllowMaintainerEdit,
  1121. }
  1122. // FIXME: check error in the case two people send pull request at almost same time, give nice error prompt
  1123. // instead of 500.
  1124. if err := pull_service.NewPullRequest(ctx, repo, pullIssue, labelIDs, attachments, pullRequest, assigneeIDs); err != nil {
  1125. if repo_model.IsErrUserDoesNotHaveAccessToRepo(err) {
  1126. ctx.Error(http.StatusBadRequest, "UserDoesNotHaveAccessToRepo", err.Error())
  1127. } else if git.IsErrPushRejected(err) {
  1128. pushrejErr := err.(*git.ErrPushRejected)
  1129. message := pushrejErr.Message
  1130. if len(message) == 0 {
  1131. ctx.JSONError(ctx.Tr("repo.pulls.push_rejected_no_message"))
  1132. return
  1133. }
  1134. flashError, err := ctx.RenderToHTML(tplAlertDetails, map[string]any{
  1135. "Message": ctx.Tr("repo.pulls.push_rejected"),
  1136. "Summary": ctx.Tr("repo.pulls.push_rejected_summary"),
  1137. "Details": utils.SanitizeFlashErrorString(pushrejErr.Message),
  1138. })
  1139. if err != nil {
  1140. ctx.ServerError("CompareAndPullRequest.HTMLString", err)
  1141. return
  1142. }
  1143. ctx.JSONError(flashError)
  1144. } else if errors.Is(err, user_model.ErrBlockedUser) {
  1145. flashError, err := ctx.RenderToHTML(tplAlertDetails, map[string]any{
  1146. "Message": ctx.Tr("repo.pulls.push_rejected"),
  1147. "Summary": ctx.Tr("repo.pulls.new.blocked_user"),
  1148. })
  1149. if err != nil {
  1150. ctx.ServerError("CompareAndPullRequest.HTMLString", err)
  1151. return
  1152. }
  1153. ctx.JSONError(flashError)
  1154. }
  1155. return
  1156. }
  1157. if projectID > 0 {
  1158. if !ctx.Repo.CanWrite(unit.TypeProjects) {
  1159. ctx.Error(http.StatusBadRequest, "user hasn't the permission to write to projects")
  1160. return
  1161. }
  1162. if err := issues_model.ChangeProjectAssign(ctx, pullIssue, ctx.Doer, projectID); err != nil {
  1163. ctx.ServerError("ChangeProjectAssign", err)
  1164. return
  1165. }
  1166. }
  1167. log.Trace("Pull request created: %d/%d", repo.ID, pullIssue.ID)
  1168. ctx.JSONRedirect(pullIssue.Link())
  1169. }
  1170. // CleanUpPullRequest responses for delete merged branch when PR has been merged
  1171. func CleanUpPullRequest(ctx *context.Context) {
  1172. issue, ok := getPullInfo(ctx)
  1173. if !ok {
  1174. return
  1175. }
  1176. pr := issue.PullRequest
  1177. // Don't cleanup unmerged and unclosed PRs
  1178. if !pr.HasMerged && !issue.IsClosed {
  1179. ctx.NotFound("CleanUpPullRequest", nil)
  1180. return
  1181. }
  1182. // Don't cleanup when there are other PR's that use this branch as head branch.
  1183. exist, err := issues_model.HasUnmergedPullRequestsByHeadInfo(ctx, pr.HeadRepoID, pr.HeadBranch)
  1184. if err != nil {
  1185. ctx.ServerError("HasUnmergedPullRequestsByHeadInfo", err)
  1186. return
  1187. }
  1188. if exist {
  1189. ctx.NotFound("CleanUpPullRequest", nil)
  1190. return
  1191. }
  1192. if err := pr.LoadHeadRepo(ctx); err != nil {
  1193. ctx.ServerError("LoadHeadRepo", err)
  1194. return
  1195. } else if pr.HeadRepo == nil {
  1196. // Forked repository has already been deleted
  1197. ctx.NotFound("CleanUpPullRequest", nil)
  1198. return
  1199. } else if err = pr.LoadBaseRepo(ctx); err != nil {
  1200. ctx.ServerError("LoadBaseRepo", err)
  1201. return
  1202. } else if err = pr.HeadRepo.LoadOwner(ctx); err != nil {
  1203. ctx.ServerError("HeadRepo.LoadOwner", err)
  1204. return
  1205. }
  1206. perm, err := access_model.GetUserRepoPermission(ctx, pr.HeadRepo, ctx.Doer)
  1207. if err != nil {
  1208. ctx.ServerError("GetUserRepoPermission", err)
  1209. return
  1210. }
  1211. if !perm.CanWrite(unit.TypeCode) {
  1212. ctx.NotFound("CleanUpPullRequest", nil)
  1213. return
  1214. }
  1215. fullBranchName := pr.HeadRepo.Owner.Name + "/" + pr.HeadBranch
  1216. var gitBaseRepo *git.Repository
  1217. // Assume that the base repo is the current context (almost certainly)
  1218. if ctx.Repo != nil && ctx.Repo.Repository != nil && ctx.Repo.Repository.ID == pr.BaseRepoID && ctx.Repo.GitRepo != nil {
  1219. gitBaseRepo = ctx.Repo.GitRepo
  1220. } else {
  1221. // If not just open it
  1222. gitBaseRepo, err = gitrepo.OpenRepository(ctx, pr.BaseRepo)
  1223. if err != nil {
  1224. ctx.ServerError(fmt.Sprintf("OpenRepository[%s]", pr.BaseRepo.FullName()), err)
  1225. return
  1226. }
  1227. defer gitBaseRepo.Close()
  1228. }
  1229. // Now assume that the head repo is the same as the base repo (reasonable chance)
  1230. gitRepo := gitBaseRepo
  1231. // But if not: is it the same as the context?
  1232. if pr.BaseRepoID != pr.HeadRepoID && ctx.Repo != nil && ctx.Repo.Repository != nil && ctx.Repo.Repository.ID == pr.HeadRepoID && ctx.Repo.GitRepo != nil {
  1233. gitRepo = ctx.Repo.GitRepo
  1234. } else if pr.BaseRepoID != pr.HeadRepoID {
  1235. // Otherwise just load it up
  1236. gitRepo, err = gitrepo.OpenRepository(ctx, pr.HeadRepo)
  1237. if err != nil {
  1238. ctx.ServerError(fmt.Sprintf("OpenRepository[%s]", pr.HeadRepo.FullName()), err)
  1239. return
  1240. }
  1241. defer gitRepo.Close()
  1242. }
  1243. defer func() {
  1244. ctx.JSONRedirect(issue.Link())
  1245. }()
  1246. // Check if branch has no new commits
  1247. headCommitID, err := gitBaseRepo.GetRefCommitID(pr.GetGitRefName())
  1248. if err != nil {
  1249. log.Error("GetRefCommitID: %v", err)
  1250. ctx.Flash.Error(ctx.Tr("repo.branch.deletion_failed", fullBranchName))
  1251. return
  1252. }
  1253. branchCommitID, err := gitRepo.GetBranchCommitID(pr.HeadBranch)
  1254. if err != nil {
  1255. log.Error("GetBranchCommitID: %v", err)
  1256. ctx.Flash.Error(ctx.Tr("repo.branch.deletion_failed", fullBranchName))
  1257. return
  1258. }
  1259. if headCommitID != branchCommitID {
  1260. ctx.Flash.Error(ctx.Tr("repo.branch.delete_branch_has_new_commits", fullBranchName))
  1261. return
  1262. }
  1263. deleteBranch(ctx, pr, gitRepo)
  1264. }
  1265. func deleteBranch(ctx *context.Context, pr *issues_model.PullRequest, gitRepo *git.Repository) {
  1266. fullBranchName := pr.HeadRepo.FullName() + ":" + pr.HeadBranch
  1267. if err := pull_service.RetargetChildrenOnMerge(ctx, ctx.Doer, pr); err != nil {
  1268. ctx.Flash.Error(ctx.Tr("repo.branch.deletion_failed", fullBranchName))
  1269. return
  1270. }
  1271. if err := repo_service.DeleteBranch(ctx, ctx.Doer, pr.HeadRepo, gitRepo, pr.HeadBranch); err != nil {
  1272. switch {
  1273. case git.IsErrBranchNotExist(err):
  1274. ctx.Flash.Error(ctx.Tr("repo.branch.deletion_failed", fullBranchName))
  1275. case errors.Is(err, repo_service.ErrBranchIsDefault):
  1276. ctx.Flash.Error(ctx.Tr("repo.branch.deletion_failed", fullBranchName))
  1277. case errors.Is(err, git_model.ErrBranchIsProtected):
  1278. ctx.Flash.Error(ctx.Tr("repo.branch.deletion_failed", fullBranchName))
  1279. default:
  1280. log.Error("DeleteBranch: %v", err)
  1281. ctx.Flash.Error(ctx.Tr("repo.branch.deletion_failed", fullBranchName))
  1282. }
  1283. return
  1284. }
  1285. if err := issues_model.AddDeletePRBranchComment(ctx, ctx.Doer, pr.BaseRepo, pr.IssueID, pr.HeadBranch); err != nil {
  1286. // Do not fail here as branch has already been deleted
  1287. log.Error("DeleteBranch: %v", err)
  1288. }
  1289. ctx.Flash.Success(ctx.Tr("repo.branch.deletion_success", fullBranchName))
  1290. }
  1291. // DownloadPullDiff render a pull's raw diff
  1292. func DownloadPullDiff(ctx *context.Context) {
  1293. DownloadPullDiffOrPatch(ctx, false)
  1294. }
  1295. // DownloadPullPatch render a pull's raw patch
  1296. func DownloadPullPatch(ctx *context.Context) {
  1297. DownloadPullDiffOrPatch(ctx, true)
  1298. }
  1299. // DownloadPullDiffOrPatch render a pull's raw diff or patch
  1300. func DownloadPullDiffOrPatch(ctx *context.Context, patch bool) {
  1301. pr, err := issues_model.GetPullRequestByIndex(ctx, ctx.Repo.Repository.ID, ctx.ParamsInt64(":index"))
  1302. if err != nil {
  1303. if issues_model.IsErrPullRequestNotExist(err) {
  1304. ctx.NotFound("GetPullRequestByIndex", err)
  1305. } else {
  1306. ctx.ServerError("GetPullRequestByIndex", err)
  1307. }
  1308. return
  1309. }
  1310. binary := ctx.FormBool("binary")
  1311. if err := pull_service.DownloadDiffOrPatch(ctx, pr, ctx, patch, binary); err != nil {
  1312. ctx.ServerError("DownloadDiffOrPatch", err)
  1313. return
  1314. }
  1315. }
  1316. // UpdatePullRequestTarget change pull request's target branch
  1317. func UpdatePullRequestTarget(ctx *context.Context) {
  1318. issue := GetActionIssue(ctx)
  1319. if ctx.Written() {
  1320. return
  1321. }
  1322. pr := issue.PullRequest
  1323. if !issue.IsPull {
  1324. ctx.Error(http.StatusNotFound)
  1325. return
  1326. }
  1327. if !ctx.IsSigned || (!issue.IsPoster(ctx.Doer.ID) && !ctx.Repo.CanWriteIssuesOrPulls(issue.IsPull)) {
  1328. ctx.Error(http.StatusForbidden)
  1329. return
  1330. }
  1331. targetBranch := ctx.FormTrim("target_branch")
  1332. if len(targetBranch) == 0 {
  1333. ctx.Error(http.StatusNoContent)
  1334. return
  1335. }
  1336. if err := pull_service.ChangeTargetBranch(ctx, pr, ctx.Doer, targetBranch); err != nil {
  1337. if issues_model.IsErrPullRequestAlreadyExists(err) {
  1338. err := err.(issues_model.ErrPullRequestAlreadyExists)
  1339. RepoRelPath := ctx.Repo.Owner.Name + "/" + ctx.Repo.Repository.Name
  1340. errorMessage := ctx.Tr("repo.pulls.has_pull_request", html.EscapeString(ctx.Repo.RepoLink+"/pulls/"+strconv.FormatInt(err.IssueID, 10)), html.EscapeString(RepoRelPath), err.IssueID) // FIXME: Creates url inside locale string
  1341. ctx.Flash.Error(errorMessage)
  1342. ctx.JSON(http.StatusConflict, map[string]any{
  1343. "error": err.Error(),
  1344. "user_error": errorMessage,
  1345. })
  1346. } else if issues_model.IsErrIssueIsClosed(err) {
  1347. errorMessage := ctx.Tr("repo.pulls.is_closed")
  1348. ctx.Flash.Error(errorMessage)
  1349. ctx.JSON(http.StatusConflict, map[string]any{
  1350. "error": err.Error(),
  1351. "user_error": errorMessage,
  1352. })
  1353. } else if models.IsErrPullRequestHasMerged(err) {
  1354. errorMessage := ctx.Tr("repo.pulls.has_merged")
  1355. ctx.Flash.Error(errorMessage)
  1356. ctx.JSON(http.StatusConflict, map[string]any{
  1357. "error": err.Error(),
  1358. "user_error": errorMessage,
  1359. })
  1360. } else if git_model.IsErrBranchesEqual(err) {
  1361. errorMessage := ctx.Tr("repo.pulls.nothing_to_compare")
  1362. ctx.Flash.Error(errorMessage)
  1363. ctx.JSON(http.StatusBadRequest, map[string]any{
  1364. "error": err.Error(),
  1365. "user_error": errorMessage,
  1366. })
  1367. } else {
  1368. ctx.ServerError("UpdatePullRequestTarget", err)
  1369. }
  1370. return
  1371. }
  1372. notify_service.PullRequestChangeTargetBranch(ctx, ctx.Doer, pr, targetBranch)
  1373. ctx.JSON(http.StatusOK, map[string]any{
  1374. "base_branch": pr.BaseBranch,
  1375. })
  1376. }
  1377. // SetAllowEdits allow edits from maintainers to PRs
  1378. func SetAllowEdits(ctx *context.Context) {
  1379. form := web.GetForm(ctx).(*forms.UpdateAllowEditsForm)
  1380. pr, err := issues_model.GetPullRequestByIndex(ctx, ctx.Repo.Repository.ID, ctx.ParamsInt64(":index"))
  1381. if err != nil {
  1382. if issues_model.IsErrPullRequestNotExist(err) {
  1383. ctx.NotFound("GetPullRequestByIndex", err)
  1384. } else {
  1385. ctx.ServerError("GetPullRequestByIndex", err)
  1386. }
  1387. return
  1388. }
  1389. if err := pull_service.SetAllowEdits(ctx, ctx.Doer, pr, form.AllowMaintainerEdit); err != nil {
  1390. if errors.Is(pull_service.ErrUserHasNoPermissionForAction, err) {
  1391. ctx.Error(http.StatusForbidden)
  1392. return
  1393. }
  1394. ctx.ServerError("SetAllowEdits", err)
  1395. return
  1396. }
  1397. ctx.JSON(http.StatusOK, map[string]any{
  1398. "allow_maintainer_edit": pr.AllowMaintainerEdit,
  1399. })
  1400. }