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 34KB

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