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