pull.go 20 KB

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