pull.go 19 KB

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