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

pull.go 33KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200
  1. // Copyright 2018 The Gitea Authors.
  2. // Copyright 2014 The Gogs Authors.
  3. // All rights reserved.
  4. // Use of this source code is governed by a MIT-style
  5. // license that can be found in the LICENSE file.
  6. package repo
  7. import (
  8. "container/list"
  9. "crypto/subtle"
  10. "fmt"
  11. "html"
  12. "net/http"
  13. "path"
  14. "strings"
  15. "time"
  16. "code.gitea.io/gitea/models"
  17. "code.gitea.io/gitea/modules/auth"
  18. "code.gitea.io/gitea/modules/base"
  19. "code.gitea.io/gitea/modules/context"
  20. "code.gitea.io/gitea/modules/git"
  21. "code.gitea.io/gitea/modules/log"
  22. "code.gitea.io/gitea/modules/notification"
  23. "code.gitea.io/gitea/modules/repofiles"
  24. "code.gitea.io/gitea/modules/setting"
  25. "code.gitea.io/gitea/modules/util"
  26. "code.gitea.io/gitea/routers/utils"
  27. "code.gitea.io/gitea/services/gitdiff"
  28. pull_service "code.gitea.io/gitea/services/pull"
  29. repo_service "code.gitea.io/gitea/services/repository"
  30. "github.com/unknwon/com"
  31. )
  32. const (
  33. tplFork base.TplName = "repo/pulls/fork"
  34. tplCompareDiff base.TplName = "repo/diff/compare"
  35. tplPullCommits base.TplName = "repo/pulls/commits"
  36. tplPullFiles base.TplName = "repo/pulls/files"
  37. pullRequestTemplateKey = "PullRequestTemplate"
  38. )
  39. var (
  40. pullRequestTemplateCandidates = []string{
  41. "PULL_REQUEST_TEMPLATE.md",
  42. "pull_request_template.md",
  43. ".gitea/PULL_REQUEST_TEMPLATE.md",
  44. ".gitea/pull_request_template.md",
  45. ".github/PULL_REQUEST_TEMPLATE.md",
  46. ".github/pull_request_template.md",
  47. }
  48. )
  49. func getRepository(ctx *context.Context, repoID int64) *models.Repository {
  50. repo, err := models.GetRepositoryByID(repoID)
  51. if err != nil {
  52. if models.IsErrRepoNotExist(err) {
  53. ctx.NotFound("GetRepositoryByID", nil)
  54. } else {
  55. ctx.ServerError("GetRepositoryByID", err)
  56. }
  57. return nil
  58. }
  59. perm, err := models.GetUserRepoPermission(repo, ctx.User)
  60. if err != nil {
  61. ctx.ServerError("GetUserRepoPermission", err)
  62. return nil
  63. }
  64. if !perm.CanRead(models.UnitTypeCode) {
  65. log.Trace("Permission Denied: User %-v cannot read %-v of repo %-v\n"+
  66. "User in repo has Permissions: %-+v",
  67. ctx.User,
  68. models.UnitTypeCode,
  69. ctx.Repo,
  70. perm)
  71. ctx.NotFound("getRepository", nil)
  72. return nil
  73. }
  74. return repo
  75. }
  76. func getForkRepository(ctx *context.Context) *models.Repository {
  77. forkRepo := getRepository(ctx, ctx.ParamsInt64(":repoid"))
  78. if ctx.Written() {
  79. return nil
  80. }
  81. if forkRepo.IsEmpty {
  82. log.Trace("Empty repository %-v", forkRepo)
  83. ctx.NotFound("getForkRepository", nil)
  84. return nil
  85. }
  86. ctx.Data["repo_name"] = forkRepo.Name
  87. ctx.Data["description"] = forkRepo.Description
  88. ctx.Data["IsPrivate"] = forkRepo.IsPrivate
  89. canForkToUser := forkRepo.OwnerID != ctx.User.ID && !ctx.User.HasForkedRepo(forkRepo.ID)
  90. if err := forkRepo.GetOwner(); err != nil {
  91. ctx.ServerError("GetOwner", err)
  92. return nil
  93. }
  94. ctx.Data["ForkFrom"] = forkRepo.Owner.Name + "/" + forkRepo.Name
  95. ctx.Data["ForkFromOwnerID"] = forkRepo.Owner.ID
  96. if err := ctx.User.GetOwnedOrganizations(); err != nil {
  97. ctx.ServerError("GetOwnedOrganizations", err)
  98. return nil
  99. }
  100. var orgs []*models.User
  101. for _, org := range ctx.User.OwnedOrgs {
  102. if forkRepo.OwnerID != org.ID && !org.HasForkedRepo(forkRepo.ID) {
  103. orgs = append(orgs, org)
  104. }
  105. }
  106. var traverseParentRepo = forkRepo
  107. var err error
  108. for {
  109. if ctx.User.ID == traverseParentRepo.OwnerID {
  110. canForkToUser = false
  111. } else {
  112. for i, org := range orgs {
  113. if org.ID == traverseParentRepo.OwnerID {
  114. orgs = append(orgs[:i], orgs[i+1:]...)
  115. break
  116. }
  117. }
  118. }
  119. if !traverseParentRepo.IsFork {
  120. break
  121. }
  122. traverseParentRepo, err = models.GetRepositoryByID(traverseParentRepo.ForkID)
  123. if err != nil {
  124. ctx.ServerError("GetRepositoryByID", err)
  125. return nil
  126. }
  127. }
  128. ctx.Data["CanForkToUser"] = canForkToUser
  129. ctx.Data["Orgs"] = orgs
  130. if canForkToUser {
  131. ctx.Data["ContextUser"] = ctx.User
  132. } else if len(orgs) > 0 {
  133. ctx.Data["ContextUser"] = orgs[0]
  134. }
  135. return forkRepo
  136. }
  137. // Fork render repository fork page
  138. func Fork(ctx *context.Context) {
  139. ctx.Data["Title"] = ctx.Tr("new_fork")
  140. getForkRepository(ctx)
  141. if ctx.Written() {
  142. return
  143. }
  144. ctx.HTML(200, tplFork)
  145. }
  146. // ForkPost response for forking a repository
  147. func ForkPost(ctx *context.Context, form auth.CreateRepoForm) {
  148. ctx.Data["Title"] = ctx.Tr("new_fork")
  149. ctxUser := checkContextUser(ctx, form.UID)
  150. if ctx.Written() {
  151. return
  152. }
  153. forkRepo := getForkRepository(ctx)
  154. if ctx.Written() {
  155. return
  156. }
  157. ctx.Data["ContextUser"] = ctxUser
  158. if ctx.HasError() {
  159. ctx.HTML(200, tplFork)
  160. return
  161. }
  162. var err error
  163. var traverseParentRepo = forkRepo
  164. for {
  165. if ctxUser.ID == traverseParentRepo.OwnerID {
  166. ctx.RenderWithErr(ctx.Tr("repo.settings.new_owner_has_same_repo"), tplFork, &form)
  167. return
  168. }
  169. repo, has := models.HasForkedRepo(ctxUser.ID, traverseParentRepo.ID)
  170. if has {
  171. ctx.Redirect(setting.AppSubURL + "/" + ctxUser.Name + "/" + repo.Name)
  172. return
  173. }
  174. if !traverseParentRepo.IsFork {
  175. break
  176. }
  177. traverseParentRepo, err = models.GetRepositoryByID(traverseParentRepo.ForkID)
  178. if err != nil {
  179. ctx.ServerError("GetRepositoryByID", err)
  180. return
  181. }
  182. }
  183. // Check ownership of organization.
  184. if ctxUser.IsOrganization() {
  185. isOwner, err := ctxUser.IsOwnedBy(ctx.User.ID)
  186. if err != nil {
  187. ctx.ServerError("IsOwnedBy", err)
  188. return
  189. } else if !isOwner {
  190. ctx.Error(403)
  191. return
  192. }
  193. }
  194. repo, err := repo_service.ForkRepository(ctx.User, ctxUser, forkRepo, form.RepoName, form.Description)
  195. if err != nil {
  196. ctx.Data["Err_RepoName"] = true
  197. switch {
  198. case models.IsErrRepoAlreadyExist(err):
  199. ctx.RenderWithErr(ctx.Tr("repo.settings.new_owner_has_same_repo"), tplFork, &form)
  200. case models.IsErrNameReserved(err):
  201. ctx.RenderWithErr(ctx.Tr("repo.form.name_reserved", err.(models.ErrNameReserved).Name), tplFork, &form)
  202. case models.IsErrNamePatternNotAllowed(err):
  203. ctx.RenderWithErr(ctx.Tr("repo.form.name_pattern_not_allowed", err.(models.ErrNamePatternNotAllowed).Pattern), tplFork, &form)
  204. default:
  205. ctx.ServerError("ForkPost", err)
  206. }
  207. return
  208. }
  209. log.Trace("Repository forked[%d]: %s/%s", forkRepo.ID, ctxUser.Name, repo.Name)
  210. ctx.Redirect(setting.AppSubURL + "/" + ctxUser.Name + "/" + repo.Name)
  211. }
  212. func checkPullInfo(ctx *context.Context) *models.Issue {
  213. issue, err := models.GetIssueByIndex(ctx.Repo.Repository.ID, ctx.ParamsInt64(":index"))
  214. if err != nil {
  215. if models.IsErrIssueNotExist(err) {
  216. ctx.NotFound("GetIssueByIndex", err)
  217. } else {
  218. ctx.ServerError("GetIssueByIndex", err)
  219. }
  220. return nil
  221. }
  222. if err = issue.LoadPoster(); err != nil {
  223. ctx.ServerError("LoadPoster", err)
  224. return nil
  225. }
  226. if err := issue.LoadRepo(); err != nil {
  227. ctx.ServerError("LoadRepo", err)
  228. return nil
  229. }
  230. ctx.Data["Title"] = fmt.Sprintf("#%d - %s", issue.Index, issue.Title)
  231. ctx.Data["Issue"] = issue
  232. if !issue.IsPull {
  233. ctx.NotFound("ViewPullCommits", nil)
  234. return nil
  235. }
  236. if err = issue.LoadPullRequest(); err != nil {
  237. ctx.ServerError("LoadPullRequest", err)
  238. return nil
  239. }
  240. if err = issue.PullRequest.GetHeadRepo(); err != nil {
  241. ctx.ServerError("GetHeadRepo", err)
  242. return nil
  243. }
  244. if ctx.IsSigned {
  245. // Update issue-user.
  246. if err = issue.ReadBy(ctx.User.ID); err != nil {
  247. ctx.ServerError("ReadBy", err)
  248. return nil
  249. }
  250. }
  251. return issue
  252. }
  253. func setMergeTarget(ctx *context.Context, pull *models.PullRequest) {
  254. if ctx.Repo.Owner.Name == pull.MustHeadUserName() {
  255. ctx.Data["HeadTarget"] = pull.HeadBranch
  256. } else if pull.HeadRepo == nil {
  257. ctx.Data["HeadTarget"] = pull.MustHeadUserName() + ":" + pull.HeadBranch
  258. } else {
  259. ctx.Data["HeadTarget"] = pull.MustHeadUserName() + "/" + pull.HeadRepo.Name + ":" + pull.HeadBranch
  260. }
  261. ctx.Data["BaseTarget"] = pull.BaseBranch
  262. }
  263. // PrepareMergedViewPullInfo show meta information for a merged pull request view page
  264. func PrepareMergedViewPullInfo(ctx *context.Context, issue *models.Issue) *git.CompareInfo {
  265. pull := issue.PullRequest
  266. setMergeTarget(ctx, pull)
  267. ctx.Data["HasMerged"] = true
  268. compareInfo, err := ctx.Repo.GitRepo.GetCompareInfo(ctx.Repo.Repository.RepoPath(),
  269. pull.MergeBase, pull.GetGitRefName())
  270. if err != nil {
  271. if strings.Contains(err.Error(), "fatal: Not a valid object name") {
  272. ctx.Data["IsPullRequestBroken"] = true
  273. ctx.Data["BaseTarget"] = "deleted"
  274. ctx.Data["NumCommits"] = 0
  275. ctx.Data["NumFiles"] = 0
  276. return nil
  277. }
  278. ctx.ServerError("GetCompareInfo", err)
  279. return nil
  280. }
  281. ctx.Data["NumCommits"] = compareInfo.Commits.Len()
  282. ctx.Data["NumFiles"] = compareInfo.NumFiles
  283. return compareInfo
  284. }
  285. // PrepareViewPullInfo show meta information for a pull request preview page
  286. func PrepareViewPullInfo(ctx *context.Context, issue *models.Issue) *git.CompareInfo {
  287. repo := ctx.Repo.Repository
  288. pull := issue.PullRequest
  289. if err := pull.GetHeadRepo(); err != nil {
  290. ctx.ServerError("GetHeadRepo", err)
  291. return nil
  292. }
  293. if err := pull.GetBaseRepo(); err != nil {
  294. ctx.ServerError("GetBaseRepo", err)
  295. return nil
  296. }
  297. setMergeTarget(ctx, pull)
  298. if err := pull.LoadProtectedBranch(); err != nil {
  299. ctx.ServerError("LoadProtectedBranch", err)
  300. return nil
  301. }
  302. ctx.Data["EnableStatusCheck"] = pull.ProtectedBranch != nil && pull.ProtectedBranch.EnableStatusCheck
  303. baseGitRepo, err := git.OpenRepository(pull.BaseRepo.RepoPath())
  304. if err != nil {
  305. ctx.ServerError("OpenRepository", err)
  306. return nil
  307. }
  308. defer baseGitRepo.Close()
  309. var headBranchExist bool
  310. var headBranchSha string
  311. // HeadRepo may be missing
  312. if pull.HeadRepo != nil {
  313. var err error
  314. headGitRepo, err := git.OpenRepository(pull.HeadRepo.RepoPath())
  315. if err != nil {
  316. ctx.ServerError("OpenRepository", err)
  317. return nil
  318. }
  319. defer headGitRepo.Close()
  320. headBranchExist = headGitRepo.IsBranchExist(pull.HeadBranch)
  321. if headBranchExist {
  322. headBranchSha, err = headGitRepo.GetBranchCommitID(pull.HeadBranch)
  323. if err != nil {
  324. ctx.ServerError("GetBranchCommitID", err)
  325. return nil
  326. }
  327. }
  328. }
  329. if headBranchExist {
  330. allowUpdate, err := pull_service.IsUserAllowedToUpdate(pull, ctx.User)
  331. if err != nil {
  332. ctx.ServerError("IsUserAllowedToUpdate", err)
  333. return nil
  334. }
  335. ctx.Data["UpdateAllowed"] = allowUpdate
  336. divergence, err := pull_service.GetDiverging(pull)
  337. if err != nil {
  338. ctx.ServerError("GetDiverging", err)
  339. return nil
  340. }
  341. ctx.Data["Divergence"] = divergence
  342. }
  343. sha, err := baseGitRepo.GetRefCommitID(pull.GetGitRefName())
  344. if err != nil {
  345. ctx.ServerError(fmt.Sprintf("GetRefCommitID(%s)", pull.GetGitRefName()), err)
  346. return nil
  347. }
  348. commitStatuses, err := models.GetLatestCommitStatus(repo, sha, 0)
  349. if err != nil {
  350. ctx.ServerError("GetLatestCommitStatus", err)
  351. return nil
  352. }
  353. if len(commitStatuses) > 0 {
  354. ctx.Data["LatestCommitStatuses"] = commitStatuses
  355. ctx.Data["LatestCommitStatus"] = models.CalcCommitStatus(commitStatuses)
  356. }
  357. if pull.ProtectedBranch != nil && pull.ProtectedBranch.EnableStatusCheck {
  358. ctx.Data["is_context_required"] = func(context string) bool {
  359. for _, c := range pull.ProtectedBranch.StatusCheckContexts {
  360. if c == context {
  361. return true
  362. }
  363. }
  364. return false
  365. }
  366. state := pull_service.MergeRequiredContextsCommitStatus(commitStatuses, pull.ProtectedBranch.StatusCheckContexts)
  367. ctx.Data["RequiredStatusCheckState"] = state
  368. ctx.Data["IsRequiredStatusCheckSuccess"] = state.IsSuccess()
  369. }
  370. ctx.Data["HeadBranchMovedOn"] = headBranchSha != sha
  371. ctx.Data["HeadBranchCommitID"] = headBranchSha
  372. ctx.Data["PullHeadCommitID"] = sha
  373. if pull.HeadRepo == nil || !headBranchExist || headBranchSha != sha {
  374. ctx.Data["IsPullRequestBroken"] = true
  375. ctx.Data["HeadTarget"] = "deleted"
  376. }
  377. compareInfo, err := baseGitRepo.GetCompareInfo(pull.BaseRepo.RepoPath(),
  378. pull.BaseBranch, pull.GetGitRefName())
  379. if err != nil {
  380. if strings.Contains(err.Error(), "fatal: Not a valid object name") {
  381. ctx.Data["IsPullRequestBroken"] = true
  382. ctx.Data["BaseTarget"] = "deleted"
  383. ctx.Data["NumCommits"] = 0
  384. ctx.Data["NumFiles"] = 0
  385. return nil
  386. }
  387. ctx.ServerError("GetCompareInfo", err)
  388. return nil
  389. }
  390. if pull.IsWorkInProgress() {
  391. ctx.Data["IsPullWorkInProgress"] = true
  392. ctx.Data["WorkInProgressPrefix"] = pull.GetWorkInProgressPrefix()
  393. }
  394. if pull.IsFilesConflicted() {
  395. ctx.Data["IsPullFilesConflicted"] = true
  396. ctx.Data["ConflictedFiles"] = pull.ConflictedFiles
  397. }
  398. ctx.Data["NumCommits"] = compareInfo.Commits.Len()
  399. ctx.Data["NumFiles"] = compareInfo.NumFiles
  400. return compareInfo
  401. }
  402. // ViewPullCommits show commits for a pull request
  403. func ViewPullCommits(ctx *context.Context) {
  404. ctx.Data["PageIsPullList"] = true
  405. ctx.Data["PageIsPullCommits"] = true
  406. issue := checkPullInfo(ctx)
  407. if ctx.Written() {
  408. return
  409. }
  410. pull := issue.PullRequest
  411. var commits *list.List
  412. var prInfo *git.CompareInfo
  413. if pull.HasMerged {
  414. prInfo = PrepareMergedViewPullInfo(ctx, issue)
  415. } else {
  416. prInfo = PrepareViewPullInfo(ctx, issue)
  417. }
  418. if ctx.Written() {
  419. return
  420. } else if prInfo == nil {
  421. ctx.NotFound("ViewPullCommits", nil)
  422. return
  423. }
  424. ctx.Data["Username"] = ctx.Repo.Owner.Name
  425. ctx.Data["Reponame"] = ctx.Repo.Repository.Name
  426. commits = prInfo.Commits
  427. commits = models.ValidateCommitsWithEmails(commits)
  428. commits = models.ParseCommitsWithSignature(commits, ctx.Repo.Repository)
  429. commits = models.ParseCommitsWithStatus(commits, ctx.Repo.Repository)
  430. ctx.Data["Commits"] = commits
  431. ctx.Data["CommitCount"] = commits.Len()
  432. getBranchData(ctx, issue)
  433. ctx.HTML(200, tplPullCommits)
  434. }
  435. // ViewPullFiles render pull request changed files list page
  436. func ViewPullFiles(ctx *context.Context) {
  437. ctx.Data["PageIsPullList"] = true
  438. ctx.Data["PageIsPullFiles"] = true
  439. issue := checkPullInfo(ctx)
  440. if ctx.Written() {
  441. return
  442. }
  443. pull := issue.PullRequest
  444. whitespaceFlags := map[string]string{
  445. "ignore-all": "-w",
  446. "ignore-change": "-b",
  447. "ignore-eol": "--ignore-space-at-eol",
  448. "": ""}
  449. var (
  450. diffRepoPath string
  451. startCommitID string
  452. endCommitID string
  453. gitRepo *git.Repository
  454. )
  455. var headTarget string
  456. var prInfo *git.CompareInfo
  457. if pull.HasMerged {
  458. prInfo = PrepareMergedViewPullInfo(ctx, issue)
  459. } else {
  460. prInfo = PrepareViewPullInfo(ctx, issue)
  461. }
  462. if ctx.Written() {
  463. return
  464. } else if prInfo == nil {
  465. ctx.NotFound("ViewPullFiles", nil)
  466. return
  467. }
  468. diffRepoPath = ctx.Repo.GitRepo.Path
  469. gitRepo = ctx.Repo.GitRepo
  470. headCommitID, err := gitRepo.GetRefCommitID(pull.GetGitRefName())
  471. if err != nil {
  472. ctx.ServerError("GetRefCommitID", err)
  473. return
  474. }
  475. startCommitID = prInfo.MergeBase
  476. endCommitID = headCommitID
  477. headTarget = path.Join(ctx.Repo.Owner.Name, ctx.Repo.Repository.Name)
  478. ctx.Data["Username"] = ctx.Repo.Owner.Name
  479. ctx.Data["Reponame"] = ctx.Repo.Repository.Name
  480. ctx.Data["AfterCommitID"] = endCommitID
  481. diff, err := gitdiff.GetDiffRangeWithWhitespaceBehavior(diffRepoPath,
  482. startCommitID, endCommitID, setting.Git.MaxGitDiffLines,
  483. setting.Git.MaxGitDiffLineCharacters, setting.Git.MaxGitDiffFiles,
  484. whitespaceFlags[ctx.Data["WhitespaceBehavior"].(string)])
  485. if err != nil {
  486. ctx.ServerError("GetDiffRangeWithWhitespaceBehavior", err)
  487. return
  488. }
  489. if err = diff.LoadComments(issue, ctx.User); err != nil {
  490. ctx.ServerError("LoadComments", err)
  491. return
  492. }
  493. ctx.Data["Diff"] = diff
  494. ctx.Data["DiffNotAvailable"] = diff.NumFiles() == 0
  495. baseCommit, err := ctx.Repo.GitRepo.GetCommit(startCommitID)
  496. if err != nil {
  497. ctx.ServerError("GetCommit", err)
  498. return
  499. }
  500. commit, err := gitRepo.GetCommit(endCommitID)
  501. if err != nil {
  502. ctx.ServerError("GetCommit", err)
  503. return
  504. }
  505. setImageCompareContext(ctx, baseCommit, commit)
  506. setPathsCompareContext(ctx, baseCommit, commit, headTarget)
  507. ctx.Data["RequireHighlightJS"] = true
  508. ctx.Data["RequireSimpleMDE"] = true
  509. ctx.Data["RequireTribute"] = true
  510. if ctx.Data["Assignees"], err = ctx.Repo.Repository.GetAssignees(); err != nil {
  511. ctx.ServerError("GetAssignees", err)
  512. return
  513. }
  514. ctx.Data["CurrentReview"], err = models.GetCurrentReview(ctx.User, issue)
  515. if err != nil && !models.IsErrReviewNotExist(err) {
  516. ctx.ServerError("GetCurrentReview", err)
  517. return
  518. }
  519. getBranchData(ctx, issue)
  520. ctx.HTML(200, tplPullFiles)
  521. }
  522. // UpdatePullRequest merge master into PR
  523. func UpdatePullRequest(ctx *context.Context) {
  524. issue := checkPullInfo(ctx)
  525. if ctx.Written() {
  526. return
  527. }
  528. if issue.IsClosed {
  529. ctx.NotFound("MergePullRequest", nil)
  530. return
  531. }
  532. if issue.PullRequest.HasMerged {
  533. ctx.NotFound("MergePullRequest", nil)
  534. return
  535. }
  536. if err := issue.PullRequest.LoadBaseRepo(); err != nil {
  537. ctx.InternalServerError(err)
  538. return
  539. }
  540. if err := issue.PullRequest.LoadHeadRepo(); err != nil {
  541. ctx.InternalServerError(err)
  542. return
  543. }
  544. allowedUpdate, err := pull_service.IsUserAllowedToUpdate(issue.PullRequest, ctx.User)
  545. if err != nil {
  546. ctx.ServerError("IsUserAllowedToMerge", err)
  547. return
  548. }
  549. // ToDo: add check if maintainers are allowed to change branch ... (need migration & co)
  550. if !allowedUpdate {
  551. ctx.Flash.Error(ctx.Tr("repo.pulls.update_not_allowed"))
  552. ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(issue.Index))
  553. return
  554. }
  555. // default merge commit message
  556. message := fmt.Sprintf("Merge branch '%s' into %s", issue.PullRequest.BaseBranch, issue.PullRequest.HeadBranch)
  557. if err = pull_service.Update(issue.PullRequest, ctx.User, message); err != nil {
  558. sanitize := func(x string) string {
  559. runes := []rune(x)
  560. if len(runes) > 512 {
  561. x = "..." + string(runes[len(runes)-512:])
  562. }
  563. return strings.Replace(html.EscapeString(x), "\n", "<br>", -1)
  564. }
  565. if models.IsErrMergeConflicts(err) {
  566. conflictError := err.(models.ErrMergeConflicts)
  567. ctx.Flash.Error(ctx.Tr("repo.pulls.merge_conflict", sanitize(conflictError.StdErr), sanitize(conflictError.StdOut)))
  568. ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(issue.Index))
  569. return
  570. }
  571. ctx.Flash.Error(err.Error())
  572. ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(issue.Index))
  573. }
  574. time.Sleep(1 * time.Second)
  575. ctx.Flash.Success(ctx.Tr("repo.pulls.update_branch_success"))
  576. ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(issue.Index))
  577. }
  578. // MergePullRequest response for merging pull request
  579. func MergePullRequest(ctx *context.Context, form auth.MergePullRequestForm) {
  580. issue := checkPullInfo(ctx)
  581. if ctx.Written() {
  582. return
  583. }
  584. if issue.IsClosed {
  585. if issue.IsPull {
  586. ctx.Flash.Error(ctx.Tr("repo.pulls.is_closed"))
  587. ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(issue.Index))
  588. return
  589. }
  590. ctx.Flash.Error(ctx.Tr("repo.issues.closed_title"))
  591. ctx.Redirect(ctx.Repo.RepoLink + "/issues/" + com.ToStr(issue.Index))
  592. return
  593. }
  594. pr := issue.PullRequest
  595. allowedMerge, err := pull_service.IsUserAllowedToMerge(pr, ctx.Repo.Permission, ctx.User)
  596. if err != nil {
  597. ctx.ServerError("IsUserAllowedToMerge", err)
  598. return
  599. }
  600. if !allowedMerge {
  601. ctx.Flash.Error(ctx.Tr("repo.pulls.update_not_allowed"))
  602. ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(issue.Index))
  603. return
  604. }
  605. if !pr.CanAutoMerge() {
  606. ctx.Flash.Error(ctx.Tr("repo.pulls.no_merge_not_ready"))
  607. ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(issue.Index))
  608. return
  609. }
  610. if pr.HasMerged {
  611. ctx.Flash.Error(ctx.Tr("repo.pulls.has_merged"))
  612. ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(issue.Index))
  613. return
  614. }
  615. if pr.IsWorkInProgress() {
  616. ctx.Flash.Error(ctx.Tr("repo.pulls.no_merge_wip"))
  617. ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(pr.Index))
  618. return
  619. }
  620. if err := pull_service.CheckPRReadyToMerge(pr); err != nil {
  621. if !models.IsErrNotAllowedToMerge(err) {
  622. ctx.ServerError("Merge PR status", err)
  623. return
  624. }
  625. if isRepoAdmin, err := models.IsUserRepoAdmin(pr.BaseRepo, ctx.User); err != nil {
  626. ctx.ServerError("IsUserRepoAdmin", err)
  627. return
  628. } else if !isRepoAdmin {
  629. ctx.Flash.Error(ctx.Tr("repo.pulls.no_merge_not_ready"))
  630. ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(pr.Index))
  631. return
  632. }
  633. }
  634. if ctx.HasError() {
  635. ctx.Flash.Error(ctx.Data["ErrorMsg"].(string))
  636. ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(pr.Index))
  637. return
  638. }
  639. message := strings.TrimSpace(form.MergeTitleField)
  640. if len(message) == 0 {
  641. if models.MergeStyle(form.Do) == models.MergeStyleMerge {
  642. message = pr.GetDefaultMergeMessage()
  643. }
  644. if models.MergeStyle(form.Do) == models.MergeStyleRebaseMerge {
  645. message = pr.GetDefaultMergeMessage()
  646. }
  647. if models.MergeStyle(form.Do) == models.MergeStyleSquash {
  648. message = pr.GetDefaultSquashMessage()
  649. }
  650. }
  651. form.MergeMessageField = strings.TrimSpace(form.MergeMessageField)
  652. if len(form.MergeMessageField) > 0 {
  653. message += "\n\n" + form.MergeMessageField
  654. }
  655. pr.Issue = issue
  656. pr.Issue.Repo = ctx.Repo.Repository
  657. noDeps, err := models.IssueNoDependenciesLeft(issue)
  658. if err != nil {
  659. return
  660. }
  661. if !noDeps {
  662. ctx.Flash.Error(ctx.Tr("repo.issues.dependency.pr_close_blocked"))
  663. ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(pr.Index))
  664. return
  665. }
  666. if err = pull_service.Merge(pr, ctx.User, ctx.Repo.GitRepo, models.MergeStyle(form.Do), message); err != nil {
  667. if models.IsErrInvalidMergeStyle(err) {
  668. ctx.Flash.Error(ctx.Tr("repo.pulls.invalid_merge_option"))
  669. ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(pr.Index))
  670. return
  671. } else if models.IsErrMergeConflicts(err) {
  672. conflictError := err.(models.ErrMergeConflicts)
  673. ctx.Flash.Error(ctx.Tr("repo.pulls.merge_conflict", utils.SanitizeFlashErrorString(conflictError.StdErr), utils.SanitizeFlashErrorString(conflictError.StdOut)))
  674. ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(pr.Index))
  675. return
  676. } else if models.IsErrRebaseConflicts(err) {
  677. conflictError := err.(models.ErrRebaseConflicts)
  678. ctx.Flash.Error(ctx.Tr("repo.pulls.rebase_conflict", utils.SanitizeFlashErrorString(conflictError.CommitSHA), utils.SanitizeFlashErrorString(conflictError.StdErr), utils.SanitizeFlashErrorString(conflictError.StdOut)))
  679. ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(pr.Index))
  680. return
  681. } else if models.IsErrMergeUnrelatedHistories(err) {
  682. log.Debug("MergeUnrelatedHistories error: %v", err)
  683. ctx.Flash.Error(ctx.Tr("repo.pulls.unrelated_histories"))
  684. ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(pr.Index))
  685. return
  686. } else if models.IsErrMergePushOutOfDate(err) {
  687. log.Debug("MergePushOutOfDate error: %v", err)
  688. ctx.Flash.Error(ctx.Tr("repo.pulls.merge_out_of_date"))
  689. ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(pr.Index))
  690. return
  691. } else if models.IsErrPushRejected(err) {
  692. log.Debug("MergePushRejected error: %v", err)
  693. pushrejErr := err.(models.ErrPushRejected)
  694. message := pushrejErr.Message
  695. if len(message) == 0 {
  696. ctx.Flash.Error(ctx.Tr("repo.pulls.push_rejected_no_message"))
  697. } else {
  698. ctx.Flash.Error(ctx.Tr("repo.pulls.push_rejected", utils.SanitizeFlashErrorString(pushrejErr.Message)))
  699. }
  700. ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(pr.Index))
  701. return
  702. }
  703. ctx.ServerError("Merge", err)
  704. return
  705. }
  706. if err := stopTimerIfAvailable(ctx.User, issue); err != nil {
  707. ctx.ServerError("CreateOrStopIssueStopwatch", err)
  708. return
  709. }
  710. log.Trace("Pull request merged: %d", pr.ID)
  711. ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(pr.Index))
  712. }
  713. func stopTimerIfAvailable(user *models.User, issue *models.Issue) error {
  714. if models.StopwatchExists(user.ID, issue.ID) {
  715. if err := models.CreateOrStopIssueStopwatch(user, issue); err != nil {
  716. return err
  717. }
  718. }
  719. return nil
  720. }
  721. // CompareAndPullRequestPost response for creating pull request
  722. func CompareAndPullRequestPost(ctx *context.Context, form auth.CreateIssueForm) {
  723. ctx.Data["Title"] = ctx.Tr("repo.pulls.compare_changes")
  724. ctx.Data["PageIsComparePull"] = true
  725. ctx.Data["IsDiffCompare"] = true
  726. ctx.Data["RequireHighlightJS"] = true
  727. ctx.Data["PullRequestWorkInProgressPrefixes"] = setting.Repository.PullRequest.WorkInProgressPrefixes
  728. renderAttachmentSettings(ctx)
  729. var (
  730. repo = ctx.Repo.Repository
  731. attachments []string
  732. )
  733. headUser, headRepo, headGitRepo, prInfo, baseBranch, headBranch := ParseCompareInfo(ctx)
  734. if ctx.Written() {
  735. return
  736. }
  737. defer headGitRepo.Close()
  738. labelIDs, assigneeIDs, milestoneID := ValidateRepoMetas(ctx, form, true)
  739. if ctx.Written() {
  740. return
  741. }
  742. if setting.AttachmentEnabled {
  743. attachments = form.Files
  744. }
  745. if ctx.HasError() {
  746. auth.AssignForm(form, ctx.Data)
  747. // This stage is already stop creating new pull request, so it does not matter if it has
  748. // something to compare or not.
  749. PrepareCompareDiff(ctx, headUser, headRepo, headGitRepo, prInfo, baseBranch, headBranch)
  750. if ctx.Written() {
  751. return
  752. }
  753. ctx.HTML(200, tplCompareDiff)
  754. return
  755. }
  756. if util.IsEmptyString(form.Title) {
  757. PrepareCompareDiff(ctx, headUser, headRepo, headGitRepo, prInfo, baseBranch, headBranch)
  758. if ctx.Written() {
  759. return
  760. }
  761. ctx.RenderWithErr(ctx.Tr("repo.issues.new.title_empty"), tplCompareDiff, form)
  762. return
  763. }
  764. pullIssue := &models.Issue{
  765. RepoID: repo.ID,
  766. Title: form.Title,
  767. PosterID: ctx.User.ID,
  768. Poster: ctx.User,
  769. MilestoneID: milestoneID,
  770. IsPull: true,
  771. Content: form.Content,
  772. }
  773. pullRequest := &models.PullRequest{
  774. HeadRepoID: headRepo.ID,
  775. BaseRepoID: repo.ID,
  776. HeadBranch: headBranch,
  777. BaseBranch: baseBranch,
  778. HeadRepo: headRepo,
  779. BaseRepo: repo,
  780. MergeBase: prInfo.MergeBase,
  781. Type: models.PullRequestGitea,
  782. }
  783. // FIXME: check error in the case two people send pull request at almost same time, give nice error prompt
  784. // instead of 500.
  785. if err := pull_service.NewPullRequest(repo, pullIssue, labelIDs, attachments, pullRequest, assigneeIDs); err != nil {
  786. if models.IsErrUserDoesNotHaveAccessToRepo(err) {
  787. ctx.Error(400, "UserDoesNotHaveAccessToRepo", err.Error())
  788. return
  789. }
  790. ctx.ServerError("NewPullRequest", err)
  791. return
  792. }
  793. log.Trace("Pull request created: %d/%d", repo.ID, pullIssue.ID)
  794. ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(pullIssue.Index))
  795. }
  796. // TriggerTask response for a trigger task request
  797. func TriggerTask(ctx *context.Context) {
  798. pusherID := ctx.QueryInt64("pusher")
  799. branch := ctx.Query("branch")
  800. secret := ctx.Query("secret")
  801. if len(branch) == 0 || len(secret) == 0 || pusherID <= 0 {
  802. ctx.Error(404)
  803. log.Trace("TriggerTask: branch or secret is empty, or pusher ID is not valid")
  804. return
  805. }
  806. owner, repo := parseOwnerAndRepo(ctx)
  807. if ctx.Written() {
  808. return
  809. }
  810. got := []byte(base.EncodeMD5(owner.Salt))
  811. want := []byte(secret)
  812. if subtle.ConstantTimeCompare(got, want) != 1 {
  813. ctx.Error(404)
  814. log.Trace("TriggerTask [%s/%s]: invalid secret", owner.Name, repo.Name)
  815. return
  816. }
  817. pusher, err := models.GetUserByID(pusherID)
  818. if err != nil {
  819. if models.IsErrUserNotExist(err) {
  820. ctx.Error(404)
  821. } else {
  822. ctx.ServerError("GetUserByID", err)
  823. }
  824. return
  825. }
  826. log.Trace("TriggerTask '%s/%s' by %s", repo.Name, branch, pusher.Name)
  827. go pull_service.AddTestPullRequestTask(pusher, repo.ID, branch, true, "", "")
  828. ctx.Status(202)
  829. }
  830. // CleanUpPullRequest responses for delete merged branch when PR has been merged
  831. func CleanUpPullRequest(ctx *context.Context) {
  832. issue := checkPullInfo(ctx)
  833. if ctx.Written() {
  834. return
  835. }
  836. pr := issue.PullRequest
  837. // Don't cleanup unmerged and unclosed PRs
  838. if !pr.HasMerged && !issue.IsClosed {
  839. ctx.NotFound("CleanUpPullRequest", nil)
  840. return
  841. }
  842. if err := pr.GetHeadRepo(); err != nil {
  843. ctx.ServerError("GetHeadRepo", err)
  844. return
  845. } else if pr.HeadRepo == nil {
  846. // Forked repository has already been deleted
  847. ctx.NotFound("CleanUpPullRequest", nil)
  848. return
  849. } else if err = pr.GetBaseRepo(); err != nil {
  850. ctx.ServerError("GetBaseRepo", err)
  851. return
  852. } else if err = pr.HeadRepo.GetOwner(); err != nil {
  853. ctx.ServerError("HeadRepo.GetOwner", err)
  854. return
  855. }
  856. perm, err := models.GetUserRepoPermission(pr.HeadRepo, ctx.User)
  857. if err != nil {
  858. ctx.ServerError("GetUserRepoPermission", err)
  859. return
  860. }
  861. if !perm.CanWrite(models.UnitTypeCode) {
  862. ctx.NotFound("CleanUpPullRequest", nil)
  863. return
  864. }
  865. fullBranchName := pr.HeadRepo.Owner.Name + "/" + pr.HeadBranch
  866. gitRepo, err := git.OpenRepository(pr.HeadRepo.RepoPath())
  867. if err != nil {
  868. ctx.ServerError(fmt.Sprintf("OpenRepository[%s]", pr.HeadRepo.RepoPath()), err)
  869. return
  870. }
  871. defer gitRepo.Close()
  872. gitBaseRepo, err := git.OpenRepository(pr.BaseRepo.RepoPath())
  873. if err != nil {
  874. ctx.ServerError(fmt.Sprintf("OpenRepository[%s]", pr.BaseRepo.RepoPath()), err)
  875. return
  876. }
  877. defer gitBaseRepo.Close()
  878. defer func() {
  879. ctx.JSON(200, map[string]interface{}{
  880. "redirect": pr.BaseRepo.Link() + "/pulls/" + com.ToStr(issue.Index),
  881. })
  882. }()
  883. if pr.HeadBranch == pr.HeadRepo.DefaultBranch || !gitRepo.IsBranchExist(pr.HeadBranch) {
  884. ctx.Flash.Error(ctx.Tr("repo.branch.deletion_failed", fullBranchName))
  885. return
  886. }
  887. // Check if branch is not protected
  888. if protected, err := pr.HeadRepo.IsProtectedBranch(pr.HeadBranch, ctx.User); err != nil || protected {
  889. if err != nil {
  890. log.Error("HeadRepo.IsProtectedBranch: %v", err)
  891. }
  892. ctx.Flash.Error(ctx.Tr("repo.branch.deletion_failed", fullBranchName))
  893. return
  894. }
  895. // Check if branch has no new commits
  896. headCommitID, err := gitBaseRepo.GetRefCommitID(pr.GetGitRefName())
  897. if err != nil {
  898. log.Error("GetRefCommitID: %v", err)
  899. ctx.Flash.Error(ctx.Tr("repo.branch.deletion_failed", fullBranchName))
  900. return
  901. }
  902. branchCommitID, err := gitRepo.GetBranchCommitID(pr.HeadBranch)
  903. if err != nil {
  904. log.Error("GetBranchCommitID: %v", err)
  905. ctx.Flash.Error(ctx.Tr("repo.branch.deletion_failed", fullBranchName))
  906. return
  907. }
  908. if headCommitID != branchCommitID {
  909. ctx.Flash.Error(ctx.Tr("repo.branch.delete_branch_has_new_commits", fullBranchName))
  910. return
  911. }
  912. if err := gitRepo.DeleteBranch(pr.HeadBranch, git.DeleteBranchOptions{
  913. Force: true,
  914. }); err != nil {
  915. log.Error("DeleteBranch: %v", err)
  916. ctx.Flash.Error(ctx.Tr("repo.branch.deletion_failed", fullBranchName))
  917. return
  918. }
  919. if err := repofiles.PushUpdate(
  920. pr.HeadRepo,
  921. pr.HeadBranch,
  922. repofiles.PushUpdateOptions{
  923. RefFullName: git.BranchPrefix + pr.HeadBranch,
  924. OldCommitID: branchCommitID,
  925. NewCommitID: git.EmptySHA,
  926. PusherID: ctx.User.ID,
  927. PusherName: ctx.User.Name,
  928. RepoUserName: pr.HeadRepo.Owner.Name,
  929. RepoName: pr.HeadRepo.Name,
  930. }); err != nil {
  931. log.Error("Update: %v", err)
  932. }
  933. if err := models.AddDeletePRBranchComment(ctx.User, pr.BaseRepo, issue.ID, pr.HeadBranch); err != nil {
  934. // Do not fail here as branch has already been deleted
  935. log.Error("DeleteBranch: %v", err)
  936. }
  937. ctx.Flash.Success(ctx.Tr("repo.branch.deletion_success", fullBranchName))
  938. }
  939. // DownloadPullDiff render a pull's raw diff
  940. func DownloadPullDiff(ctx *context.Context) {
  941. DownloadPullDiffOrPatch(ctx, false)
  942. }
  943. // DownloadPullPatch render a pull's raw patch
  944. func DownloadPullPatch(ctx *context.Context) {
  945. DownloadPullDiffOrPatch(ctx, true)
  946. }
  947. // DownloadPullDiffOrPatch render a pull's raw diff or patch
  948. func DownloadPullDiffOrPatch(ctx *context.Context, patch bool) {
  949. issue, err := models.GetIssueByIndex(ctx.Repo.Repository.ID, ctx.ParamsInt64(":index"))
  950. if err != nil {
  951. if models.IsErrIssueNotExist(err) {
  952. ctx.NotFound("GetIssueByIndex", err)
  953. } else {
  954. ctx.ServerError("GetIssueByIndex", err)
  955. }
  956. return
  957. }
  958. // Return not found if it's not a pull request
  959. if !issue.IsPull {
  960. ctx.NotFound("DownloadPullDiff",
  961. fmt.Errorf("Issue is not a pull request"))
  962. return
  963. }
  964. if err = issue.LoadPullRequest(); err != nil {
  965. ctx.ServerError("LoadPullRequest", err)
  966. return
  967. }
  968. pr := issue.PullRequest
  969. if err := pull_service.DownloadDiffOrPatch(pr, ctx, patch); err != nil {
  970. ctx.ServerError("DownloadDiffOrPatch", err)
  971. return
  972. }
  973. }
  974. // UpdatePullRequestTarget change pull request's target branch
  975. func UpdatePullRequestTarget(ctx *context.Context) {
  976. issue := GetActionIssue(ctx)
  977. pr := issue.PullRequest
  978. if ctx.Written() {
  979. return
  980. }
  981. if !issue.IsPull {
  982. ctx.Error(http.StatusNotFound)
  983. return
  984. }
  985. if !ctx.IsSigned || (!issue.IsPoster(ctx.User.ID) && !ctx.Repo.CanWriteIssuesOrPulls(issue.IsPull)) {
  986. ctx.Error(http.StatusForbidden)
  987. return
  988. }
  989. targetBranch := ctx.QueryTrim("target_branch")
  990. if len(targetBranch) == 0 {
  991. ctx.Error(http.StatusNoContent)
  992. return
  993. }
  994. if err := pull_service.ChangeTargetBranch(pr, ctx.User, targetBranch); err != nil {
  995. if models.IsErrPullRequestAlreadyExists(err) {
  996. err := err.(models.ErrPullRequestAlreadyExists)
  997. RepoRelPath := ctx.Repo.Owner.Name + "/" + ctx.Repo.Repository.Name
  998. errorMessage := ctx.Tr("repo.pulls.has_pull_request", ctx.Repo.RepoLink, RepoRelPath, err.IssueID)
  999. ctx.Flash.Error(errorMessage)
  1000. ctx.JSON(http.StatusConflict, map[string]interface{}{
  1001. "error": err.Error(),
  1002. "user_error": errorMessage,
  1003. })
  1004. } else if models.IsErrIssueIsClosed(err) {
  1005. errorMessage := ctx.Tr("repo.pulls.is_closed")
  1006. ctx.Flash.Error(errorMessage)
  1007. ctx.JSON(http.StatusConflict, map[string]interface{}{
  1008. "error": err.Error(),
  1009. "user_error": errorMessage,
  1010. })
  1011. } else if models.IsErrPullRequestHasMerged(err) {
  1012. errorMessage := ctx.Tr("repo.pulls.has_merged")
  1013. ctx.Flash.Error(errorMessage)
  1014. ctx.JSON(http.StatusConflict, map[string]interface{}{
  1015. "error": err.Error(),
  1016. "user_error": errorMessage,
  1017. })
  1018. } else if models.IsErrBranchesEqual(err) {
  1019. errorMessage := ctx.Tr("repo.pulls.nothing_to_compare")
  1020. ctx.Flash.Error(errorMessage)
  1021. ctx.JSON(http.StatusBadRequest, map[string]interface{}{
  1022. "error": err.Error(),
  1023. "user_error": errorMessage,
  1024. })
  1025. } else {
  1026. ctx.ServerError("UpdatePullRequestTarget", err)
  1027. }
  1028. return
  1029. }
  1030. notification.NotifyPullRequestChangeTargetBranch(ctx.User, pr, targetBranch)
  1031. ctx.JSON(http.StatusOK, map[string]interface{}{
  1032. "base_branch": pr.BaseBranch,
  1033. })
  1034. }