You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

pull.go 30 kB

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