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

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