1
0

pull.go 19 KB

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