pull.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753
  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. "time"
  10. "github.com/unknwon/com"
  11. log "unknwon.dev/clog/v2"
  12. "github.com/gogs/git-module"
  13. "gogs.io/gogs/internal/conf"
  14. "gogs.io/gogs/internal/context"
  15. "gogs.io/gogs/internal/db"
  16. "gogs.io/gogs/internal/form"
  17. "gogs.io/gogs/internal/gitutil"
  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. PULL_REQUEST_TITLE_TEMPLATE_KEY = "PullRequestTitleTemplate"
  26. )
  27. var (
  28. PullRequestTemplateCandidates = []string{
  29. "PULL_REQUEST.md",
  30. ".gogs/PULL_REQUEST.md",
  31. ".github/PULL_REQUEST.md",
  32. }
  33. PullRequestTitleTemplateCandidates = []string{
  34. "PULL_REQUEST_TITLE.md",
  35. ".gogs/PULL_REQUEST_TITLE.md",
  36. ".github/PULL_REQUEST_TITLE.md",
  37. }
  38. )
  39. func parseBaseRepository(c *context.Context) *db.Repository {
  40. baseRepo, err := db.GetRepositoryByID(c.ParamsInt64(":repoid"))
  41. if err != nil {
  42. c.NotFoundOrError(err, "get repository by ID")
  43. return nil
  44. }
  45. if !baseRepo.CanBeForked() || !baseRepo.HasAccess(c.User.ID) {
  46. c.NotFound()
  47. return nil
  48. }
  49. c.Data["repo_name"] = baseRepo.Name
  50. c.Data["description"] = baseRepo.Description
  51. c.Data["IsPrivate"] = baseRepo.IsPrivate
  52. c.Data["IsUnlisted"] = baseRepo.IsUnlisted
  53. if err = baseRepo.GetOwner(); err != nil {
  54. c.Error(err, "get owner")
  55. return nil
  56. }
  57. c.Data["ForkFrom"] = baseRepo.Owner.Name + "/" + baseRepo.Name
  58. if err := c.User.GetOrganizations(true); err != nil {
  59. c.Error(err, "get organizations")
  60. return nil
  61. }
  62. c.Data["Orgs"] = c.User.Orgs
  63. return baseRepo
  64. }
  65. func Fork(c *context.Context) {
  66. c.Data["Title"] = c.Tr("new_fork")
  67. parseBaseRepository(c)
  68. if c.Written() {
  69. return
  70. }
  71. c.Data["ContextUser"] = c.User
  72. c.Success(FORK)
  73. }
  74. func ForkPost(c *context.Context, f form.CreateRepo) {
  75. c.Data["Title"] = c.Tr("new_fork")
  76. baseRepo := parseBaseRepository(c)
  77. if c.Written() {
  78. return
  79. }
  80. ctxUser := checkContextUser(c, f.UserID)
  81. if c.Written() {
  82. return
  83. }
  84. c.Data["ContextUser"] = ctxUser
  85. if c.HasError() {
  86. c.Success(FORK)
  87. return
  88. }
  89. repo, has, err := db.HasForkedRepo(ctxUser.ID, baseRepo.ID)
  90. if err != nil {
  91. c.Error(err, "check forked repository")
  92. return
  93. } else if has {
  94. c.Redirect(repo.Link())
  95. return
  96. }
  97. // Check ownership of organization.
  98. if ctxUser.IsOrganization() && !ctxUser.IsOwnedBy(c.User.ID) {
  99. c.Status(http.StatusForbidden)
  100. return
  101. }
  102. // Cannot fork to same owner
  103. if ctxUser.ID == baseRepo.OwnerID {
  104. c.RenderWithErr(c.Tr("repo.settings.cannot_fork_to_same_owner"), FORK, &f)
  105. return
  106. }
  107. repo, err = db.ForkRepository(c.User, ctxUser, baseRepo, f.RepoName, f.Description)
  108. if err != nil {
  109. c.Data["Err_RepoName"] = true
  110. switch {
  111. case db.IsErrReachLimitOfRepo(err):
  112. c.RenderWithErr(c.Tr("repo.form.reach_limit_of_creation", err.(db.ErrReachLimitOfRepo).Limit), FORK, &f)
  113. case db.IsErrRepoAlreadyExist(err):
  114. c.RenderWithErr(c.Tr("repo.settings.new_owner_has_same_repo"), FORK, &f)
  115. case db.IsErrNameNotAllowed(err):
  116. c.RenderWithErr(c.Tr("repo.form.name_not_allowed", err.(db.ErrNameNotAllowed).Value()), 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, Timeout: time.Duration(conf.Git.Timeout.Diff) * time.Second},
  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 !db.Perms.Authorize(
  433. c.Req.Context(),
  434. c.User.ID,
  435. headRepo.ID,
  436. db.AccessModeWrite,
  437. db.AccessModeOptions{
  438. OwnerID: headRepo.OwnerID,
  439. Private: headRepo.IsPrivate,
  440. },
  441. ) && !c.User.IsAdmin {
  442. log.Trace("ParseCompareInfo [base_repo_id: %d]: does not have write access or site admin", baseRepo.ID)
  443. c.NotFound()
  444. return nil, nil, nil, nil, "", ""
  445. }
  446. // Check if head branch is valid.
  447. if !headGitRepo.HasBranch(headBranch) {
  448. c.NotFound()
  449. return nil, nil, nil, nil, "", ""
  450. }
  451. headBranches, err := headGitRepo.Branches()
  452. if err != nil {
  453. c.Error(err, "get branches")
  454. return nil, nil, nil, nil, "", ""
  455. }
  456. c.Data["HeadBranches"] = headBranches
  457. baseRepoPath := db.RepoPath(baseRepo.Owner.Name, baseRepo.Name)
  458. meta, err := gitutil.Module.PullRequestMeta(headGitRepo.Path(), baseRepoPath, headBranch, baseBranch)
  459. if err != nil {
  460. if gitutil.IsErrNoMergeBase(err) {
  461. c.Data["IsNoMergeBase"] = true
  462. c.Success(COMPARE_PULL)
  463. } else {
  464. c.Error(err, "get pull request meta")
  465. }
  466. return nil, nil, nil, nil, "", ""
  467. }
  468. c.Data["BeforeCommitID"] = meta.MergeBase
  469. return headUser, headRepo, headGitRepo, meta, baseBranch, headBranch
  470. }
  471. func PrepareCompareDiff(
  472. c *context.Context,
  473. headUser *db.User,
  474. headRepo *db.Repository,
  475. headGitRepo *git.Repository,
  476. meta *gitutil.PullRequestMeta,
  477. headBranch string,
  478. ) bool {
  479. var (
  480. repo = c.Repo.Repository
  481. err error
  482. )
  483. // Get diff information.
  484. c.Data["CommitRepoLink"] = headRepo.Link()
  485. headCommitID, err := headGitRepo.BranchCommitID(headBranch)
  486. if err != nil {
  487. c.Error(err, "get head branch commit ID")
  488. return false
  489. }
  490. c.Data["AfterCommitID"] = headCommitID
  491. if headCommitID == meta.MergeBase {
  492. c.Data["IsNothingToCompare"] = true
  493. return true
  494. }
  495. diff, err := gitutil.RepoDiff(headGitRepo,
  496. headCommitID, conf.Git.MaxDiffFiles, conf.Git.MaxDiffLines, conf.Git.MaxDiffLineChars,
  497. git.DiffOptions{Base: meta.MergeBase, Timeout: time.Duration(conf.Git.Timeout.Diff) * time.Second},
  498. )
  499. if err != nil {
  500. c.Error(err, "get repository diff")
  501. return false
  502. }
  503. c.Data["Diff"] = diff
  504. c.Data["DiffNotAvailable"] = diff.NumFiles() == 0
  505. headCommit, err := headGitRepo.CatFileCommit(headCommitID)
  506. if err != nil {
  507. c.Error(err, "get head commit")
  508. return false
  509. }
  510. c.Data["Commits"] = db.ValidateCommitsWithEmails(meta.Commits)
  511. c.Data["CommitCount"] = len(meta.Commits)
  512. c.Data["Username"] = headUser.Name
  513. c.Data["Reponame"] = headRepo.Name
  514. c.Data["IsImageFile"] = headCommit.IsImageFile
  515. c.Data["IsImageFileByIndex"] = headCommit.IsImageFileByIndex
  516. headTarget := path.Join(headUser.Name, repo.Name)
  517. c.Data["SourcePath"] = conf.Server.Subpath + "/" + path.Join(headTarget, "src", headCommitID)
  518. c.Data["RawPath"] = conf.Server.Subpath + "/" + path.Join(headTarget, "raw", headCommitID)
  519. c.Data["BeforeSourcePath"] = conf.Server.Subpath + "/" + path.Join(headTarget, "src", meta.MergeBase)
  520. c.Data["BeforeRawPath"] = conf.Server.Subpath + "/" + path.Join(headTarget, "raw", meta.MergeBase)
  521. return false
  522. }
  523. func CompareAndPullRequest(c *context.Context) {
  524. c.Data["Title"] = c.Tr("repo.pulls.compare_changes")
  525. c.Data["PageIsComparePull"] = true
  526. c.Data["IsDiffCompare"] = true
  527. c.Data["RequireHighlightJS"] = true
  528. setTemplateIfExists(c, PULL_REQUEST_TEMPLATE_KEY, PullRequestTemplateCandidates)
  529. renderAttachmentSettings(c)
  530. headUser, headRepo, headGitRepo, prInfo, baseBranch, headBranch := ParseCompareInfo(c)
  531. if c.Written() {
  532. return
  533. }
  534. pr, err := db.GetUnmergedPullRequest(headRepo.ID, c.Repo.Repository.ID, headBranch, baseBranch)
  535. if err != nil {
  536. if !db.IsErrPullRequestNotExist(err) {
  537. c.Error(err, "get unmerged pull request")
  538. return
  539. }
  540. } else {
  541. c.Data["HasPullRequest"] = true
  542. c.Data["PullRequest"] = pr
  543. c.Success(COMPARE_PULL)
  544. return
  545. }
  546. nothingToCompare := PrepareCompareDiff(c, headUser, headRepo, headGitRepo, prInfo, headBranch)
  547. if c.Written() {
  548. return
  549. }
  550. if !nothingToCompare {
  551. // Setup information for new form.
  552. RetrieveRepoMetas(c, c.Repo.Repository)
  553. if c.Written() {
  554. return
  555. }
  556. }
  557. setEditorconfigIfExists(c)
  558. if c.Written() {
  559. return
  560. }
  561. c.Data["IsSplitStyle"] = c.Query("style") == "split"
  562. setTemplateIfExists(c, PULL_REQUEST_TITLE_TEMPLATE_KEY, PullRequestTitleTemplateCandidates)
  563. if c.Data[PULL_REQUEST_TITLE_TEMPLATE_KEY] != nil {
  564. customTitle := c.Data[PULL_REQUEST_TITLE_TEMPLATE_KEY].(string)
  565. r := strings.NewReplacer("{{headBranch}}", headBranch, "{{baseBranch}}", baseBranch)
  566. c.Data["title"] = r.Replace(customTitle)
  567. }
  568. c.Success(COMPARE_PULL)
  569. }
  570. func CompareAndPullRequestPost(c *context.Context, f form.NewIssue) {
  571. c.Data["Title"] = c.Tr("repo.pulls.compare_changes")
  572. c.Data["PageIsComparePull"] = true
  573. c.Data["IsDiffCompare"] = true
  574. c.Data["RequireHighlightJS"] = true
  575. renderAttachmentSettings(c)
  576. var (
  577. repo = c.Repo.Repository
  578. attachments []string
  579. )
  580. headUser, headRepo, headGitRepo, meta, baseBranch, headBranch := ParseCompareInfo(c)
  581. if c.Written() {
  582. return
  583. }
  584. labelIDs, milestoneID, assigneeID := ValidateRepoMetas(c, f)
  585. if c.Written() {
  586. return
  587. }
  588. if conf.Attachment.Enabled {
  589. attachments = f.Files
  590. }
  591. if c.HasError() {
  592. form.Assign(f, c.Data)
  593. // This stage is already stop creating new pull request, so it does not matter if it has
  594. // something to compare or not.
  595. PrepareCompareDiff(c, headUser, headRepo, headGitRepo, meta, headBranch)
  596. if c.Written() {
  597. return
  598. }
  599. c.Success(COMPARE_PULL)
  600. return
  601. }
  602. patch, err := headGitRepo.DiffBinary(meta.MergeBase, headBranch)
  603. if err != nil {
  604. c.Error(err, "get patch")
  605. return
  606. }
  607. pullIssue := &db.Issue{
  608. RepoID: repo.ID,
  609. Index: repo.NextIssueIndex(),
  610. Title: f.Title,
  611. PosterID: c.User.ID,
  612. Poster: c.User,
  613. MilestoneID: milestoneID,
  614. AssigneeID: assigneeID,
  615. IsPull: true,
  616. Content: f.Content,
  617. }
  618. pullRequest := &db.PullRequest{
  619. HeadRepoID: headRepo.ID,
  620. BaseRepoID: repo.ID,
  621. HeadUserName: headUser.Name,
  622. HeadBranch: headBranch,
  623. BaseBranch: baseBranch,
  624. HeadRepo: headRepo,
  625. BaseRepo: repo,
  626. MergeBase: meta.MergeBase,
  627. Type: db.PULL_REQUEST_GOGS,
  628. }
  629. // FIXME: check error in the case two people send pull request at almost same time, give nice error prompt
  630. // instead of 500.
  631. if err := db.NewPullRequest(repo, pullIssue, labelIDs, attachments, pullRequest, patch); err != nil {
  632. c.Error(err, "new pull request")
  633. return
  634. } else if err := pullRequest.PushToBaseRepo(); err != nil {
  635. c.Error(err, "push to base repository")
  636. return
  637. }
  638. log.Trace("Pull request created: %d/%d", repo.ID, pullIssue.ID)
  639. c.Redirect(c.Repo.RepoLink + "/pulls/" + com.ToStr(pullIssue.Index))
  640. }