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

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