pull.go 19 KB

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