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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208
  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.LoadHeadRepo(); err != nil {
  241. ctx.ServerError("LoadHeadRepo", 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"] = pull.BaseBranch
  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.LoadHeadRepo(); err != nil {
  290. ctx.ServerError("LoadHeadRepo", err)
  291. return nil
  292. }
  293. if err := pull.LoadBaseRepo(); err != nil {
  294. ctx.ServerError("LoadBaseRepo", 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. if pull.IsSameRepo() {
  376. ctx.Data["HeadTarget"] = pull.HeadBranch
  377. } else {
  378. if pull.HeadRepo == nil {
  379. ctx.Data["HeadTarget"] = "<deleted>:" + pull.HeadBranch
  380. } else {
  381. ctx.Data["HeadTarget"] = pull.HeadRepo.OwnerName + ":" + pull.HeadBranch
  382. }
  383. }
  384. }
  385. compareInfo, err := baseGitRepo.GetCompareInfo(pull.BaseRepo.RepoPath(),
  386. pull.BaseBranch, pull.GetGitRefName())
  387. if err != nil {
  388. if strings.Contains(err.Error(), "fatal: Not a valid object name") {
  389. ctx.Data["IsPullRequestBroken"] = true
  390. ctx.Data["BaseTarget"] = pull.BaseBranch
  391. ctx.Data["NumCommits"] = 0
  392. ctx.Data["NumFiles"] = 0
  393. return nil
  394. }
  395. ctx.ServerError("GetCompareInfo", err)
  396. return nil
  397. }
  398. if pull.IsWorkInProgress() {
  399. ctx.Data["IsPullWorkInProgress"] = true
  400. ctx.Data["WorkInProgressPrefix"] = pull.GetWorkInProgressPrefix()
  401. }
  402. if pull.IsFilesConflicted() {
  403. ctx.Data["IsPullFilesConflicted"] = true
  404. ctx.Data["ConflictedFiles"] = pull.ConflictedFiles
  405. }
  406. ctx.Data["NumCommits"] = compareInfo.Commits.Len()
  407. ctx.Data["NumFiles"] = compareInfo.NumFiles
  408. return compareInfo
  409. }
  410. // ViewPullCommits show commits for a pull request
  411. func ViewPullCommits(ctx *context.Context) {
  412. ctx.Data["PageIsPullList"] = true
  413. ctx.Data["PageIsPullCommits"] = true
  414. issue := checkPullInfo(ctx)
  415. if ctx.Written() {
  416. return
  417. }
  418. pull := issue.PullRequest
  419. var commits *list.List
  420. var prInfo *git.CompareInfo
  421. if pull.HasMerged {
  422. prInfo = PrepareMergedViewPullInfo(ctx, issue)
  423. } else {
  424. prInfo = PrepareViewPullInfo(ctx, issue)
  425. }
  426. if ctx.Written() {
  427. return
  428. } else if prInfo == nil {
  429. ctx.NotFound("ViewPullCommits", nil)
  430. return
  431. }
  432. ctx.Data["Username"] = ctx.Repo.Owner.Name
  433. ctx.Data["Reponame"] = ctx.Repo.Repository.Name
  434. commits = prInfo.Commits
  435. commits = models.ValidateCommitsWithEmails(commits)
  436. commits = models.ParseCommitsWithSignature(commits, ctx.Repo.Repository)
  437. commits = models.ParseCommitsWithStatus(commits, ctx.Repo.Repository)
  438. ctx.Data["Commits"] = commits
  439. ctx.Data["CommitCount"] = commits.Len()
  440. getBranchData(ctx, issue)
  441. ctx.HTML(200, tplPullCommits)
  442. }
  443. // ViewPullFiles render pull request changed files list page
  444. func ViewPullFiles(ctx *context.Context) {
  445. ctx.Data["PageIsPullList"] = true
  446. ctx.Data["PageIsPullFiles"] = true
  447. issue := checkPullInfo(ctx)
  448. if ctx.Written() {
  449. return
  450. }
  451. pull := issue.PullRequest
  452. whitespaceFlags := map[string]string{
  453. "ignore-all": "-w",
  454. "ignore-change": "-b",
  455. "ignore-eol": "--ignore-space-at-eol",
  456. "": ""}
  457. var (
  458. diffRepoPath string
  459. startCommitID string
  460. endCommitID string
  461. gitRepo *git.Repository
  462. )
  463. var headTarget string
  464. var prInfo *git.CompareInfo
  465. if pull.HasMerged {
  466. prInfo = PrepareMergedViewPullInfo(ctx, issue)
  467. } else {
  468. prInfo = PrepareViewPullInfo(ctx, issue)
  469. }
  470. if ctx.Written() {
  471. return
  472. } else if prInfo == nil {
  473. ctx.NotFound("ViewPullFiles", nil)
  474. return
  475. }
  476. diffRepoPath = ctx.Repo.GitRepo.Path
  477. gitRepo = ctx.Repo.GitRepo
  478. headCommitID, err := gitRepo.GetRefCommitID(pull.GetGitRefName())
  479. if err != nil {
  480. ctx.ServerError("GetRefCommitID", err)
  481. return
  482. }
  483. startCommitID = prInfo.MergeBase
  484. endCommitID = headCommitID
  485. headTarget = path.Join(ctx.Repo.Owner.Name, ctx.Repo.Repository.Name)
  486. ctx.Data["Username"] = ctx.Repo.Owner.Name
  487. ctx.Data["Reponame"] = ctx.Repo.Repository.Name
  488. ctx.Data["AfterCommitID"] = endCommitID
  489. diff, err := gitdiff.GetDiffRangeWithWhitespaceBehavior(diffRepoPath,
  490. startCommitID, endCommitID, setting.Git.MaxGitDiffLines,
  491. setting.Git.MaxGitDiffLineCharacters, setting.Git.MaxGitDiffFiles,
  492. whitespaceFlags[ctx.Data["WhitespaceBehavior"].(string)])
  493. if err != nil {
  494. ctx.ServerError("GetDiffRangeWithWhitespaceBehavior", err)
  495. return
  496. }
  497. if err = diff.LoadComments(issue, ctx.User); err != nil {
  498. ctx.ServerError("LoadComments", err)
  499. return
  500. }
  501. ctx.Data["Diff"] = diff
  502. ctx.Data["DiffNotAvailable"] = diff.NumFiles() == 0
  503. baseCommit, err := ctx.Repo.GitRepo.GetCommit(startCommitID)
  504. if err != nil {
  505. ctx.ServerError("GetCommit", err)
  506. return
  507. }
  508. commit, err := gitRepo.GetCommit(endCommitID)
  509. if err != nil {
  510. ctx.ServerError("GetCommit", err)
  511. return
  512. }
  513. setImageCompareContext(ctx, baseCommit, commit)
  514. setPathsCompareContext(ctx, baseCommit, commit, headTarget)
  515. ctx.Data["RequireHighlightJS"] = true
  516. ctx.Data["RequireSimpleMDE"] = true
  517. ctx.Data["RequireTribute"] = true
  518. if ctx.Data["Assignees"], err = ctx.Repo.Repository.GetAssignees(); err != nil {
  519. ctx.ServerError("GetAssignees", err)
  520. return
  521. }
  522. ctx.Data["CurrentReview"], err = models.GetCurrentReview(ctx.User, issue)
  523. if err != nil && !models.IsErrReviewNotExist(err) {
  524. ctx.ServerError("GetCurrentReview", err)
  525. return
  526. }
  527. getBranchData(ctx, issue)
  528. ctx.HTML(200, tplPullFiles)
  529. }
  530. // UpdatePullRequest merge master into PR
  531. func UpdatePullRequest(ctx *context.Context) {
  532. issue := checkPullInfo(ctx)
  533. if ctx.Written() {
  534. return
  535. }
  536. if issue.IsClosed {
  537. ctx.NotFound("MergePullRequest", nil)
  538. return
  539. }
  540. if issue.PullRequest.HasMerged {
  541. ctx.NotFound("MergePullRequest", nil)
  542. return
  543. }
  544. if err := issue.PullRequest.LoadBaseRepo(); err != nil {
  545. ctx.InternalServerError(err)
  546. return
  547. }
  548. if err := issue.PullRequest.LoadHeadRepo(); err != nil {
  549. ctx.InternalServerError(err)
  550. return
  551. }
  552. allowedUpdate, err := pull_service.IsUserAllowedToUpdate(issue.PullRequest, ctx.User)
  553. if err != nil {
  554. ctx.ServerError("IsUserAllowedToMerge", err)
  555. return
  556. }
  557. // ToDo: add check if maintainers are allowed to change branch ... (need migration & co)
  558. if !allowedUpdate {
  559. ctx.Flash.Error(ctx.Tr("repo.pulls.update_not_allowed"))
  560. ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(issue.Index))
  561. return
  562. }
  563. // default merge commit message
  564. message := fmt.Sprintf("Merge branch '%s' into %s", issue.PullRequest.BaseBranch, issue.PullRequest.HeadBranch)
  565. if err = pull_service.Update(issue.PullRequest, ctx.User, message); err != nil {
  566. sanitize := func(x string) string {
  567. runes := []rune(x)
  568. if len(runes) > 512 {
  569. x = "..." + string(runes[len(runes)-512:])
  570. }
  571. return strings.Replace(html.EscapeString(x), "\n", "<br>", -1)
  572. }
  573. if models.IsErrMergeConflicts(err) {
  574. conflictError := err.(models.ErrMergeConflicts)
  575. ctx.Flash.Error(ctx.Tr("repo.pulls.merge_conflict", sanitize(conflictError.StdErr), sanitize(conflictError.StdOut)))
  576. ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(issue.Index))
  577. return
  578. }
  579. ctx.Flash.Error(err.Error())
  580. ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(issue.Index))
  581. }
  582. time.Sleep(1 * time.Second)
  583. ctx.Flash.Success(ctx.Tr("repo.pulls.update_branch_success"))
  584. ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(issue.Index))
  585. }
  586. // MergePullRequest response for merging pull request
  587. func MergePullRequest(ctx *context.Context, form auth.MergePullRequestForm) {
  588. issue := checkPullInfo(ctx)
  589. if ctx.Written() {
  590. return
  591. }
  592. if issue.IsClosed {
  593. if issue.IsPull {
  594. ctx.Flash.Error(ctx.Tr("repo.pulls.is_closed"))
  595. ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(issue.Index))
  596. return
  597. }
  598. ctx.Flash.Error(ctx.Tr("repo.issues.closed_title"))
  599. ctx.Redirect(ctx.Repo.RepoLink + "/issues/" + com.ToStr(issue.Index))
  600. return
  601. }
  602. pr := issue.PullRequest
  603. allowedMerge, err := pull_service.IsUserAllowedToMerge(pr, ctx.Repo.Permission, ctx.User)
  604. if err != nil {
  605. ctx.ServerError("IsUserAllowedToMerge", err)
  606. return
  607. }
  608. if !allowedMerge {
  609. ctx.Flash.Error(ctx.Tr("repo.pulls.update_not_allowed"))
  610. ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(issue.Index))
  611. return
  612. }
  613. if !pr.CanAutoMerge() {
  614. ctx.Flash.Error(ctx.Tr("repo.pulls.no_merge_not_ready"))
  615. ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(issue.Index))
  616. return
  617. }
  618. if pr.HasMerged {
  619. ctx.Flash.Error(ctx.Tr("repo.pulls.has_merged"))
  620. ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(issue.Index))
  621. return
  622. }
  623. if pr.IsWorkInProgress() {
  624. ctx.Flash.Error(ctx.Tr("repo.pulls.no_merge_wip"))
  625. ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(pr.Index))
  626. return
  627. }
  628. if err := pull_service.CheckPRReadyToMerge(pr); err != nil {
  629. if !models.IsErrNotAllowedToMerge(err) {
  630. ctx.ServerError("Merge PR status", err)
  631. return
  632. }
  633. if isRepoAdmin, err := models.IsUserRepoAdmin(pr.BaseRepo, ctx.User); err != nil {
  634. ctx.ServerError("IsUserRepoAdmin", err)
  635. return
  636. } else if !isRepoAdmin {
  637. ctx.Flash.Error(ctx.Tr("repo.pulls.no_merge_not_ready"))
  638. ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(pr.Index))
  639. return
  640. }
  641. }
  642. if ctx.HasError() {
  643. ctx.Flash.Error(ctx.Data["ErrorMsg"].(string))
  644. ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(pr.Index))
  645. return
  646. }
  647. message := strings.TrimSpace(form.MergeTitleField)
  648. if len(message) == 0 {
  649. if models.MergeStyle(form.Do) == models.MergeStyleMerge {
  650. message = pr.GetDefaultMergeMessage()
  651. }
  652. if models.MergeStyle(form.Do) == models.MergeStyleRebaseMerge {
  653. message = pr.GetDefaultMergeMessage()
  654. }
  655. if models.MergeStyle(form.Do) == models.MergeStyleSquash {
  656. message = pr.GetDefaultSquashMessage()
  657. }
  658. }
  659. form.MergeMessageField = strings.TrimSpace(form.MergeMessageField)
  660. if len(form.MergeMessageField) > 0 {
  661. message += "\n\n" + form.MergeMessageField
  662. }
  663. pr.Issue = issue
  664. pr.Issue.Repo = ctx.Repo.Repository
  665. noDeps, err := models.IssueNoDependenciesLeft(issue)
  666. if err != nil {
  667. return
  668. }
  669. if !noDeps {
  670. ctx.Flash.Error(ctx.Tr("repo.issues.dependency.pr_close_blocked"))
  671. ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(pr.Index))
  672. return
  673. }
  674. if err = pull_service.Merge(pr, ctx.User, ctx.Repo.GitRepo, models.MergeStyle(form.Do), message); err != nil {
  675. if models.IsErrInvalidMergeStyle(err) {
  676. ctx.Flash.Error(ctx.Tr("repo.pulls.invalid_merge_option"))
  677. ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(pr.Index))
  678. return
  679. } else if models.IsErrMergeConflicts(err) {
  680. conflictError := err.(models.ErrMergeConflicts)
  681. ctx.Flash.Error(ctx.Tr("repo.pulls.merge_conflict", utils.SanitizeFlashErrorString(conflictError.StdErr), utils.SanitizeFlashErrorString(conflictError.StdOut)))
  682. ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(pr.Index))
  683. return
  684. } else if models.IsErrRebaseConflicts(err) {
  685. conflictError := err.(models.ErrRebaseConflicts)
  686. ctx.Flash.Error(ctx.Tr("repo.pulls.rebase_conflict", utils.SanitizeFlashErrorString(conflictError.CommitSHA), utils.SanitizeFlashErrorString(conflictError.StdErr), utils.SanitizeFlashErrorString(conflictError.StdOut)))
  687. ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(pr.Index))
  688. return
  689. } else if models.IsErrMergeUnrelatedHistories(err) {
  690. log.Debug("MergeUnrelatedHistories error: %v", err)
  691. ctx.Flash.Error(ctx.Tr("repo.pulls.unrelated_histories"))
  692. ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(pr.Index))
  693. return
  694. } else if models.IsErrMergePushOutOfDate(err) {
  695. log.Debug("MergePushOutOfDate error: %v", err)
  696. ctx.Flash.Error(ctx.Tr("repo.pulls.merge_out_of_date"))
  697. ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(pr.Index))
  698. return
  699. } else if models.IsErrPushRejected(err) {
  700. log.Debug("MergePushRejected error: %v", err)
  701. pushrejErr := err.(models.ErrPushRejected)
  702. message := pushrejErr.Message
  703. if len(message) == 0 {
  704. ctx.Flash.Error(ctx.Tr("repo.pulls.push_rejected_no_message"))
  705. } else {
  706. ctx.Flash.Error(ctx.Tr("repo.pulls.push_rejected", utils.SanitizeFlashErrorString(pushrejErr.Message)))
  707. }
  708. ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(pr.Index))
  709. return
  710. }
  711. ctx.ServerError("Merge", err)
  712. return
  713. }
  714. if err := stopTimerIfAvailable(ctx.User, issue); err != nil {
  715. ctx.ServerError("CreateOrStopIssueStopwatch", err)
  716. return
  717. }
  718. log.Trace("Pull request merged: %d", pr.ID)
  719. ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(pr.Index))
  720. }
  721. func stopTimerIfAvailable(user *models.User, issue *models.Issue) error {
  722. if models.StopwatchExists(user.ID, issue.ID) {
  723. if err := models.CreateOrStopIssueStopwatch(user, issue); err != nil {
  724. return err
  725. }
  726. }
  727. return nil
  728. }
  729. // CompareAndPullRequestPost response for creating pull request
  730. func CompareAndPullRequestPost(ctx *context.Context, form auth.CreateIssueForm) {
  731. ctx.Data["Title"] = ctx.Tr("repo.pulls.compare_changes")
  732. ctx.Data["PageIsComparePull"] = true
  733. ctx.Data["IsDiffCompare"] = true
  734. ctx.Data["RequireHighlightJS"] = true
  735. ctx.Data["PullRequestWorkInProgressPrefixes"] = setting.Repository.PullRequest.WorkInProgressPrefixes
  736. renderAttachmentSettings(ctx)
  737. var (
  738. repo = ctx.Repo.Repository
  739. attachments []string
  740. )
  741. headUser, headRepo, headGitRepo, prInfo, baseBranch, headBranch := ParseCompareInfo(ctx)
  742. if ctx.Written() {
  743. return
  744. }
  745. defer headGitRepo.Close()
  746. labelIDs, assigneeIDs, milestoneID := ValidateRepoMetas(ctx, form, true)
  747. if ctx.Written() {
  748. return
  749. }
  750. if setting.AttachmentEnabled {
  751. attachments = form.Files
  752. }
  753. if ctx.HasError() {
  754. auth.AssignForm(form, ctx.Data)
  755. // This stage is already stop creating new pull request, so it does not matter if it has
  756. // something to compare or not.
  757. PrepareCompareDiff(ctx, headUser, headRepo, headGitRepo, prInfo, baseBranch, headBranch)
  758. if ctx.Written() {
  759. return
  760. }
  761. ctx.HTML(200, tplCompareDiff)
  762. return
  763. }
  764. if util.IsEmptyString(form.Title) {
  765. PrepareCompareDiff(ctx, headUser, headRepo, headGitRepo, prInfo, baseBranch, headBranch)
  766. if ctx.Written() {
  767. return
  768. }
  769. ctx.RenderWithErr(ctx.Tr("repo.issues.new.title_empty"), tplCompareDiff, form)
  770. return
  771. }
  772. pullIssue := &models.Issue{
  773. RepoID: repo.ID,
  774. Title: form.Title,
  775. PosterID: ctx.User.ID,
  776. Poster: ctx.User,
  777. MilestoneID: milestoneID,
  778. IsPull: true,
  779. Content: form.Content,
  780. }
  781. pullRequest := &models.PullRequest{
  782. HeadRepoID: headRepo.ID,
  783. BaseRepoID: repo.ID,
  784. HeadBranch: headBranch,
  785. BaseBranch: baseBranch,
  786. HeadRepo: headRepo,
  787. BaseRepo: repo,
  788. MergeBase: prInfo.MergeBase,
  789. Type: models.PullRequestGitea,
  790. }
  791. // FIXME: check error in the case two people send pull request at almost same time, give nice error prompt
  792. // instead of 500.
  793. if err := pull_service.NewPullRequest(repo, pullIssue, labelIDs, attachments, pullRequest, assigneeIDs); err != nil {
  794. if models.IsErrUserDoesNotHaveAccessToRepo(err) {
  795. ctx.Error(400, "UserDoesNotHaveAccessToRepo", err.Error())
  796. return
  797. }
  798. ctx.ServerError("NewPullRequest", err)
  799. return
  800. }
  801. log.Trace("Pull request created: %d/%d", repo.ID, pullIssue.ID)
  802. ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(pullIssue.Index))
  803. }
  804. // TriggerTask response for a trigger task request
  805. func TriggerTask(ctx *context.Context) {
  806. pusherID := ctx.QueryInt64("pusher")
  807. branch := ctx.Query("branch")
  808. secret := ctx.Query("secret")
  809. if len(branch) == 0 || len(secret) == 0 || pusherID <= 0 {
  810. ctx.Error(404)
  811. log.Trace("TriggerTask: branch or secret is empty, or pusher ID is not valid")
  812. return
  813. }
  814. owner, repo := parseOwnerAndRepo(ctx)
  815. if ctx.Written() {
  816. return
  817. }
  818. got := []byte(base.EncodeMD5(owner.Salt))
  819. want := []byte(secret)
  820. if subtle.ConstantTimeCompare(got, want) != 1 {
  821. ctx.Error(404)
  822. log.Trace("TriggerTask [%s/%s]: invalid secret", owner.Name, repo.Name)
  823. return
  824. }
  825. pusher, err := models.GetUserByID(pusherID)
  826. if err != nil {
  827. if models.IsErrUserNotExist(err) {
  828. ctx.Error(404)
  829. } else {
  830. ctx.ServerError("GetUserByID", err)
  831. }
  832. return
  833. }
  834. log.Trace("TriggerTask '%s/%s' by %s", repo.Name, branch, pusher.Name)
  835. go pull_service.AddTestPullRequestTask(pusher, repo.ID, branch, true, "", "")
  836. ctx.Status(202)
  837. }
  838. // CleanUpPullRequest responses for delete merged branch when PR has been merged
  839. func CleanUpPullRequest(ctx *context.Context) {
  840. issue := checkPullInfo(ctx)
  841. if ctx.Written() {
  842. return
  843. }
  844. pr := issue.PullRequest
  845. // Don't cleanup unmerged and unclosed PRs
  846. if !pr.HasMerged && !issue.IsClosed {
  847. ctx.NotFound("CleanUpPullRequest", nil)
  848. return
  849. }
  850. if err := pr.LoadHeadRepo(); err != nil {
  851. ctx.ServerError("LoadHeadRepo", err)
  852. return
  853. } else if pr.HeadRepo == nil {
  854. // Forked repository has already been deleted
  855. ctx.NotFound("CleanUpPullRequest", nil)
  856. return
  857. } else if err = pr.LoadBaseRepo(); err != nil {
  858. ctx.ServerError("LoadBaseRepo", err)
  859. return
  860. } else if err = pr.HeadRepo.GetOwner(); err != nil {
  861. ctx.ServerError("HeadRepo.GetOwner", err)
  862. return
  863. }
  864. perm, err := models.GetUserRepoPermission(pr.HeadRepo, ctx.User)
  865. if err != nil {
  866. ctx.ServerError("GetUserRepoPermission", err)
  867. return
  868. }
  869. if !perm.CanWrite(models.UnitTypeCode) {
  870. ctx.NotFound("CleanUpPullRequest", nil)
  871. return
  872. }
  873. fullBranchName := pr.HeadRepo.Owner.Name + "/" + pr.HeadBranch
  874. gitRepo, err := git.OpenRepository(pr.HeadRepo.RepoPath())
  875. if err != nil {
  876. ctx.ServerError(fmt.Sprintf("OpenRepository[%s]", pr.HeadRepo.RepoPath()), err)
  877. return
  878. }
  879. defer gitRepo.Close()
  880. gitBaseRepo, err := git.OpenRepository(pr.BaseRepo.RepoPath())
  881. if err != nil {
  882. ctx.ServerError(fmt.Sprintf("OpenRepository[%s]", pr.BaseRepo.RepoPath()), err)
  883. return
  884. }
  885. defer gitBaseRepo.Close()
  886. defer func() {
  887. ctx.JSON(200, map[string]interface{}{
  888. "redirect": pr.BaseRepo.Link() + "/pulls/" + com.ToStr(issue.Index),
  889. })
  890. }()
  891. if pr.HeadBranch == pr.HeadRepo.DefaultBranch || !gitRepo.IsBranchExist(pr.HeadBranch) {
  892. ctx.Flash.Error(ctx.Tr("repo.branch.deletion_failed", fullBranchName))
  893. return
  894. }
  895. // Check if branch is not protected
  896. if protected, err := pr.HeadRepo.IsProtectedBranch(pr.HeadBranch, ctx.User); err != nil || protected {
  897. if err != nil {
  898. log.Error("HeadRepo.IsProtectedBranch: %v", err)
  899. }
  900. ctx.Flash.Error(ctx.Tr("repo.branch.deletion_failed", fullBranchName))
  901. return
  902. }
  903. // Check if branch has no new commits
  904. headCommitID, err := gitBaseRepo.GetRefCommitID(pr.GetGitRefName())
  905. if err != nil {
  906. log.Error("GetRefCommitID: %v", err)
  907. ctx.Flash.Error(ctx.Tr("repo.branch.deletion_failed", fullBranchName))
  908. return
  909. }
  910. branchCommitID, err := gitRepo.GetBranchCommitID(pr.HeadBranch)
  911. if err != nil {
  912. log.Error("GetBranchCommitID: %v", err)
  913. ctx.Flash.Error(ctx.Tr("repo.branch.deletion_failed", fullBranchName))
  914. return
  915. }
  916. if headCommitID != branchCommitID {
  917. ctx.Flash.Error(ctx.Tr("repo.branch.delete_branch_has_new_commits", fullBranchName))
  918. return
  919. }
  920. if err := gitRepo.DeleteBranch(pr.HeadBranch, git.DeleteBranchOptions{
  921. Force: true,
  922. }); err != nil {
  923. log.Error("DeleteBranch: %v", err)
  924. ctx.Flash.Error(ctx.Tr("repo.branch.deletion_failed", fullBranchName))
  925. return
  926. }
  927. if err := repofiles.PushUpdate(
  928. pr.HeadRepo,
  929. pr.HeadBranch,
  930. repofiles.PushUpdateOptions{
  931. RefFullName: git.BranchPrefix + pr.HeadBranch,
  932. OldCommitID: branchCommitID,
  933. NewCommitID: git.EmptySHA,
  934. PusherID: ctx.User.ID,
  935. PusherName: ctx.User.Name,
  936. RepoUserName: pr.HeadRepo.Owner.Name,
  937. RepoName: pr.HeadRepo.Name,
  938. }); err != nil {
  939. log.Error("Update: %v", err)
  940. }
  941. if err := models.AddDeletePRBranchComment(ctx.User, pr.BaseRepo, issue.ID, pr.HeadBranch); err != nil {
  942. // Do not fail here as branch has already been deleted
  943. log.Error("DeleteBranch: %v", err)
  944. }
  945. ctx.Flash.Success(ctx.Tr("repo.branch.deletion_success", fullBranchName))
  946. }
  947. // DownloadPullDiff render a pull's raw diff
  948. func DownloadPullDiff(ctx *context.Context) {
  949. DownloadPullDiffOrPatch(ctx, false)
  950. }
  951. // DownloadPullPatch render a pull's raw patch
  952. func DownloadPullPatch(ctx *context.Context) {
  953. DownloadPullDiffOrPatch(ctx, true)
  954. }
  955. // DownloadPullDiffOrPatch render a pull's raw diff or patch
  956. func DownloadPullDiffOrPatch(ctx *context.Context, patch bool) {
  957. issue, err := models.GetIssueByIndex(ctx.Repo.Repository.ID, ctx.ParamsInt64(":index"))
  958. if err != nil {
  959. if models.IsErrIssueNotExist(err) {
  960. ctx.NotFound("GetIssueByIndex", err)
  961. } else {
  962. ctx.ServerError("GetIssueByIndex", err)
  963. }
  964. return
  965. }
  966. // Return not found if it's not a pull request
  967. if !issue.IsPull {
  968. ctx.NotFound("DownloadPullDiff",
  969. fmt.Errorf("Issue is not a pull request"))
  970. return
  971. }
  972. if err = issue.LoadPullRequest(); err != nil {
  973. ctx.ServerError("LoadPullRequest", err)
  974. return
  975. }
  976. pr := issue.PullRequest
  977. if err := pull_service.DownloadDiffOrPatch(pr, ctx, patch); err != nil {
  978. ctx.ServerError("DownloadDiffOrPatch", err)
  979. return
  980. }
  981. }
  982. // UpdatePullRequestTarget change pull request's target branch
  983. func UpdatePullRequestTarget(ctx *context.Context) {
  984. issue := GetActionIssue(ctx)
  985. pr := issue.PullRequest
  986. if ctx.Written() {
  987. return
  988. }
  989. if !issue.IsPull {
  990. ctx.Error(http.StatusNotFound)
  991. return
  992. }
  993. if !ctx.IsSigned || (!issue.IsPoster(ctx.User.ID) && !ctx.Repo.CanWriteIssuesOrPulls(issue.IsPull)) {
  994. ctx.Error(http.StatusForbidden)
  995. return
  996. }
  997. targetBranch := ctx.QueryTrim("target_branch")
  998. if len(targetBranch) == 0 {
  999. ctx.Error(http.StatusNoContent)
  1000. return
  1001. }
  1002. if err := pull_service.ChangeTargetBranch(pr, ctx.User, targetBranch); err != nil {
  1003. if models.IsErrPullRequestAlreadyExists(err) {
  1004. err := err.(models.ErrPullRequestAlreadyExists)
  1005. RepoRelPath := ctx.Repo.Owner.Name + "/" + ctx.Repo.Repository.Name
  1006. errorMessage := ctx.Tr("repo.pulls.has_pull_request", ctx.Repo.RepoLink, RepoRelPath, err.IssueID)
  1007. ctx.Flash.Error(errorMessage)
  1008. ctx.JSON(http.StatusConflict, map[string]interface{}{
  1009. "error": err.Error(),
  1010. "user_error": errorMessage,
  1011. })
  1012. } else if models.IsErrIssueIsClosed(err) {
  1013. errorMessage := ctx.Tr("repo.pulls.is_closed")
  1014. ctx.Flash.Error(errorMessage)
  1015. ctx.JSON(http.StatusConflict, map[string]interface{}{
  1016. "error": err.Error(),
  1017. "user_error": errorMessage,
  1018. })
  1019. } else if models.IsErrPullRequestHasMerged(err) {
  1020. errorMessage := ctx.Tr("repo.pulls.has_merged")
  1021. ctx.Flash.Error(errorMessage)
  1022. ctx.JSON(http.StatusConflict, map[string]interface{}{
  1023. "error": err.Error(),
  1024. "user_error": errorMessage,
  1025. })
  1026. } else if models.IsErrBranchesEqual(err) {
  1027. errorMessage := ctx.Tr("repo.pulls.nothing_to_compare")
  1028. ctx.Flash.Error(errorMessage)
  1029. ctx.JSON(http.StatusBadRequest, map[string]interface{}{
  1030. "error": err.Error(),
  1031. "user_error": errorMessage,
  1032. })
  1033. } else {
  1034. ctx.ServerError("UpdatePullRequestTarget", err)
  1035. }
  1036. return
  1037. }
  1038. notification.NotifyPullRequestChangeTargetBranch(ctx.User, pr, targetBranch)
  1039. ctx.JSON(http.StatusOK, map[string]interface{}{
  1040. "base_branch": pr.BaseBranch,
  1041. })
  1042. }