pull.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759
  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. "path"
  8. "strings"
  9. "github.com/Unknwon/com"
  10. log "gopkg.in/clog.v1"
  11. "github.com/gogits/git-module"
  12. "github.com/gogits/gogs/models"
  13. "github.com/gogits/gogs/models/errors"
  14. "github.com/gogits/gogs/pkg/context"
  15. "github.com/gogits/gogs/pkg/form"
  16. "github.com/gogits/gogs/pkg/setting"
  17. "github.com/gogits/gogs/pkg/tool"
  18. )
  19. const (
  20. FORK = "repo/pulls/fork"
  21. COMPARE_PULL = "repo/pulls/compare"
  22. PULL_COMMITS = "repo/pulls/commits"
  23. PULL_FILES = "repo/pulls/files"
  24. PULL_REQUEST_TEMPLATE_KEY = "PullRequestTemplate"
  25. )
  26. var (
  27. PullRequestTemplateCandidates = []string{
  28. "PULL_REQUEST.md",
  29. ".gogs/PULL_REQUEST.md",
  30. ".github/PULL_REQUEST.md",
  31. }
  32. )
  33. func parseBaseRepository(ctx *context.Context) *models.Repository {
  34. baseRepo, err := models.GetRepositoryByID(ctx.ParamsInt64(":repoid"))
  35. if err != nil {
  36. ctx.NotFoundOrServerError("GetRepositoryByID", errors.IsRepoNotExist, err)
  37. return nil
  38. }
  39. if !baseRepo.CanBeForked() || !baseRepo.HasAccess(ctx.User.ID) {
  40. ctx.NotFound()
  41. return nil
  42. }
  43. ctx.Data["repo_name"] = baseRepo.Name
  44. ctx.Data["description"] = baseRepo.Description
  45. ctx.Data["IsPrivate"] = baseRepo.IsPrivate
  46. if err = baseRepo.GetOwner(); err != nil {
  47. ctx.Handle(500, "GetOwner", err)
  48. return nil
  49. }
  50. ctx.Data["ForkFrom"] = baseRepo.Owner.Name + "/" + baseRepo.Name
  51. if err := ctx.User.GetOrganizations(true); err != nil {
  52. ctx.Handle(500, "GetOrganizations", err)
  53. return nil
  54. }
  55. ctx.Data["Orgs"] = ctx.User.Orgs
  56. return baseRepo
  57. }
  58. func Fork(ctx *context.Context) {
  59. ctx.Data["Title"] = ctx.Tr("new_fork")
  60. parseBaseRepository(ctx)
  61. if ctx.Written() {
  62. return
  63. }
  64. ctx.Data["ContextUser"] = ctx.User
  65. ctx.HTML(200, FORK)
  66. }
  67. func ForkPost(ctx *context.Context, f form.CreateRepo) {
  68. ctx.Data["Title"] = ctx.Tr("new_fork")
  69. baseRepo := parseBaseRepository(ctx)
  70. if ctx.Written() {
  71. return
  72. }
  73. ctxUser := checkContextUser(ctx, f.UserID)
  74. if ctx.Written() {
  75. return
  76. }
  77. ctx.Data["ContextUser"] = ctxUser
  78. if ctx.HasError() {
  79. ctx.HTML(200, FORK)
  80. return
  81. }
  82. repo, has := models.HasForkedRepo(ctxUser.ID, baseRepo.ID)
  83. if has {
  84. ctx.Redirect(repo.Link())
  85. return
  86. }
  87. // Check ownership of organization.
  88. if ctxUser.IsOrganization() && !ctxUser.IsOwnedBy(ctx.User.ID) {
  89. ctx.Error(403)
  90. return
  91. }
  92. // Cannot fork to same owner
  93. if ctxUser.ID == baseRepo.OwnerID {
  94. ctx.RenderWithErr(ctx.Tr("repo.settings.cannot_fork_to_same_owner"), FORK, &f)
  95. return
  96. }
  97. repo, err := models.ForkRepository(ctx.User, ctxUser, baseRepo, f.RepoName, f.Description)
  98. if err != nil {
  99. ctx.Data["Err_RepoName"] = true
  100. switch {
  101. case models.IsErrRepoAlreadyExist(err):
  102. ctx.RenderWithErr(ctx.Tr("repo.settings.new_owner_has_same_repo"), FORK, &f)
  103. case models.IsErrNameReserved(err):
  104. ctx.RenderWithErr(ctx.Tr("repo.form.name_reserved", err.(models.ErrNameReserved).Name), FORK, &f)
  105. case models.IsErrNamePatternNotAllowed(err):
  106. ctx.RenderWithErr(ctx.Tr("repo.form.name_pattern_not_allowed", err.(models.ErrNamePatternNotAllowed).Pattern), FORK, &f)
  107. default:
  108. ctx.Handle(500, "ForkPost", err)
  109. }
  110. return
  111. }
  112. log.Trace("Repository forked from '%s' -> '%s'", baseRepo.FullName(), repo.FullName())
  113. ctx.Redirect(repo.Link())
  114. }
  115. func checkPullInfo(ctx *context.Context) *models.Issue {
  116. issue, err := models.GetIssueByIndex(ctx.Repo.Repository.ID, ctx.ParamsInt64(":index"))
  117. if err != nil {
  118. ctx.NotFoundOrServerError("GetIssueByIndex", errors.IsIssueNotExist, err)
  119. return nil
  120. }
  121. ctx.Data["Title"] = issue.Title
  122. ctx.Data["Issue"] = issue
  123. if !issue.IsPull {
  124. ctx.Handle(404, "ViewPullCommits", nil)
  125. return nil
  126. }
  127. if ctx.IsLogged {
  128. // Update issue-user.
  129. if err = issue.ReadBy(ctx.User.ID); err != nil {
  130. ctx.Handle(500, "ReadBy", err)
  131. return nil
  132. }
  133. }
  134. return issue
  135. }
  136. func PrepareMergedViewPullInfo(ctx *context.Context, issue *models.Issue) {
  137. pull := issue.PullRequest
  138. ctx.Data["HasMerged"] = true
  139. ctx.Data["HeadTarget"] = issue.PullRequest.HeadUserName + "/" + pull.HeadBranch
  140. ctx.Data["BaseTarget"] = ctx.Repo.Owner.Name + "/" + pull.BaseBranch
  141. var err error
  142. ctx.Data["NumCommits"], err = ctx.Repo.GitRepo.CommitsCountBetween(pull.MergeBase, pull.MergedCommitID)
  143. if err != nil {
  144. ctx.Handle(500, "Repo.GitRepo.CommitsCountBetween", err)
  145. return
  146. }
  147. ctx.Data["NumFiles"], err = ctx.Repo.GitRepo.FilesCountBetween(pull.MergeBase, pull.MergedCommitID)
  148. if err != nil {
  149. ctx.Handle(500, "Repo.GitRepo.FilesCountBetween", err)
  150. return
  151. }
  152. }
  153. func PrepareViewPullInfo(ctx *context.Context, issue *models.Issue) *git.PullRequestInfo {
  154. repo := ctx.Repo.Repository
  155. pull := issue.PullRequest
  156. ctx.Data["HeadTarget"] = pull.HeadUserName + "/" + pull.HeadBranch
  157. ctx.Data["BaseTarget"] = ctx.Repo.Owner.Name + "/" + pull.BaseBranch
  158. var (
  159. headGitRepo *git.Repository
  160. err error
  161. )
  162. if pull.HeadRepo != nil {
  163. headGitRepo, err = git.OpenRepository(pull.HeadRepo.RepoPath())
  164. if err != nil {
  165. ctx.Handle(500, "OpenRepository", err)
  166. return nil
  167. }
  168. }
  169. if pull.HeadRepo == nil || !headGitRepo.IsBranchExist(pull.HeadBranch) {
  170. ctx.Data["IsPullReuqestBroken"] = true
  171. ctx.Data["HeadTarget"] = "deleted"
  172. ctx.Data["NumCommits"] = 0
  173. ctx.Data["NumFiles"] = 0
  174. return nil
  175. }
  176. prInfo, err := headGitRepo.GetPullRequestInfo(models.RepoPath(repo.Owner.Name, repo.Name),
  177. pull.BaseBranch, pull.HeadBranch)
  178. if err != nil {
  179. if strings.Contains(err.Error(), "fatal: Not a valid object name") {
  180. ctx.Data["IsPullReuqestBroken"] = true
  181. ctx.Data["BaseTarget"] = "deleted"
  182. ctx.Data["NumCommits"] = 0
  183. ctx.Data["NumFiles"] = 0
  184. return nil
  185. }
  186. ctx.Handle(500, "GetPullRequestInfo", err)
  187. return nil
  188. }
  189. ctx.Data["NumCommits"] = prInfo.Commits.Len()
  190. ctx.Data["NumFiles"] = prInfo.NumFiles
  191. return prInfo
  192. }
  193. func ViewPullCommits(ctx *context.Context) {
  194. ctx.Data["PageIsPullList"] = true
  195. ctx.Data["PageIsPullCommits"] = true
  196. issue := checkPullInfo(ctx)
  197. if ctx.Written() {
  198. return
  199. }
  200. pull := issue.PullRequest
  201. if pull.HeadRepo != nil {
  202. ctx.Data["Username"] = pull.HeadUserName
  203. ctx.Data["Reponame"] = pull.HeadRepo.Name
  204. }
  205. var commits *list.List
  206. if pull.HasMerged {
  207. PrepareMergedViewPullInfo(ctx, issue)
  208. if ctx.Written() {
  209. return
  210. }
  211. startCommit, err := ctx.Repo.GitRepo.GetCommit(pull.MergeBase)
  212. if err != nil {
  213. ctx.Handle(500, "Repo.GitRepo.GetCommit", err)
  214. return
  215. }
  216. endCommit, err := ctx.Repo.GitRepo.GetCommit(pull.MergedCommitID)
  217. if err != nil {
  218. ctx.Handle(500, "Repo.GitRepo.GetCommit", err)
  219. return
  220. }
  221. commits, err = ctx.Repo.GitRepo.CommitsBetween(endCommit, startCommit)
  222. if err != nil {
  223. ctx.Handle(500, "Repo.GitRepo.CommitsBetween", err)
  224. return
  225. }
  226. } else {
  227. prInfo := PrepareViewPullInfo(ctx, issue)
  228. if ctx.Written() {
  229. return
  230. } else if prInfo == nil {
  231. ctx.Handle(404, "ViewPullCommits", nil)
  232. return
  233. }
  234. commits = prInfo.Commits
  235. }
  236. commits = models.ValidateCommitsWithEmails(commits)
  237. ctx.Data["Commits"] = commits
  238. ctx.Data["CommitsCount"] = commits.Len()
  239. ctx.HTML(200, PULL_COMMITS)
  240. }
  241. func ViewPullFiles(ctx *context.Context) {
  242. ctx.Data["PageIsPullList"] = true
  243. ctx.Data["PageIsPullFiles"] = true
  244. issue := checkPullInfo(ctx)
  245. if ctx.Written() {
  246. return
  247. }
  248. pull := issue.PullRequest
  249. var (
  250. diffRepoPath string
  251. startCommitID string
  252. endCommitID string
  253. gitRepo *git.Repository
  254. )
  255. if pull.HasMerged {
  256. PrepareMergedViewPullInfo(ctx, issue)
  257. if ctx.Written() {
  258. return
  259. }
  260. diffRepoPath = ctx.Repo.GitRepo.Path
  261. startCommitID = pull.MergeBase
  262. endCommitID = pull.MergedCommitID
  263. gitRepo = ctx.Repo.GitRepo
  264. } else {
  265. prInfo := PrepareViewPullInfo(ctx, issue)
  266. if ctx.Written() {
  267. return
  268. } else if prInfo == nil {
  269. ctx.Handle(404, "ViewPullFiles", nil)
  270. return
  271. }
  272. headRepoPath := models.RepoPath(pull.HeadUserName, pull.HeadRepo.Name)
  273. headGitRepo, err := git.OpenRepository(headRepoPath)
  274. if err != nil {
  275. ctx.Handle(500, "OpenRepository", err)
  276. return
  277. }
  278. headCommitID, err := headGitRepo.GetBranchCommitID(pull.HeadBranch)
  279. if err != nil {
  280. ctx.Handle(500, "GetBranchCommitID", err)
  281. return
  282. }
  283. diffRepoPath = headRepoPath
  284. startCommitID = prInfo.MergeBase
  285. endCommitID = headCommitID
  286. gitRepo = headGitRepo
  287. }
  288. diff, err := models.GetDiffRange(diffRepoPath,
  289. startCommitID, endCommitID, setting.Git.MaxGitDiffLines,
  290. setting.Git.MaxGitDiffLineCharacters, setting.Git.MaxGitDiffFiles)
  291. if err != nil {
  292. ctx.Handle(500, "GetDiffRange", err)
  293. return
  294. }
  295. ctx.Data["Diff"] = diff
  296. ctx.Data["DiffNotAvailable"] = diff.NumFiles() == 0
  297. commit, err := gitRepo.GetCommit(endCommitID)
  298. if err != nil {
  299. ctx.Handle(500, "GetCommit", err)
  300. return
  301. }
  302. setEditorconfigIfExists(ctx)
  303. if ctx.Written() {
  304. return
  305. }
  306. ctx.Data["IsSplitStyle"] = ctx.Query("style") == "split"
  307. ctx.Data["IsImageFile"] = commit.IsImageFile
  308. // It is possible head repo has been deleted for merged pull requests
  309. if pull.HeadRepo != nil {
  310. ctx.Data["Username"] = pull.HeadUserName
  311. ctx.Data["Reponame"] = pull.HeadRepo.Name
  312. headTarget := path.Join(pull.HeadUserName, pull.HeadRepo.Name)
  313. ctx.Data["SourcePath"] = setting.AppSubURL + "/" + path.Join(headTarget, "src", endCommitID)
  314. ctx.Data["BeforeSourcePath"] = setting.AppSubURL + "/" + path.Join(headTarget, "src", startCommitID)
  315. ctx.Data["RawPath"] = setting.AppSubURL + "/" + path.Join(headTarget, "raw", endCommitID)
  316. }
  317. ctx.Data["RequireHighlightJS"] = true
  318. ctx.HTML(200, PULL_FILES)
  319. }
  320. func MergePullRequest(ctx *context.Context) {
  321. issue := checkPullInfo(ctx)
  322. if ctx.Written() {
  323. return
  324. }
  325. if issue.IsClosed {
  326. ctx.Handle(404, "MergePullRequest", nil)
  327. return
  328. }
  329. pr, err := models.GetPullRequestByIssueID(issue.ID)
  330. if err != nil {
  331. ctx.NotFoundOrServerError("GetPullRequestByIssueID", models.IsErrPullRequestNotExist, err)
  332. return
  333. }
  334. if !pr.CanAutoMerge() || pr.HasMerged {
  335. ctx.Handle(404, "MergePullRequest", nil)
  336. return
  337. }
  338. pr.Issue = issue
  339. pr.Issue.Repo = ctx.Repo.Repository
  340. if err = pr.Merge(ctx.User, ctx.Repo.GitRepo); err != nil {
  341. ctx.Handle(500, "Merge", err)
  342. return
  343. }
  344. log.Trace("Pull request merged: %d", pr.ID)
  345. ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(pr.Index))
  346. }
  347. func ParseCompareInfo(ctx *context.Context) (*models.User, *models.Repository, *git.Repository, *git.PullRequestInfo, string, string) {
  348. baseRepo := ctx.Repo.Repository
  349. // Get compared branches information
  350. // format: <base branch>...[<head repo>:]<head branch>
  351. // base<-head: master...head:feature
  352. // same repo: master...feature
  353. infos := strings.Split(ctx.Params("*"), "...")
  354. if len(infos) != 2 {
  355. log.Trace("ParseCompareInfo[%d]: not enough compared branches information %s", baseRepo.ID, infos)
  356. ctx.Handle(404, "CompareAndPullRequest", nil)
  357. return nil, nil, nil, nil, "", ""
  358. }
  359. baseBranch := infos[0]
  360. ctx.Data["BaseBranch"] = baseBranch
  361. var (
  362. headUser *models.User
  363. headBranch string
  364. isSameRepo bool
  365. err error
  366. )
  367. // If there is no head repository, it means pull request between same repository.
  368. headInfos := strings.Split(infos[1], ":")
  369. if len(headInfos) == 1 {
  370. isSameRepo = true
  371. headUser = ctx.Repo.Owner
  372. headBranch = headInfos[0]
  373. } else if len(headInfos) == 2 {
  374. headUser, err = models.GetUserByName(headInfos[0])
  375. if err != nil {
  376. ctx.NotFoundOrServerError("GetUserByName", errors.IsUserNotExist, err)
  377. return nil, nil, nil, nil, "", ""
  378. }
  379. headBranch = headInfos[1]
  380. isSameRepo = headUser.ID == baseRepo.OwnerID
  381. } else {
  382. ctx.Handle(404, "CompareAndPullRequest", nil)
  383. return nil, nil, nil, nil, "", ""
  384. }
  385. ctx.Data["HeadUser"] = headUser
  386. ctx.Data["HeadBranch"] = headBranch
  387. ctx.Repo.PullRequest.SameRepo = isSameRepo
  388. // Check if base branch is valid.
  389. if !ctx.Repo.GitRepo.IsBranchExist(baseBranch) {
  390. ctx.Handle(404, "IsBranchExist", nil)
  391. return nil, nil, nil, nil, "", ""
  392. }
  393. var (
  394. headRepo *models.Repository
  395. headGitRepo *git.Repository
  396. )
  397. // In case user included redundant head user name for comparison in same repository,
  398. // no need to check the fork relation.
  399. if !isSameRepo {
  400. var has bool
  401. headRepo, has = models.HasForkedRepo(headUser.ID, baseRepo.ID)
  402. if !has {
  403. log.Trace("ParseCompareInfo[%d]: does not have fork or in same repository", baseRepo.ID)
  404. ctx.Handle(404, "ParseCompareInfo", nil)
  405. return nil, nil, nil, nil, "", ""
  406. }
  407. headGitRepo, err = git.OpenRepository(models.RepoPath(headUser.Name, headRepo.Name))
  408. if err != nil {
  409. ctx.Handle(500, "OpenRepository", err)
  410. return nil, nil, nil, nil, "", ""
  411. }
  412. } else {
  413. headRepo = ctx.Repo.Repository
  414. headGitRepo = ctx.Repo.GitRepo
  415. }
  416. if !ctx.User.IsWriterOfRepo(headRepo) && !ctx.User.IsAdmin {
  417. log.Trace("ParseCompareInfo[%d]: does not have write access or site admin", baseRepo.ID)
  418. ctx.Handle(404, "ParseCompareInfo", nil)
  419. return nil, nil, nil, nil, "", ""
  420. }
  421. // Check if head branch is valid.
  422. if !headGitRepo.IsBranchExist(headBranch) {
  423. ctx.Handle(404, "IsBranchExist", nil)
  424. return nil, nil, nil, nil, "", ""
  425. }
  426. headBranches, err := headGitRepo.GetBranches()
  427. if err != nil {
  428. ctx.Handle(500, "GetBranches", err)
  429. return nil, nil, nil, nil, "", ""
  430. }
  431. ctx.Data["HeadBranches"] = headBranches
  432. prInfo, err := headGitRepo.GetPullRequestInfo(models.RepoPath(baseRepo.Owner.Name, baseRepo.Name), baseBranch, headBranch)
  433. if err != nil {
  434. ctx.Handle(500, "GetPullRequestInfo", err)
  435. return nil, nil, nil, nil, "", ""
  436. }
  437. ctx.Data["BeforeCommitID"] = prInfo.MergeBase
  438. return headUser, headRepo, headGitRepo, prInfo, baseBranch, headBranch
  439. }
  440. func PrepareCompareDiff(
  441. ctx *context.Context,
  442. headUser *models.User,
  443. headRepo *models.Repository,
  444. headGitRepo *git.Repository,
  445. prInfo *git.PullRequestInfo,
  446. baseBranch, headBranch string) bool {
  447. var (
  448. repo = ctx.Repo.Repository
  449. err error
  450. )
  451. // Get diff information.
  452. ctx.Data["CommitRepoLink"] = headRepo.Link()
  453. headCommitID, err := headGitRepo.GetBranchCommitID(headBranch)
  454. if err != nil {
  455. ctx.Handle(500, "GetBranchCommitID", err)
  456. return false
  457. }
  458. ctx.Data["AfterCommitID"] = headCommitID
  459. if headCommitID == prInfo.MergeBase {
  460. ctx.Data["IsNothingToCompare"] = true
  461. return true
  462. }
  463. diff, err := models.GetDiffRange(models.RepoPath(headUser.Name, headRepo.Name),
  464. prInfo.MergeBase, headCommitID, setting.Git.MaxGitDiffLines,
  465. setting.Git.MaxGitDiffLineCharacters, setting.Git.MaxGitDiffFiles)
  466. if err != nil {
  467. ctx.Handle(500, "GetDiffRange", err)
  468. return false
  469. }
  470. ctx.Data["Diff"] = diff
  471. ctx.Data["DiffNotAvailable"] = diff.NumFiles() == 0
  472. headCommit, err := headGitRepo.GetCommit(headCommitID)
  473. if err != nil {
  474. ctx.Handle(500, "GetCommit", err)
  475. return false
  476. }
  477. prInfo.Commits = models.ValidateCommitsWithEmails(prInfo.Commits)
  478. ctx.Data["Commits"] = prInfo.Commits
  479. ctx.Data["CommitCount"] = prInfo.Commits.Len()
  480. ctx.Data["Username"] = headUser.Name
  481. ctx.Data["Reponame"] = headRepo.Name
  482. ctx.Data["IsImageFile"] = headCommit.IsImageFile
  483. headTarget := path.Join(headUser.Name, repo.Name)
  484. ctx.Data["SourcePath"] = setting.AppSubURL + "/" + path.Join(headTarget, "src", headCommitID)
  485. ctx.Data["BeforeSourcePath"] = setting.AppSubURL + "/" + path.Join(headTarget, "src", prInfo.MergeBase)
  486. ctx.Data["RawPath"] = setting.AppSubURL + "/" + path.Join(headTarget, "raw", headCommitID)
  487. return false
  488. }
  489. func CompareAndPullRequest(ctx *context.Context) {
  490. ctx.Data["Title"] = ctx.Tr("repo.pulls.compare_changes")
  491. ctx.Data["PageIsComparePull"] = true
  492. ctx.Data["IsDiffCompare"] = true
  493. ctx.Data["RequireHighlightJS"] = true
  494. setTemplateIfExists(ctx, PULL_REQUEST_TEMPLATE_KEY, PullRequestTemplateCandidates)
  495. renderAttachmentSettings(ctx)
  496. headUser, headRepo, headGitRepo, prInfo, baseBranch, headBranch := ParseCompareInfo(ctx)
  497. if ctx.Written() {
  498. return
  499. }
  500. pr, err := models.GetUnmergedPullRequest(headRepo.ID, ctx.Repo.Repository.ID, headBranch, baseBranch)
  501. if err != nil {
  502. if !models.IsErrPullRequestNotExist(err) {
  503. ctx.Handle(500, "GetUnmergedPullRequest", err)
  504. return
  505. }
  506. } else {
  507. ctx.Data["HasPullRequest"] = true
  508. ctx.Data["PullRequest"] = pr
  509. ctx.HTML(200, COMPARE_PULL)
  510. return
  511. }
  512. nothingToCompare := PrepareCompareDiff(ctx, headUser, headRepo, headGitRepo, prInfo, baseBranch, headBranch)
  513. if ctx.Written() {
  514. return
  515. }
  516. if !nothingToCompare {
  517. // Setup information for new form.
  518. RetrieveRepoMetas(ctx, ctx.Repo.Repository)
  519. if ctx.Written() {
  520. return
  521. }
  522. }
  523. setEditorconfigIfExists(ctx)
  524. if ctx.Written() {
  525. return
  526. }
  527. ctx.Data["IsSplitStyle"] = ctx.Query("style") == "split"
  528. ctx.HTML(200, COMPARE_PULL)
  529. }
  530. func CompareAndPullRequestPost(ctx *context.Context, f form.NewIssue) {
  531. ctx.Data["Title"] = ctx.Tr("repo.pulls.compare_changes")
  532. ctx.Data["PageIsComparePull"] = true
  533. ctx.Data["IsDiffCompare"] = true
  534. ctx.Data["RequireHighlightJS"] = true
  535. renderAttachmentSettings(ctx)
  536. var (
  537. repo = ctx.Repo.Repository
  538. attachments []string
  539. )
  540. headUser, headRepo, headGitRepo, prInfo, baseBranch, headBranch := ParseCompareInfo(ctx)
  541. if ctx.Written() {
  542. return
  543. }
  544. labelIDs, milestoneID, assigneeID := ValidateRepoMetas(ctx, f)
  545. if ctx.Written() {
  546. return
  547. }
  548. if setting.AttachmentEnabled {
  549. attachments = f.Files
  550. }
  551. if ctx.HasError() {
  552. form.Assign(f, ctx.Data)
  553. // This stage is already stop creating new pull request, so it does not matter if it has
  554. // something to compare or not.
  555. PrepareCompareDiff(ctx, headUser, headRepo, headGitRepo, prInfo, baseBranch, headBranch)
  556. if ctx.Written() {
  557. return
  558. }
  559. ctx.HTML(200, COMPARE_PULL)
  560. return
  561. }
  562. patch, err := headGitRepo.GetPatch(prInfo.MergeBase, headBranch)
  563. if err != nil {
  564. ctx.Handle(500, "GetPatch", err)
  565. return
  566. }
  567. pullIssue := &models.Issue{
  568. RepoID: repo.ID,
  569. Index: repo.NextIssueIndex(),
  570. Title: f.Title,
  571. PosterID: ctx.User.ID,
  572. Poster: ctx.User,
  573. MilestoneID: milestoneID,
  574. AssigneeID: assigneeID,
  575. IsPull: true,
  576. Content: f.Content,
  577. }
  578. pullRequest := &models.PullRequest{
  579. HeadRepoID: headRepo.ID,
  580. BaseRepoID: repo.ID,
  581. HeadUserName: headUser.Name,
  582. HeadBranch: headBranch,
  583. BaseBranch: baseBranch,
  584. HeadRepo: headRepo,
  585. BaseRepo: repo,
  586. MergeBase: prInfo.MergeBase,
  587. Type: models.PULL_REQUEST_GOGS,
  588. }
  589. // FIXME: check error in the case two people send pull request at almost same time, give nice error prompt
  590. // instead of 500.
  591. if err := models.NewPullRequest(repo, pullIssue, labelIDs, attachments, pullRequest, patch); err != nil {
  592. ctx.Handle(500, "NewPullRequest", err)
  593. return
  594. } else if err := pullRequest.PushToBaseRepo(); err != nil {
  595. ctx.Handle(500, "PushToBaseRepo", err)
  596. return
  597. }
  598. log.Trace("Pull request created: %d/%d", repo.ID, pullIssue.ID)
  599. ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(pullIssue.Index))
  600. }
  601. func parseOwnerAndRepo(ctx *context.Context) (*models.User, *models.Repository) {
  602. owner, err := models.GetUserByName(ctx.Params(":username"))
  603. if err != nil {
  604. ctx.NotFoundOrServerError("GetUserByName", errors.IsUserNotExist, err)
  605. return nil, nil
  606. }
  607. repo, err := models.GetRepositoryByName(owner.ID, ctx.Params(":reponame"))
  608. if err != nil {
  609. ctx.NotFoundOrServerError("GetRepositoryByName", errors.IsRepoNotExist, err)
  610. return nil, nil
  611. }
  612. return owner, repo
  613. }
  614. func TriggerTask(ctx *context.Context) {
  615. pusherID := ctx.QueryInt64("pusher")
  616. branch := ctx.Query("branch")
  617. secret := ctx.Query("secret")
  618. if len(branch) == 0 || len(secret) == 0 || pusherID <= 0 {
  619. ctx.Error(404)
  620. log.Trace("TriggerTask: branch or secret is empty, or pusher ID is not valid")
  621. return
  622. }
  623. owner, repo := parseOwnerAndRepo(ctx)
  624. if ctx.Written() {
  625. return
  626. }
  627. if secret != tool.MD5(owner.Salt) {
  628. ctx.Error(404)
  629. log.Trace("TriggerTask [%s/%s]: invalid secret", owner.Name, repo.Name)
  630. return
  631. }
  632. pusher, err := models.GetUserByID(pusherID)
  633. if err != nil {
  634. ctx.NotFoundOrServerError("GetUserByID", errors.IsUserNotExist, err)
  635. return
  636. }
  637. log.Trace("TriggerTask '%s/%s' by '%s'", repo.Name, branch, pusher.Name)
  638. go models.HookQueue.Add(repo.ID)
  639. go models.AddTestPullRequestTask(pusher, repo.ID, branch, true)
  640. ctx.Status(202)
  641. }