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 28 kB

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