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

1074 lines
29 KiB

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