Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614
  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 err := stopTimerIfAvailable(ctx, ctx.Doer, issue); err != nil {
  1013. ctx.ServerError("stopTimerIfAvailable", err)
  1014. return
  1015. }
  1016. log.Trace("Pull request merged: %d", pr.ID)
  1017. if form.DeleteBranchAfterMerge {
  1018. // Don't cleanup when other pr use this branch as head branch
  1019. exist, err := issues_model.HasUnmergedPullRequestsByHeadInfo(ctx, pr.HeadRepoID, pr.HeadBranch)
  1020. if err != nil {
  1021. ctx.ServerError("HasUnmergedPullRequestsByHeadInfo", err)
  1022. return
  1023. }
  1024. if exist {
  1025. ctx.JSONRedirect(issue.Link())
  1026. return
  1027. }
  1028. var headRepo *git.Repository
  1029. if ctx.Repo != nil && ctx.Repo.Repository != nil && pr.HeadRepoID == ctx.Repo.Repository.ID && ctx.Repo.GitRepo != nil {
  1030. headRepo = ctx.Repo.GitRepo
  1031. } else {
  1032. headRepo, err = gitrepo.OpenRepository(ctx, pr.HeadRepo)
  1033. if err != nil {
  1034. ctx.ServerError(fmt.Sprintf("OpenRepository[%s]", pr.HeadRepo.FullName()), err)
  1035. return
  1036. }
  1037. defer headRepo.Close()
  1038. }
  1039. deleteBranch(ctx, pr, headRepo)
  1040. }
  1041. ctx.JSONRedirect(issue.Link())
  1042. }
  1043. // CancelAutoMergePullRequest cancels a scheduled pr
  1044. func CancelAutoMergePullRequest(ctx *context.Context) {
  1045. issue, ok := getPullInfo(ctx)
  1046. if !ok {
  1047. return
  1048. }
  1049. if err := automerge.RemoveScheduledAutoMerge(ctx, ctx.Doer, issue.PullRequest); err != nil {
  1050. if db.IsErrNotExist(err) {
  1051. ctx.Flash.Error(ctx.Tr("repo.pulls.auto_merge_not_scheduled"))
  1052. ctx.Redirect(fmt.Sprintf("%s/pulls/%d", ctx.Repo.RepoLink, issue.Index))
  1053. return
  1054. }
  1055. ctx.ServerError("RemoveScheduledAutoMerge", err)
  1056. return
  1057. }
  1058. ctx.Flash.Success(ctx.Tr("repo.pulls.auto_merge_canceled_schedule"))
  1059. ctx.Redirect(fmt.Sprintf("%s/pulls/%d", ctx.Repo.RepoLink, issue.Index))
  1060. }
  1061. func stopTimerIfAvailable(ctx *context.Context, user *user_model.User, issue *issues_model.Issue) error {
  1062. if issues_model.StopwatchExists(ctx, user.ID, issue.ID) {
  1063. if err := issues_model.CreateOrStopIssueStopwatch(ctx, user, issue); err != nil {
  1064. return err
  1065. }
  1066. }
  1067. return nil
  1068. }
  1069. // CompareAndPullRequestPost response for creating pull request
  1070. func CompareAndPullRequestPost(ctx *context.Context) {
  1071. form := web.GetForm(ctx).(*forms.CreateIssueForm)
  1072. ctx.Data["Title"] = ctx.Tr("repo.pulls.compare_changes")
  1073. ctx.Data["PageIsComparePull"] = true
  1074. ctx.Data["IsDiffCompare"] = true
  1075. ctx.Data["IsRepoToolbarCommits"] = true
  1076. ctx.Data["PullRequestWorkInProgressPrefixes"] = setting.Repository.PullRequest.WorkInProgressPrefixes
  1077. ctx.Data["IsAttachmentEnabled"] = setting.Attachment.Enabled
  1078. upload.AddUploadContext(ctx, "comment")
  1079. ctx.Data["HasIssuesOrPullsWritePermission"] = ctx.Repo.CanWrite(unit.TypePullRequests)
  1080. var (
  1081. repo = ctx.Repo.Repository
  1082. attachments []string
  1083. )
  1084. ci := ParseCompareInfo(ctx)
  1085. defer func() {
  1086. if ci != nil && ci.HeadGitRepo != nil {
  1087. ci.HeadGitRepo.Close()
  1088. }
  1089. }()
  1090. if ctx.Written() {
  1091. return
  1092. }
  1093. labelIDs, assigneeIDs, milestoneID, projectID := ValidateRepoMetas(ctx, *form, true)
  1094. if ctx.Written() {
  1095. return
  1096. }
  1097. if setting.Attachment.Enabled {
  1098. attachments = form.Files
  1099. }
  1100. if ctx.HasError() {
  1101. ctx.JSONError(ctx.GetErrMsg())
  1102. return
  1103. }
  1104. if util.IsEmptyString(form.Title) {
  1105. ctx.JSONError(ctx.Tr("repo.issues.new.title_empty"))
  1106. return
  1107. }
  1108. content := form.Content
  1109. if filename := ctx.Req.Form.Get("template-file"); filename != "" {
  1110. if template, err := issue_template.UnmarshalFromRepo(ctx.Repo.GitRepo, ctx.Repo.Repository.DefaultBranch, filename); err == nil {
  1111. content = issue_template.RenderToMarkdown(template, ctx.Req.Form)
  1112. }
  1113. }
  1114. pullIssue := &issues_model.Issue{
  1115. RepoID: repo.ID,
  1116. Repo: repo,
  1117. Title: form.Title,
  1118. PosterID: ctx.Doer.ID,
  1119. Poster: ctx.Doer,
  1120. MilestoneID: milestoneID,
  1121. IsPull: true,
  1122. Content: content,
  1123. }
  1124. pullRequest := &issues_model.PullRequest{
  1125. HeadRepoID: ci.HeadRepo.ID,
  1126. BaseRepoID: repo.ID,
  1127. HeadBranch: ci.HeadBranch,
  1128. BaseBranch: ci.BaseBranch,
  1129. HeadRepo: ci.HeadRepo,
  1130. BaseRepo: repo,
  1131. MergeBase: ci.CompareInfo.MergeBase,
  1132. Type: issues_model.PullRequestGitea,
  1133. AllowMaintainerEdit: form.AllowMaintainerEdit,
  1134. }
  1135. // FIXME: check error in the case two people send pull request at almost same time, give nice error prompt
  1136. // instead of 500.
  1137. if err := pull_service.NewPullRequest(ctx, repo, pullIssue, labelIDs, attachments, pullRequest, assigneeIDs); err != nil {
  1138. if repo_model.IsErrUserDoesNotHaveAccessToRepo(err) {
  1139. ctx.Error(http.StatusBadRequest, "UserDoesNotHaveAccessToRepo", err.Error())
  1140. } else if git.IsErrPushRejected(err) {
  1141. pushrejErr := err.(*git.ErrPushRejected)
  1142. message := pushrejErr.Message
  1143. if len(message) == 0 {
  1144. ctx.JSONError(ctx.Tr("repo.pulls.push_rejected_no_message"))
  1145. return
  1146. }
  1147. flashError, err := ctx.RenderToHTML(tplAlertDetails, map[string]any{
  1148. "Message": ctx.Tr("repo.pulls.push_rejected"),
  1149. "Summary": ctx.Tr("repo.pulls.push_rejected_summary"),
  1150. "Details": utils.SanitizeFlashErrorString(pushrejErr.Message),
  1151. })
  1152. if err != nil {
  1153. ctx.ServerError("CompareAndPullRequest.HTMLString", err)
  1154. return
  1155. }
  1156. ctx.JSONError(flashError)
  1157. } else if errors.Is(err, user_model.ErrBlockedUser) {
  1158. flashError, err := ctx.RenderToHTML(tplAlertDetails, map[string]any{
  1159. "Message": ctx.Tr("repo.pulls.push_rejected"),
  1160. "Summary": ctx.Tr("repo.pulls.new.blocked_user"),
  1161. })
  1162. if err != nil {
  1163. ctx.ServerError("CompareAndPullRequest.HTMLString", err)
  1164. return
  1165. }
  1166. ctx.JSONError(flashError)
  1167. }
  1168. return
  1169. }
  1170. if projectID > 0 {
  1171. if !ctx.Repo.CanWrite(unit.TypeProjects) {
  1172. ctx.Error(http.StatusBadRequest, "user hasn't the permission to write to projects")
  1173. return
  1174. }
  1175. if err := issues_model.ChangeProjectAssign(ctx, pullIssue, ctx.Doer, projectID); err != nil {
  1176. ctx.ServerError("ChangeProjectAssign", err)
  1177. return
  1178. }
  1179. }
  1180. log.Trace("Pull request created: %d/%d", repo.ID, pullIssue.ID)
  1181. ctx.JSONRedirect(pullIssue.Link())
  1182. }
  1183. // CleanUpPullRequest responses for delete merged branch when PR has been merged
  1184. func CleanUpPullRequest(ctx *context.Context) {
  1185. issue, ok := getPullInfo(ctx)
  1186. if !ok {
  1187. return
  1188. }
  1189. pr := issue.PullRequest
  1190. // Don't cleanup unmerged and unclosed PRs
  1191. if !pr.HasMerged && !issue.IsClosed {
  1192. ctx.NotFound("CleanUpPullRequest", nil)
  1193. return
  1194. }
  1195. // Don't cleanup when there are other PR's that use this branch as head branch.
  1196. exist, err := issues_model.HasUnmergedPullRequestsByHeadInfo(ctx, pr.HeadRepoID, pr.HeadBranch)
  1197. if err != nil {
  1198. ctx.ServerError("HasUnmergedPullRequestsByHeadInfo", err)
  1199. return
  1200. }
  1201. if exist {
  1202. ctx.NotFound("CleanUpPullRequest", nil)
  1203. return
  1204. }
  1205. if err := pr.LoadHeadRepo(ctx); err != nil {
  1206. ctx.ServerError("LoadHeadRepo", err)
  1207. return
  1208. } else if pr.HeadRepo == nil {
  1209. // Forked repository has already been deleted
  1210. ctx.NotFound("CleanUpPullRequest", nil)
  1211. return
  1212. } else if err = pr.LoadBaseRepo(ctx); err != nil {
  1213. ctx.ServerError("LoadBaseRepo", err)
  1214. return
  1215. } else if err = pr.HeadRepo.LoadOwner(ctx); err != nil {
  1216. ctx.ServerError("HeadRepo.LoadOwner", err)
  1217. return
  1218. }
  1219. perm, err := access_model.GetUserRepoPermission(ctx, pr.HeadRepo, ctx.Doer)
  1220. if err != nil {
  1221. ctx.ServerError("GetUserRepoPermission", err)
  1222. return
  1223. }
  1224. if !perm.CanWrite(unit.TypeCode) {
  1225. ctx.NotFound("CleanUpPullRequest", nil)
  1226. return
  1227. }
  1228. fullBranchName := pr.HeadRepo.Owner.Name + "/" + pr.HeadBranch
  1229. var gitBaseRepo *git.Repository
  1230. // Assume that the base repo is the current context (almost certainly)
  1231. if ctx.Repo != nil && ctx.Repo.Repository != nil && ctx.Repo.Repository.ID == pr.BaseRepoID && ctx.Repo.GitRepo != nil {
  1232. gitBaseRepo = ctx.Repo.GitRepo
  1233. } else {
  1234. // If not just open it
  1235. gitBaseRepo, err = gitrepo.OpenRepository(ctx, pr.BaseRepo)
  1236. if err != nil {
  1237. ctx.ServerError(fmt.Sprintf("OpenRepository[%s]", pr.BaseRepo.FullName()), err)
  1238. return
  1239. }
  1240. defer gitBaseRepo.Close()
  1241. }
  1242. // Now assume that the head repo is the same as the base repo (reasonable chance)
  1243. gitRepo := gitBaseRepo
  1244. // But if not: is it the same as the context?
  1245. if pr.BaseRepoID != pr.HeadRepoID && ctx.Repo != nil && ctx.Repo.Repository != nil && ctx.Repo.Repository.ID == pr.HeadRepoID && ctx.Repo.GitRepo != nil {
  1246. gitRepo = ctx.Repo.GitRepo
  1247. } else if pr.BaseRepoID != pr.HeadRepoID {
  1248. // Otherwise just load it up
  1249. gitRepo, err = gitrepo.OpenRepository(ctx, pr.HeadRepo)
  1250. if err != nil {
  1251. ctx.ServerError(fmt.Sprintf("OpenRepository[%s]", pr.HeadRepo.FullName()), err)
  1252. return
  1253. }
  1254. defer gitRepo.Close()
  1255. }
  1256. defer func() {
  1257. ctx.JSONRedirect(issue.Link())
  1258. }()
  1259. // Check if branch has no new commits
  1260. headCommitID, err := gitBaseRepo.GetRefCommitID(pr.GetGitRefName())
  1261. if err != nil {
  1262. log.Error("GetRefCommitID: %v", err)
  1263. ctx.Flash.Error(ctx.Tr("repo.branch.deletion_failed", fullBranchName))
  1264. return
  1265. }
  1266. branchCommitID, err := gitRepo.GetBranchCommitID(pr.HeadBranch)
  1267. if err != nil {
  1268. log.Error("GetBranchCommitID: %v", err)
  1269. ctx.Flash.Error(ctx.Tr("repo.branch.deletion_failed", fullBranchName))
  1270. return
  1271. }
  1272. if headCommitID != branchCommitID {
  1273. ctx.Flash.Error(ctx.Tr("repo.branch.delete_branch_has_new_commits", fullBranchName))
  1274. return
  1275. }
  1276. deleteBranch(ctx, pr, gitRepo)
  1277. }
  1278. func deleteBranch(ctx *context.Context, pr *issues_model.PullRequest, gitRepo *git.Repository) {
  1279. fullBranchName := pr.HeadRepo.FullName() + ":" + pr.HeadBranch
  1280. if err := pull_service.RetargetChildrenOnMerge(ctx, ctx.Doer, pr); err != nil {
  1281. ctx.Flash.Error(ctx.Tr("repo.branch.deletion_failed", fullBranchName))
  1282. return
  1283. }
  1284. if err := repo_service.DeleteBranch(ctx, ctx.Doer, pr.HeadRepo, gitRepo, pr.HeadBranch); err != nil {
  1285. switch {
  1286. case git.IsErrBranchNotExist(err):
  1287. ctx.Flash.Error(ctx.Tr("repo.branch.deletion_failed", fullBranchName))
  1288. case errors.Is(err, repo_service.ErrBranchIsDefault):
  1289. ctx.Flash.Error(ctx.Tr("repo.branch.deletion_failed", fullBranchName))
  1290. case errors.Is(err, git_model.ErrBranchIsProtected):
  1291. ctx.Flash.Error(ctx.Tr("repo.branch.deletion_failed", fullBranchName))
  1292. default:
  1293. log.Error("DeleteBranch: %v", err)
  1294. ctx.Flash.Error(ctx.Tr("repo.branch.deletion_failed", fullBranchName))
  1295. }
  1296. return
  1297. }
  1298. if err := issues_model.AddDeletePRBranchComment(ctx, ctx.Doer, pr.BaseRepo, pr.IssueID, pr.HeadBranch); err != nil {
  1299. // Do not fail here as branch has already been deleted
  1300. log.Error("DeleteBranch: %v", err)
  1301. }
  1302. ctx.Flash.Success(ctx.Tr("repo.branch.deletion_success", fullBranchName))
  1303. }
  1304. // DownloadPullDiff render a pull's raw diff
  1305. func DownloadPullDiff(ctx *context.Context) {
  1306. DownloadPullDiffOrPatch(ctx, false)
  1307. }
  1308. // DownloadPullPatch render a pull's raw patch
  1309. func DownloadPullPatch(ctx *context.Context) {
  1310. DownloadPullDiffOrPatch(ctx, true)
  1311. }
  1312. // DownloadPullDiffOrPatch render a pull's raw diff or patch
  1313. func DownloadPullDiffOrPatch(ctx *context.Context, patch bool) {
  1314. pr, err := issues_model.GetPullRequestByIndex(ctx, ctx.Repo.Repository.ID, ctx.ParamsInt64(":index"))
  1315. if err != nil {
  1316. if issues_model.IsErrPullRequestNotExist(err) {
  1317. ctx.NotFound("GetPullRequestByIndex", err)
  1318. } else {
  1319. ctx.ServerError("GetPullRequestByIndex", err)
  1320. }
  1321. return
  1322. }
  1323. binary := ctx.FormBool("binary")
  1324. if err := pull_service.DownloadDiffOrPatch(ctx, pr, ctx, patch, binary); err != nil {
  1325. ctx.ServerError("DownloadDiffOrPatch", err)
  1326. return
  1327. }
  1328. }
  1329. // UpdatePullRequestTarget change pull request's target branch
  1330. func UpdatePullRequestTarget(ctx *context.Context) {
  1331. issue := GetActionIssue(ctx)
  1332. if ctx.Written() {
  1333. return
  1334. }
  1335. pr := issue.PullRequest
  1336. if !issue.IsPull {
  1337. ctx.Error(http.StatusNotFound)
  1338. return
  1339. }
  1340. if !ctx.IsSigned || (!issue.IsPoster(ctx.Doer.ID) && !ctx.Repo.CanWriteIssuesOrPulls(issue.IsPull)) {
  1341. ctx.Error(http.StatusForbidden)
  1342. return
  1343. }
  1344. targetBranch := ctx.FormTrim("target_branch")
  1345. if len(targetBranch) == 0 {
  1346. ctx.Error(http.StatusNoContent)
  1347. return
  1348. }
  1349. if err := pull_service.ChangeTargetBranch(ctx, pr, ctx.Doer, targetBranch); err != nil {
  1350. if issues_model.IsErrPullRequestAlreadyExists(err) {
  1351. err := err.(issues_model.ErrPullRequestAlreadyExists)
  1352. RepoRelPath := ctx.Repo.Owner.Name + "/" + ctx.Repo.Repository.Name
  1353. 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
  1354. ctx.Flash.Error(errorMessage)
  1355. ctx.JSON(http.StatusConflict, map[string]any{
  1356. "error": err.Error(),
  1357. "user_error": errorMessage,
  1358. })
  1359. } else if issues_model.IsErrIssueIsClosed(err) {
  1360. errorMessage := ctx.Tr("repo.pulls.is_closed")
  1361. ctx.Flash.Error(errorMessage)
  1362. ctx.JSON(http.StatusConflict, map[string]any{
  1363. "error": err.Error(),
  1364. "user_error": errorMessage,
  1365. })
  1366. } else if models.IsErrPullRequestHasMerged(err) {
  1367. errorMessage := ctx.Tr("repo.pulls.has_merged")
  1368. ctx.Flash.Error(errorMessage)
  1369. ctx.JSON(http.StatusConflict, map[string]any{
  1370. "error": err.Error(),
  1371. "user_error": errorMessage,
  1372. })
  1373. } else if git_model.IsErrBranchesEqual(err) {
  1374. errorMessage := ctx.Tr("repo.pulls.nothing_to_compare")
  1375. ctx.Flash.Error(errorMessage)
  1376. ctx.JSON(http.StatusBadRequest, map[string]any{
  1377. "error": err.Error(),
  1378. "user_error": errorMessage,
  1379. })
  1380. } else {
  1381. ctx.ServerError("UpdatePullRequestTarget", err)
  1382. }
  1383. return
  1384. }
  1385. notify_service.PullRequestChangeTargetBranch(ctx, ctx.Doer, pr, targetBranch)
  1386. ctx.JSON(http.StatusOK, map[string]any{
  1387. "base_branch": pr.BaseBranch,
  1388. })
  1389. }
  1390. // SetAllowEdits allow edits from maintainers to PRs
  1391. func SetAllowEdits(ctx *context.Context) {
  1392. form := web.GetForm(ctx).(*forms.UpdateAllowEditsForm)
  1393. pr, err := issues_model.GetPullRequestByIndex(ctx, ctx.Repo.Repository.ID, ctx.ParamsInt64(":index"))
  1394. if err != nil {
  1395. if issues_model.IsErrPullRequestNotExist(err) {
  1396. ctx.NotFound("GetPullRequestByIndex", err)
  1397. } else {
  1398. ctx.ServerError("GetPullRequestByIndex", err)
  1399. }
  1400. return
  1401. }
  1402. if err := pull_service.SetAllowEdits(ctx, ctx.Doer, pr, form.AllowMaintainerEdit); err != nil {
  1403. if errors.Is(pull_service.ErrUserHasNoPermissionForAction, err) {
  1404. ctx.Error(http.StatusForbidden)
  1405. return
  1406. }
  1407. ctx.ServerError("SetAllowEdits", err)
  1408. return
  1409. }
  1410. ctx.JSON(http.StatusOK, map[string]any{
  1411. "allow_maintainer_edit": pr.AllowMaintainerEdit,
  1412. })
  1413. }