pull.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794
  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. c.Data["IsImageFileByIndex"] = commit.IsImageFileByIndex
  321. // It is possible head repo has been deleted for merged pull requests
  322. if pull.HeadRepo != nil {
  323. c.Data["Username"] = pull.HeadUserName
  324. c.Data["Reponame"] = pull.HeadRepo.Name
  325. headTarget := path.Join(pull.HeadUserName, pull.HeadRepo.Name)
  326. c.Data["SourcePath"] = conf.Server.Subpath + "/" + path.Join(headTarget, "src", endCommitID)
  327. c.Data["RawPath"] = conf.Server.Subpath + "/" + path.Join(headTarget, "raw", endCommitID)
  328. c.Data["BeforeSourcePath"] = conf.Server.Subpath + "/" + path.Join(headTarget, "src", startCommitID)
  329. c.Data["BeforeRawPath"] = conf.Server.Subpath + "/" + path.Join(headTarget, "raw", startCommitID)
  330. }
  331. c.Data["RequireHighlightJS"] = true
  332. c.Success(PULL_FILES)
  333. }
  334. func MergePullRequest(c *context.Context) {
  335. issue := checkPullInfo(c)
  336. if c.Written() {
  337. return
  338. }
  339. if issue.IsClosed {
  340. c.NotFound()
  341. return
  342. }
  343. pr, err := db.GetPullRequestByIssueID(issue.ID)
  344. if err != nil {
  345. c.NotFoundOrError(err, "get pull request by issue ID")
  346. return
  347. }
  348. if !pr.CanAutoMerge() || pr.HasMerged {
  349. c.NotFound()
  350. return
  351. }
  352. pr.Issue = issue
  353. pr.Issue.Repo = c.Repo.Repository
  354. if err = pr.Merge(c.User, c.Repo.GitRepo, db.MergeStyle(c.Query("merge_style")), c.Query("commit_description")); err != nil {
  355. c.Error(err, "merge")
  356. return
  357. }
  358. log.Trace("Pull request merged: %d", pr.ID)
  359. c.Redirect(c.Repo.RepoLink + "/pulls/" + com.ToStr(pr.Index))
  360. }
  361. func ParseCompareInfo(c *context.Context) (*db.User, *db.Repository, *git.Repository, *gitutil.PullRequestMeta, string, string) {
  362. baseRepo := c.Repo.Repository
  363. // Get compared branches information
  364. // format: <base branch>...[<head repo>:]<head branch>
  365. // base<-head: master...head:feature
  366. // same repo: master...feature
  367. infos := strings.Split(c.Params("*"), "...")
  368. if len(infos) != 2 {
  369. log.Trace("ParseCompareInfo[%d]: not enough compared branches information %s", baseRepo.ID, infos)
  370. c.NotFound()
  371. return nil, nil, nil, nil, "", ""
  372. }
  373. baseBranch := infos[0]
  374. c.Data["BaseBranch"] = baseBranch
  375. var (
  376. headUser *db.User
  377. headBranch string
  378. isSameRepo bool
  379. err error
  380. )
  381. // If there is no head repository, it means pull request between same repository.
  382. headInfos := strings.Split(infos[1], ":")
  383. if len(headInfos) == 1 {
  384. isSameRepo = true
  385. headUser = c.Repo.Owner
  386. headBranch = headInfos[0]
  387. } else if len(headInfos) == 2 {
  388. headUser, err = db.GetUserByName(headInfos[0])
  389. if err != nil {
  390. c.NotFoundOrError(err, "get user by name")
  391. return nil, nil, nil, nil, "", ""
  392. }
  393. headBranch = headInfos[1]
  394. isSameRepo = headUser.ID == baseRepo.OwnerID
  395. } else {
  396. c.NotFound()
  397. return nil, nil, nil, nil, "", ""
  398. }
  399. c.Data["HeadUser"] = headUser
  400. c.Data["HeadBranch"] = headBranch
  401. c.Repo.PullRequest.SameRepo = isSameRepo
  402. // Check if base branch is valid.
  403. if !c.Repo.GitRepo.HasBranch(baseBranch) {
  404. c.NotFound()
  405. return nil, nil, nil, nil, "", ""
  406. }
  407. var (
  408. headRepo *db.Repository
  409. headGitRepo *git.Repository
  410. )
  411. // In case user included redundant head user name for comparison in same repository,
  412. // no need to check the fork relation.
  413. if !isSameRepo {
  414. var has bool
  415. headRepo, has, err = db.HasForkedRepo(headUser.ID, baseRepo.ID)
  416. if err != nil {
  417. c.Error(err, "get forked repository")
  418. return nil, nil, nil, nil, "", ""
  419. } else if !has {
  420. log.Trace("ParseCompareInfo [base_repo_id: %d]: does not have fork or in same repository", baseRepo.ID)
  421. c.NotFound()
  422. return nil, nil, nil, nil, "", ""
  423. }
  424. headGitRepo, err = git.Open(db.RepoPath(headUser.Name, headRepo.Name))
  425. if err != nil {
  426. c.Error(err, "open repository")
  427. return nil, nil, nil, nil, "", ""
  428. }
  429. } else {
  430. headRepo = c.Repo.Repository
  431. headGitRepo = c.Repo.GitRepo
  432. }
  433. if !c.User.IsWriterOfRepo(headRepo) && !c.User.IsAdmin {
  434. log.Trace("ParseCompareInfo [base_repo_id: %d]: does not have write access or site admin", baseRepo.ID)
  435. c.NotFound()
  436. return nil, nil, nil, nil, "", ""
  437. }
  438. // Check if head branch is valid.
  439. if !headGitRepo.HasBranch(headBranch) {
  440. c.NotFound()
  441. return nil, nil, nil, nil, "", ""
  442. }
  443. headBranches, err := headGitRepo.Branches()
  444. if err != nil {
  445. c.Error(err, "get branches")
  446. return nil, nil, nil, nil, "", ""
  447. }
  448. c.Data["HeadBranches"] = headBranches
  449. baseRepoPath := db.RepoPath(baseRepo.Owner.Name, baseRepo.Name)
  450. meta, err := gitutil.Module.PullRequestMeta(headGitRepo.Path(), baseRepoPath, headBranch, baseBranch)
  451. if err != nil {
  452. if gitutil.IsErrNoMergeBase(err) {
  453. c.Data["IsNoMergeBase"] = true
  454. c.Success(COMPARE_PULL)
  455. } else {
  456. c.Error(err, "get pull request meta")
  457. }
  458. return nil, nil, nil, nil, "", ""
  459. }
  460. c.Data["BeforeCommitID"] = meta.MergeBase
  461. return headUser, headRepo, headGitRepo, meta, baseBranch, headBranch
  462. }
  463. func PrepareCompareDiff(
  464. c *context.Context,
  465. headUser *db.User,
  466. headRepo *db.Repository,
  467. headGitRepo *git.Repository,
  468. meta *gitutil.PullRequestMeta,
  469. headBranch string,
  470. ) bool {
  471. var (
  472. repo = c.Repo.Repository
  473. err error
  474. )
  475. // Get diff information.
  476. c.Data["CommitRepoLink"] = headRepo.Link()
  477. headCommitID, err := headGitRepo.BranchCommitID(headBranch)
  478. if err != nil {
  479. c.Error(err, "get head branch commit ID")
  480. return false
  481. }
  482. c.Data["AfterCommitID"] = headCommitID
  483. if headCommitID == meta.MergeBase {
  484. c.Data["IsNothingToCompare"] = true
  485. return true
  486. }
  487. diff, err := gitutil.RepoDiff(headGitRepo,
  488. headCommitID, conf.Git.MaxDiffFiles, conf.Git.MaxDiffLines, conf.Git.MaxDiffLineChars,
  489. git.DiffOptions{Base: meta.MergeBase},
  490. )
  491. if err != nil {
  492. c.Error(err, "get repository diff")
  493. return false
  494. }
  495. c.Data["Diff"] = diff
  496. c.Data["DiffNotAvailable"] = diff.NumFiles() == 0
  497. headCommit, err := headGitRepo.CatFileCommit(headCommitID)
  498. if err != nil {
  499. c.Error(err, "get head commit")
  500. return false
  501. }
  502. c.Data["Commits"] = db.ValidateCommitsWithEmails(meta.Commits)
  503. c.Data["CommitCount"] = len(meta.Commits)
  504. c.Data["Username"] = headUser.Name
  505. c.Data["Reponame"] = headRepo.Name
  506. c.Data["IsImageFile"] = headCommit.IsImageFile
  507. c.Data["IsImageFileByIndex"] = headCommit.IsImageFileByIndex
  508. headTarget := path.Join(headUser.Name, repo.Name)
  509. c.Data["SourcePath"] = conf.Server.Subpath + "/" + path.Join(headTarget, "src", headCommitID)
  510. c.Data["RawPath"] = conf.Server.Subpath + "/" + path.Join(headTarget, "raw", headCommitID)
  511. c.Data["BeforeSourcePath"] = conf.Server.Subpath + "/" + path.Join(headTarget, "src", meta.MergeBase)
  512. c.Data["BeforeRawPath"] = conf.Server.Subpath + "/" + path.Join(headTarget, "raw", meta.MergeBase)
  513. return false
  514. }
  515. func CompareAndPullRequest(c *context.Context) {
  516. c.Data["Title"] = c.Tr("repo.pulls.compare_changes")
  517. c.Data["PageIsComparePull"] = true
  518. c.Data["IsDiffCompare"] = true
  519. c.Data["RequireHighlightJS"] = true
  520. setTemplateIfExists(c, PULL_REQUEST_TEMPLATE_KEY, PullRequestTemplateCandidates)
  521. renderAttachmentSettings(c)
  522. headUser, headRepo, headGitRepo, prInfo, baseBranch, headBranch := ParseCompareInfo(c)
  523. if c.Written() {
  524. return
  525. }
  526. pr, err := db.GetUnmergedPullRequest(headRepo.ID, c.Repo.Repository.ID, headBranch, baseBranch)
  527. if err != nil {
  528. if !db.IsErrPullRequestNotExist(err) {
  529. c.Error(err, "get unmerged pull request")
  530. return
  531. }
  532. } else {
  533. c.Data["HasPullRequest"] = true
  534. c.Data["PullRequest"] = pr
  535. c.Success(COMPARE_PULL)
  536. return
  537. }
  538. nothingToCompare := PrepareCompareDiff(c, headUser, headRepo, headGitRepo, prInfo, headBranch)
  539. if c.Written() {
  540. return
  541. }
  542. if !nothingToCompare {
  543. // Setup information for new form.
  544. RetrieveRepoMetas(c, c.Repo.Repository)
  545. if c.Written() {
  546. return
  547. }
  548. }
  549. setEditorconfigIfExists(c)
  550. if c.Written() {
  551. return
  552. }
  553. c.Data["IsSplitStyle"] = c.Query("style") == "split"
  554. setTemplateIfExists(c, PULL_REQUEST_TITLE_TEMPLATE_KEY, PullRequestTitleTemplateCandidates)
  555. if c.Data[PULL_REQUEST_TITLE_TEMPLATE_KEY] != nil {
  556. customTitle := c.Data[PULL_REQUEST_TITLE_TEMPLATE_KEY].(string)
  557. r := strings.NewReplacer("{{headBranch}}", headBranch, "{{baseBranch}}", baseBranch)
  558. c.Data["title"] = r.Replace(customTitle)
  559. }
  560. c.Success(COMPARE_PULL)
  561. }
  562. func CompareAndPullRequestPost(c *context.Context, f form.NewIssue) {
  563. c.Data["Title"] = c.Tr("repo.pulls.compare_changes")
  564. c.Data["PageIsComparePull"] = true
  565. c.Data["IsDiffCompare"] = true
  566. c.Data["RequireHighlightJS"] = true
  567. renderAttachmentSettings(c)
  568. var (
  569. repo = c.Repo.Repository
  570. attachments []string
  571. )
  572. headUser, headRepo, headGitRepo, meta, baseBranch, headBranch := ParseCompareInfo(c)
  573. if c.Written() {
  574. return
  575. }
  576. labelIDs, milestoneID, assigneeID := ValidateRepoMetas(c, f)
  577. if c.Written() {
  578. return
  579. }
  580. if conf.Attachment.Enabled {
  581. attachments = f.Files
  582. }
  583. if c.HasError() {
  584. form.Assign(f, c.Data)
  585. // This stage is already stop creating new pull request, so it does not matter if it has
  586. // something to compare or not.
  587. PrepareCompareDiff(c, headUser, headRepo, headGitRepo, meta, headBranch)
  588. if c.Written() {
  589. return
  590. }
  591. c.Success(COMPARE_PULL)
  592. return
  593. }
  594. patch, err := headGitRepo.DiffBinary(meta.MergeBase, headBranch)
  595. if err != nil {
  596. c.Error(err, "get patch")
  597. return
  598. }
  599. pullIssue := &db.Issue{
  600. RepoID: repo.ID,
  601. Index: repo.NextIssueIndex(),
  602. Title: f.Title,
  603. PosterID: c.User.ID,
  604. Poster: c.User,
  605. MilestoneID: milestoneID,
  606. AssigneeID: assigneeID,
  607. IsPull: true,
  608. Content: f.Content,
  609. }
  610. pullRequest := &db.PullRequest{
  611. HeadRepoID: headRepo.ID,
  612. BaseRepoID: repo.ID,
  613. HeadUserName: headUser.Name,
  614. HeadBranch: headBranch,
  615. BaseBranch: baseBranch,
  616. HeadRepo: headRepo,
  617. BaseRepo: repo,
  618. MergeBase: meta.MergeBase,
  619. Type: db.PULL_REQUEST_GOGS,
  620. }
  621. // FIXME: check error in the case two people send pull request at almost same time, give nice error prompt
  622. // instead of 500.
  623. if err := db.NewPullRequest(repo, pullIssue, labelIDs, attachments, pullRequest, patch); err != nil {
  624. c.Error(err, "new pull request")
  625. return
  626. } else if err := pullRequest.PushToBaseRepo(); err != nil {
  627. c.Error(err, "push to base repository")
  628. return
  629. }
  630. log.Trace("Pull request created: %d/%d", repo.ID, pullIssue.ID)
  631. c.Redirect(c.Repo.RepoLink + "/pulls/" + com.ToStr(pullIssue.Index))
  632. }
  633. func parseOwnerAndRepo(c *context.Context) (*db.User, *db.Repository) {
  634. owner, err := db.GetUserByName(c.Params(":username"))
  635. if err != nil {
  636. c.NotFoundOrError(err, "get user by name")
  637. return nil, nil
  638. }
  639. repo, err := db.GetRepositoryByName(owner.ID, c.Params(":reponame"))
  640. if err != nil {
  641. c.NotFoundOrError(err, "get repository by name")
  642. return nil, nil
  643. }
  644. return owner, repo
  645. }
  646. func TriggerTask(c *context.Context) {
  647. pusherID := c.QueryInt64("pusher")
  648. branch := c.Query("branch")
  649. secret := c.Query("secret")
  650. if len(branch) == 0 || len(secret) == 0 || pusherID <= 0 {
  651. c.NotFound()
  652. log.Trace("TriggerTask: branch or secret is empty, or pusher ID is not valid")
  653. return
  654. }
  655. owner, repo := parseOwnerAndRepo(c)
  656. if c.Written() {
  657. return
  658. }
  659. if secret != tool.MD5(owner.Salt) {
  660. c.NotFound()
  661. log.Trace("TriggerTask [%s/%s]: invalid secret", owner.Name, repo.Name)
  662. return
  663. }
  664. pusher, err := db.GetUserByID(pusherID)
  665. if err != nil {
  666. c.NotFoundOrError(err, "get user by ID")
  667. return
  668. }
  669. log.Trace("TriggerTask '%s/%s' by '%s'", repo.Name, branch, pusher.Name)
  670. go db.HookQueue.Add(repo.ID)
  671. go db.AddTestPullRequestTask(pusher, repo.ID, branch, true)
  672. c.Status(202)
  673. }