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