pull.go 20 KB

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