Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

pull.go 33KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218
  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.HTML(200, tplPullFiles)
  537. }
  538. // UpdatePullRequest merge master into PR
  539. func UpdatePullRequest(ctx *context.Context) {
  540. issue := checkPullInfo(ctx)
  541. if ctx.Written() {
  542. return
  543. }
  544. if issue.IsClosed {
  545. ctx.NotFound("MergePullRequest", nil)
  546. return
  547. }
  548. if issue.PullRequest.HasMerged {
  549. ctx.NotFound("MergePullRequest", nil)
  550. return
  551. }
  552. if err := issue.PullRequest.LoadBaseRepo(); err != nil {
  553. ctx.InternalServerError(err)
  554. return
  555. }
  556. if err := issue.PullRequest.LoadHeadRepo(); err != nil {
  557. ctx.InternalServerError(err)
  558. return
  559. }
  560. allowedUpdate, err := pull_service.IsUserAllowedToUpdate(issue.PullRequest, ctx.User)
  561. if err != nil {
  562. ctx.ServerError("IsUserAllowedToMerge", err)
  563. return
  564. }
  565. // ToDo: add check if maintainers are allowed to change branch ... (need migration & co)
  566. if !allowedUpdate {
  567. ctx.Flash.Error(ctx.Tr("repo.pulls.update_not_allowed"))
  568. ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(issue.Index))
  569. return
  570. }
  571. // default merge commit message
  572. message := fmt.Sprintf("Merge branch '%s' into %s", issue.PullRequest.BaseBranch, issue.PullRequest.HeadBranch)
  573. if err = pull_service.Update(issue.PullRequest, ctx.User, message); err != nil {
  574. sanitize := func(x string) string {
  575. runes := []rune(x)
  576. if len(runes) > 512 {
  577. x = "..." + string(runes[len(runes)-512:])
  578. }
  579. return strings.Replace(html.EscapeString(x), "\n", "<br>", -1)
  580. }
  581. if models.IsErrMergeConflicts(err) {
  582. conflictError := err.(models.ErrMergeConflicts)
  583. ctx.Flash.Error(ctx.Tr("repo.pulls.merge_conflict", sanitize(conflictError.StdErr), sanitize(conflictError.StdOut)))
  584. ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(issue.Index))
  585. return
  586. }
  587. ctx.Flash.Error(err.Error())
  588. ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(issue.Index))
  589. }
  590. time.Sleep(1 * time.Second)
  591. ctx.Flash.Success(ctx.Tr("repo.pulls.update_branch_success"))
  592. ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(issue.Index))
  593. }
  594. // MergePullRequest response for merging pull request
  595. func MergePullRequest(ctx *context.Context, form auth.MergePullRequestForm) {
  596. issue := checkPullInfo(ctx)
  597. if ctx.Written() {
  598. return
  599. }
  600. if issue.IsClosed {
  601. if issue.IsPull {
  602. ctx.Flash.Error(ctx.Tr("repo.pulls.is_closed"))
  603. ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(issue.Index))
  604. return
  605. }
  606. ctx.Flash.Error(ctx.Tr("repo.issues.closed_title"))
  607. ctx.Redirect(ctx.Repo.RepoLink + "/issues/" + com.ToStr(issue.Index))
  608. return
  609. }
  610. pr := issue.PullRequest
  611. allowedMerge, err := pull_service.IsUserAllowedToMerge(pr, ctx.Repo.Permission, ctx.User)
  612. if err != nil {
  613. ctx.ServerError("IsUserAllowedToMerge", err)
  614. return
  615. }
  616. if !allowedMerge {
  617. ctx.Flash.Error(ctx.Tr("repo.pulls.update_not_allowed"))
  618. ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(issue.Index))
  619. return
  620. }
  621. if !pr.CanAutoMerge() {
  622. ctx.Flash.Error(ctx.Tr("repo.pulls.no_merge_not_ready"))
  623. ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(issue.Index))
  624. return
  625. }
  626. if pr.HasMerged {
  627. ctx.Flash.Error(ctx.Tr("repo.pulls.has_merged"))
  628. ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(issue.Index))
  629. return
  630. }
  631. if pr.IsWorkInProgress() {
  632. ctx.Flash.Error(ctx.Tr("repo.pulls.no_merge_wip"))
  633. ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(pr.Index))
  634. return
  635. }
  636. if err := pull_service.CheckPRReadyToMerge(pr); err != nil {
  637. if !models.IsErrNotAllowedToMerge(err) {
  638. ctx.ServerError("Merge PR status", err)
  639. return
  640. }
  641. if isRepoAdmin, err := models.IsUserRepoAdmin(pr.BaseRepo, ctx.User); err != nil {
  642. ctx.ServerError("IsUserRepoAdmin", err)
  643. return
  644. } else if !isRepoAdmin {
  645. ctx.Flash.Error(ctx.Tr("repo.pulls.no_merge_not_ready"))
  646. ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(pr.Index))
  647. return
  648. }
  649. }
  650. if ctx.HasError() {
  651. ctx.Flash.Error(ctx.Data["ErrorMsg"].(string))
  652. ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(pr.Index))
  653. return
  654. }
  655. message := strings.TrimSpace(form.MergeTitleField)
  656. if len(message) == 0 {
  657. if models.MergeStyle(form.Do) == models.MergeStyleMerge {
  658. message = pr.GetDefaultMergeMessage()
  659. }
  660. if models.MergeStyle(form.Do) == models.MergeStyleRebaseMerge {
  661. message = pr.GetDefaultMergeMessage()
  662. }
  663. if models.MergeStyle(form.Do) == models.MergeStyleSquash {
  664. message = pr.GetDefaultSquashMessage()
  665. }
  666. }
  667. form.MergeMessageField = strings.TrimSpace(form.MergeMessageField)
  668. if len(form.MergeMessageField) > 0 {
  669. message += "\n\n" + form.MergeMessageField
  670. }
  671. pr.Issue = issue
  672. pr.Issue.Repo = ctx.Repo.Repository
  673. noDeps, err := models.IssueNoDependenciesLeft(issue)
  674. if err != nil {
  675. return
  676. }
  677. if !noDeps {
  678. ctx.Flash.Error(ctx.Tr("repo.issues.dependency.pr_close_blocked"))
  679. ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(pr.Index))
  680. return
  681. }
  682. if err = pull_service.Merge(pr, ctx.User, ctx.Repo.GitRepo, models.MergeStyle(form.Do), message); err != nil {
  683. if models.IsErrInvalidMergeStyle(err) {
  684. ctx.Flash.Error(ctx.Tr("repo.pulls.invalid_merge_option"))
  685. ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(pr.Index))
  686. return
  687. } else if models.IsErrMergeConflicts(err) {
  688. conflictError := err.(models.ErrMergeConflicts)
  689. ctx.Flash.Error(ctx.Tr("repo.pulls.merge_conflict", utils.SanitizeFlashErrorString(conflictError.StdErr), utils.SanitizeFlashErrorString(conflictError.StdOut)))
  690. ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(pr.Index))
  691. return
  692. } else if models.IsErrRebaseConflicts(err) {
  693. conflictError := err.(models.ErrRebaseConflicts)
  694. ctx.Flash.Error(ctx.Tr("repo.pulls.rebase_conflict", utils.SanitizeFlashErrorString(conflictError.CommitSHA), utils.SanitizeFlashErrorString(conflictError.StdErr), utils.SanitizeFlashErrorString(conflictError.StdOut)))
  695. ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(pr.Index))
  696. return
  697. } else if models.IsErrMergeUnrelatedHistories(err) {
  698. log.Debug("MergeUnrelatedHistories error: %v", err)
  699. ctx.Flash.Error(ctx.Tr("repo.pulls.unrelated_histories"))
  700. ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(pr.Index))
  701. return
  702. } else if models.IsErrMergePushOutOfDate(err) {
  703. log.Debug("MergePushOutOfDate error: %v", err)
  704. ctx.Flash.Error(ctx.Tr("repo.pulls.merge_out_of_date"))
  705. ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(pr.Index))
  706. return
  707. } else if models.IsErrPushRejected(err) {
  708. log.Debug("MergePushRejected error: %v", err)
  709. pushrejErr := err.(models.ErrPushRejected)
  710. message := pushrejErr.Message
  711. if len(message) == 0 {
  712. ctx.Flash.Error(ctx.Tr("repo.pulls.push_rejected_no_message"))
  713. } else {
  714. ctx.Flash.Error(ctx.Tr("repo.pulls.push_rejected", utils.SanitizeFlashErrorString(pushrejErr.Message)))
  715. }
  716. ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(pr.Index))
  717. return
  718. }
  719. ctx.ServerError("Merge", err)
  720. return
  721. }
  722. if err := stopTimerIfAvailable(ctx.User, issue); err != nil {
  723. ctx.ServerError("CreateOrStopIssueStopwatch", err)
  724. return
  725. }
  726. log.Trace("Pull request merged: %d", pr.ID)
  727. ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(pr.Index))
  728. }
  729. func stopTimerIfAvailable(user *models.User, issue *models.Issue) error {
  730. if models.StopwatchExists(user.ID, issue.ID) {
  731. if err := models.CreateOrStopIssueStopwatch(user, issue); err != nil {
  732. return err
  733. }
  734. }
  735. return nil
  736. }
  737. // CompareAndPullRequestPost response for creating pull request
  738. func CompareAndPullRequestPost(ctx *context.Context, form auth.CreateIssueForm) {
  739. ctx.Data["Title"] = ctx.Tr("repo.pulls.compare_changes")
  740. ctx.Data["PageIsComparePull"] = true
  741. ctx.Data["IsDiffCompare"] = true
  742. ctx.Data["RequireHighlightJS"] = true
  743. ctx.Data["PullRequestWorkInProgressPrefixes"] = setting.Repository.PullRequest.WorkInProgressPrefixes
  744. renderAttachmentSettings(ctx)
  745. var (
  746. repo = ctx.Repo.Repository
  747. attachments []string
  748. )
  749. headUser, headRepo, headGitRepo, prInfo, baseBranch, headBranch := ParseCompareInfo(ctx)
  750. if ctx.Written() {
  751. return
  752. }
  753. defer headGitRepo.Close()
  754. labelIDs, assigneeIDs, milestoneID := ValidateRepoMetas(ctx, form, true)
  755. if ctx.Written() {
  756. return
  757. }
  758. if setting.AttachmentEnabled {
  759. attachments = form.Files
  760. }
  761. if ctx.HasError() {
  762. auth.AssignForm(form, ctx.Data)
  763. // This stage is already stop creating new pull request, so it does not matter if it has
  764. // something to compare or not.
  765. PrepareCompareDiff(ctx, headUser, headRepo, headGitRepo, prInfo, baseBranch, headBranch)
  766. if ctx.Written() {
  767. return
  768. }
  769. ctx.HTML(200, tplCompareDiff)
  770. return
  771. }
  772. if util.IsEmptyString(form.Title) {
  773. PrepareCompareDiff(ctx, headUser, headRepo, headGitRepo, prInfo, baseBranch, headBranch)
  774. if ctx.Written() {
  775. return
  776. }
  777. ctx.RenderWithErr(ctx.Tr("repo.issues.new.title_empty"), tplCompareDiff, form)
  778. return
  779. }
  780. pullIssue := &models.Issue{
  781. RepoID: repo.ID,
  782. Title: form.Title,
  783. PosterID: ctx.User.ID,
  784. Poster: ctx.User,
  785. MilestoneID: milestoneID,
  786. IsPull: true,
  787. Content: form.Content,
  788. }
  789. pullRequest := &models.PullRequest{
  790. HeadRepoID: headRepo.ID,
  791. BaseRepoID: repo.ID,
  792. HeadBranch: headBranch,
  793. BaseBranch: baseBranch,
  794. HeadRepo: headRepo,
  795. BaseRepo: repo,
  796. MergeBase: prInfo.MergeBase,
  797. Type: models.PullRequestGitea,
  798. }
  799. // FIXME: check error in the case two people send pull request at almost same time, give nice error prompt
  800. // instead of 500.
  801. if err := pull_service.NewPullRequest(repo, pullIssue, labelIDs, attachments, pullRequest, assigneeIDs); err != nil {
  802. if models.IsErrUserDoesNotHaveAccessToRepo(err) {
  803. ctx.Error(400, "UserDoesNotHaveAccessToRepo", err.Error())
  804. return
  805. }
  806. ctx.ServerError("NewPullRequest", err)
  807. return
  808. }
  809. log.Trace("Pull request created: %d/%d", repo.ID, pullIssue.ID)
  810. ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(pullIssue.Index))
  811. }
  812. // TriggerTask response for a trigger task request
  813. func TriggerTask(ctx *context.Context) {
  814. pusherID := ctx.QueryInt64("pusher")
  815. branch := ctx.Query("branch")
  816. secret := ctx.Query("secret")
  817. if len(branch) == 0 || len(secret) == 0 || pusherID <= 0 {
  818. ctx.Error(404)
  819. log.Trace("TriggerTask: branch or secret is empty, or pusher ID is not valid")
  820. return
  821. }
  822. owner, repo := parseOwnerAndRepo(ctx)
  823. if ctx.Written() {
  824. return
  825. }
  826. got := []byte(base.EncodeMD5(owner.Salt))
  827. want := []byte(secret)
  828. if subtle.ConstantTimeCompare(got, want) != 1 {
  829. ctx.Error(404)
  830. log.Trace("TriggerTask [%s/%s]: invalid secret", owner.Name, repo.Name)
  831. return
  832. }
  833. pusher, err := models.GetUserByID(pusherID)
  834. if err != nil {
  835. if models.IsErrUserNotExist(err) {
  836. ctx.Error(404)
  837. } else {
  838. ctx.ServerError("GetUserByID", err)
  839. }
  840. return
  841. }
  842. log.Trace("TriggerTask '%s/%s' by %s", repo.Name, branch, pusher.Name)
  843. go pull_service.AddTestPullRequestTask(pusher, repo.ID, branch, true, "", "")
  844. ctx.Status(202)
  845. }
  846. // CleanUpPullRequest responses for delete merged branch when PR has been merged
  847. func CleanUpPullRequest(ctx *context.Context) {
  848. issue := checkPullInfo(ctx)
  849. if ctx.Written() {
  850. return
  851. }
  852. pr := issue.PullRequest
  853. // Don't cleanup unmerged and unclosed PRs
  854. if !pr.HasMerged && !issue.IsClosed {
  855. ctx.NotFound("CleanUpPullRequest", nil)
  856. return
  857. }
  858. if err := pr.LoadHeadRepo(); err != nil {
  859. ctx.ServerError("LoadHeadRepo", err)
  860. return
  861. } else if pr.HeadRepo == nil {
  862. // Forked repository has already been deleted
  863. ctx.NotFound("CleanUpPullRequest", nil)
  864. return
  865. } else if err = pr.LoadBaseRepo(); err != nil {
  866. ctx.ServerError("LoadBaseRepo", err)
  867. return
  868. } else if err = pr.HeadRepo.GetOwner(); err != nil {
  869. ctx.ServerError("HeadRepo.GetOwner", err)
  870. return
  871. }
  872. perm, err := models.GetUserRepoPermission(pr.HeadRepo, ctx.User)
  873. if err != nil {
  874. ctx.ServerError("GetUserRepoPermission", err)
  875. return
  876. }
  877. if !perm.CanWrite(models.UnitTypeCode) {
  878. ctx.NotFound("CleanUpPullRequest", nil)
  879. return
  880. }
  881. fullBranchName := pr.HeadRepo.Owner.Name + "/" + pr.HeadBranch
  882. gitRepo, err := git.OpenRepository(pr.HeadRepo.RepoPath())
  883. if err != nil {
  884. ctx.ServerError(fmt.Sprintf("OpenRepository[%s]", pr.HeadRepo.RepoPath()), err)
  885. return
  886. }
  887. defer gitRepo.Close()
  888. gitBaseRepo, err := git.OpenRepository(pr.BaseRepo.RepoPath())
  889. if err != nil {
  890. ctx.ServerError(fmt.Sprintf("OpenRepository[%s]", pr.BaseRepo.RepoPath()), err)
  891. return
  892. }
  893. defer gitBaseRepo.Close()
  894. defer func() {
  895. ctx.JSON(200, map[string]interface{}{
  896. "redirect": pr.BaseRepo.Link() + "/pulls/" + com.ToStr(issue.Index),
  897. })
  898. }()
  899. if pr.HeadBranch == pr.HeadRepo.DefaultBranch || !gitRepo.IsBranchExist(pr.HeadBranch) {
  900. ctx.Flash.Error(ctx.Tr("repo.branch.deletion_failed", fullBranchName))
  901. return
  902. }
  903. // Check if branch is not protected
  904. if protected, err := pr.HeadRepo.IsProtectedBranch(pr.HeadBranch, ctx.User); err != nil || protected {
  905. if err != nil {
  906. log.Error("HeadRepo.IsProtectedBranch: %v", err)
  907. }
  908. ctx.Flash.Error(ctx.Tr("repo.branch.deletion_failed", fullBranchName))
  909. return
  910. }
  911. // Check if branch has no new commits
  912. headCommitID, err := gitBaseRepo.GetRefCommitID(pr.GetGitRefName())
  913. if err != nil {
  914. log.Error("GetRefCommitID: %v", err)
  915. ctx.Flash.Error(ctx.Tr("repo.branch.deletion_failed", fullBranchName))
  916. return
  917. }
  918. branchCommitID, err := gitRepo.GetBranchCommitID(pr.HeadBranch)
  919. if err != nil {
  920. log.Error("GetBranchCommitID: %v", err)
  921. ctx.Flash.Error(ctx.Tr("repo.branch.deletion_failed", fullBranchName))
  922. return
  923. }
  924. if headCommitID != branchCommitID {
  925. ctx.Flash.Error(ctx.Tr("repo.branch.delete_branch_has_new_commits", fullBranchName))
  926. return
  927. }
  928. if err := gitRepo.DeleteBranch(pr.HeadBranch, git.DeleteBranchOptions{
  929. Force: true,
  930. }); err != nil {
  931. log.Error("DeleteBranch: %v", err)
  932. ctx.Flash.Error(ctx.Tr("repo.branch.deletion_failed", fullBranchName))
  933. return
  934. }
  935. if err := repofiles.PushUpdate(
  936. pr.HeadRepo,
  937. pr.HeadBranch,
  938. repofiles.PushUpdateOptions{
  939. RefFullName: git.BranchPrefix + pr.HeadBranch,
  940. OldCommitID: branchCommitID,
  941. NewCommitID: git.EmptySHA,
  942. PusherID: ctx.User.ID,
  943. PusherName: ctx.User.Name,
  944. RepoUserName: pr.HeadRepo.Owner.Name,
  945. RepoName: pr.HeadRepo.Name,
  946. }); err != nil {
  947. log.Error("Update: %v", err)
  948. }
  949. if err := models.AddDeletePRBranchComment(ctx.User, pr.BaseRepo, issue.ID, pr.HeadBranch); err != nil {
  950. // Do not fail here as branch has already been deleted
  951. log.Error("DeleteBranch: %v", err)
  952. }
  953. ctx.Flash.Success(ctx.Tr("repo.branch.deletion_success", fullBranchName))
  954. }
  955. // DownloadPullDiff render a pull's raw diff
  956. func DownloadPullDiff(ctx *context.Context) {
  957. DownloadPullDiffOrPatch(ctx, false)
  958. }
  959. // DownloadPullPatch render a pull's raw patch
  960. func DownloadPullPatch(ctx *context.Context) {
  961. DownloadPullDiffOrPatch(ctx, true)
  962. }
  963. // DownloadPullDiffOrPatch render a pull's raw diff or patch
  964. func DownloadPullDiffOrPatch(ctx *context.Context, patch bool) {
  965. issue, err := models.GetIssueByIndex(ctx.Repo.Repository.ID, ctx.ParamsInt64(":index"))
  966. if err != nil {
  967. if models.IsErrIssueNotExist(err) {
  968. ctx.NotFound("GetIssueByIndex", err)
  969. } else {
  970. ctx.ServerError("GetIssueByIndex", err)
  971. }
  972. return
  973. }
  974. // Return not found if it's not a pull request
  975. if !issue.IsPull {
  976. ctx.NotFound("DownloadPullDiff",
  977. fmt.Errorf("Issue is not a pull request"))
  978. return
  979. }
  980. if err = issue.LoadPullRequest(); err != nil {
  981. ctx.ServerError("LoadPullRequest", err)
  982. return
  983. }
  984. pr := issue.PullRequest
  985. if err := pull_service.DownloadDiffOrPatch(pr, ctx, patch); err != nil {
  986. ctx.ServerError("DownloadDiffOrPatch", err)
  987. return
  988. }
  989. }
  990. // UpdatePullRequestTarget change pull request's target branch
  991. func UpdatePullRequestTarget(ctx *context.Context) {
  992. issue := GetActionIssue(ctx)
  993. pr := issue.PullRequest
  994. if ctx.Written() {
  995. return
  996. }
  997. if !issue.IsPull {
  998. ctx.Error(http.StatusNotFound)
  999. return
  1000. }
  1001. if !ctx.IsSigned || (!issue.IsPoster(ctx.User.ID) && !ctx.Repo.CanWriteIssuesOrPulls(issue.IsPull)) {
  1002. ctx.Error(http.StatusForbidden)
  1003. return
  1004. }
  1005. targetBranch := ctx.QueryTrim("target_branch")
  1006. if len(targetBranch) == 0 {
  1007. ctx.Error(http.StatusNoContent)
  1008. return
  1009. }
  1010. if err := pull_service.ChangeTargetBranch(pr, ctx.User, targetBranch); err != nil {
  1011. if models.IsErrPullRequestAlreadyExists(err) {
  1012. err := err.(models.ErrPullRequestAlreadyExists)
  1013. RepoRelPath := ctx.Repo.Owner.Name + "/" + ctx.Repo.Repository.Name
  1014. errorMessage := ctx.Tr("repo.pulls.has_pull_request", ctx.Repo.RepoLink, RepoRelPath, err.IssueID)
  1015. ctx.Flash.Error(errorMessage)
  1016. ctx.JSON(http.StatusConflict, map[string]interface{}{
  1017. "error": err.Error(),
  1018. "user_error": errorMessage,
  1019. })
  1020. } else if models.IsErrIssueIsClosed(err) {
  1021. errorMessage := ctx.Tr("repo.pulls.is_closed")
  1022. ctx.Flash.Error(errorMessage)
  1023. ctx.JSON(http.StatusConflict, map[string]interface{}{
  1024. "error": err.Error(),
  1025. "user_error": errorMessage,
  1026. })
  1027. } else if models.IsErrPullRequestHasMerged(err) {
  1028. errorMessage := ctx.Tr("repo.pulls.has_merged")
  1029. ctx.Flash.Error(errorMessage)
  1030. ctx.JSON(http.StatusConflict, map[string]interface{}{
  1031. "error": err.Error(),
  1032. "user_error": errorMessage,
  1033. })
  1034. } else if models.IsErrBranchesEqual(err) {
  1035. errorMessage := ctx.Tr("repo.pulls.nothing_to_compare")
  1036. ctx.Flash.Error(errorMessage)
  1037. ctx.JSON(http.StatusBadRequest, map[string]interface{}{
  1038. "error": err.Error(),
  1039. "user_error": errorMessage,
  1040. })
  1041. } else {
  1042. ctx.ServerError("UpdatePullRequestTarget", err)
  1043. }
  1044. return
  1045. }
  1046. notification.NotifyPullRequestChangeTargetBranch(ctx.User, pr, targetBranch)
  1047. ctx.JSON(http.StatusOK, map[string]interface{}{
  1048. "base_branch": pr.BaseBranch,
  1049. })
  1050. }