pull.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793
  1. // Copyright 2015 - Present, The Gogs Authors. All rights reserved.
  2. // Copyright 2018 - Present, Gitote. All rights reserved.
  3. //
  4. // This source code is licensed under the MIT license found in the
  5. // LICENSE file in the root directory of this source tree.
  6. package repo
  7. import (
  8. "container/list"
  9. "gitote/gitote/models"
  10. "gitote/gitote/models/errors"
  11. "gitote/gitote/pkg/context"
  12. "gitote/gitote/pkg/form"
  13. "gitote/gitote/pkg/setting"
  14. "gitote/gitote/pkg/tool"
  15. "path"
  16. "strings"
  17. "gitlab.com/gitote/com"
  18. "gitlab.com/gitote/git-module"
  19. log "gopkg.in/clog.v1"
  20. )
  21. const (
  22. // ForkTPL page template
  23. ForkTPL = "repo/pulls/fork"
  24. // ComparePullTPL page template
  25. ComparePullTPL = "repo/pulls/compare"
  26. // PullCommitsTPL page template
  27. PullCommitsTPL = "repo/pulls/commits"
  28. // PullFilesTPL page template
  29. PullFilesTPL = "repo/pulls/files"
  30. // PullRequestTemplateKeyTPL page template
  31. PullRequestTemplateKeyTPL = "PullRequestTemplate"
  32. )
  33. var (
  34. // PullRequestTemplateCandidates stores PR Templates
  35. PullRequestTemplateCandidates = []string{
  36. "PULL_REQUEST.md",
  37. ".gitote/PULL_REQUEST.md",
  38. ".github/PULL_REQUEST.md",
  39. }
  40. )
  41. func parseBaseRepository(c *context.Context) *models.Repository {
  42. baseRepo, err := models.GetRepositoryByID(c.ParamsInt64(":repoid"))
  43. if err != nil {
  44. c.NotFoundOrServerError("GetRepositoryByID", errors.IsRepoNotExist, err)
  45. return nil
  46. }
  47. if !baseRepo.CanBeForked() || !baseRepo.HasAccess(c.User.ID) {
  48. c.NotFound()
  49. return nil
  50. }
  51. c.Data["repo_name"] = baseRepo.Name
  52. c.Data["description"] = baseRepo.Description
  53. c.Data["IsPrivate"] = baseRepo.IsPrivate
  54. if err = baseRepo.GetOwner(); err != nil {
  55. c.ServerError("GetOwner", err)
  56. return nil
  57. }
  58. c.Data["ForkFrom"] = baseRepo.Owner.Name + "/" + baseRepo.Name
  59. if err := c.User.GetOrganizations(true); err != nil {
  60. c.ServerError("GetOrganizations", err)
  61. return nil
  62. }
  63. c.Data["Orgs"] = c.User.Orgs
  64. return baseRepo
  65. }
  66. // Fork render repository fork page
  67. func Fork(c *context.Context) {
  68. c.Data["Title"] = c.Tr("new_fork")
  69. parseBaseRepository(c)
  70. if c.Written() {
  71. return
  72. }
  73. c.Data["ContextUser"] = c.User
  74. c.Success(ForkTPL)
  75. }
  76. // ForkPost forks a repo
  77. func ForkPost(c *context.Context, f form.CreateRepo) {
  78. c.Data["Title"] = c.Tr("new_fork")
  79. baseRepo := parseBaseRepository(c)
  80. if c.Written() {
  81. return
  82. }
  83. ctxUser := checkContextUser(c, f.UserID)
  84. if c.Written() {
  85. return
  86. }
  87. c.Data["ContextUser"] = ctxUser
  88. if c.HasError() {
  89. c.Success(ForkTPL)
  90. return
  91. }
  92. repo, has, err := models.HasForkedRepo(ctxUser.ID, baseRepo.ID)
  93. if err != nil {
  94. c.ServerError("HasForkedRepo", err)
  95. return
  96. } else if has {
  97. c.Redirect(repo.Link())
  98. return
  99. }
  100. // Check ownership of organization.
  101. if ctxUser.IsOrganization() && !ctxUser.IsOwnedBy(c.User.ID) {
  102. c.Error(403)
  103. return
  104. }
  105. // Cannot fork to same owner
  106. if ctxUser.ID == baseRepo.OwnerID {
  107. c.RenderWithErr(c.Tr("repo.settings.cannot_fork_to_same_owner"), ForkTPL, &f)
  108. return
  109. }
  110. repo, err = models.ForkRepository(c.User, ctxUser, baseRepo, f.RepoName, f.Description)
  111. if err != nil {
  112. c.Data["Err_RepoName"] = true
  113. switch {
  114. case errors.IsReachLimitOfRepo(err):
  115. c.RenderWithErr(c.Tr("repo.form.reach_limit_of_creation", c.User.RepoCreationNum()), ForkTPL, &f)
  116. case models.IsErrRepoAlreadyExist(err):
  117. c.RenderWithErr(c.Tr("repo.settings.new_owner_has_same_repo"), ForkTPL, &f)
  118. case models.IsErrNameReserved(err):
  119. c.RenderWithErr(c.Tr("repo.form.name_reserved", err.(models.ErrNameReserved).Name), ForkTPL, &f)
  120. case models.IsErrNamePatternNotAllowed(err):
  121. c.RenderWithErr(c.Tr("repo.form.name_pattern_not_allowed", err.(models.ErrNamePatternNotAllowed).Pattern), ForkTPL, &f)
  122. default:
  123. c.ServerError("ForkPost", err)
  124. }
  125. return
  126. }
  127. log.Trace("Repository forked from '%s' -> '%s'", baseRepo.FullName(), repo.FullName())
  128. c.Redirect(repo.Link())
  129. }
  130. func checkPullInfo(c *context.Context) *models.Issue {
  131. issue, err := models.GetIssueByIndex(c.Repo.Repository.ID, c.ParamsInt64(":index"))
  132. if err != nil {
  133. c.NotFoundOrServerError("GetIssueByIndex", errors.IsIssueNotExist, err)
  134. return nil
  135. }
  136. c.Data["Title"] = issue.Title
  137. c.Data["Issue"] = issue
  138. if !issue.IsPull {
  139. c.Handle(404, "ViewPullCommits", nil)
  140. return nil
  141. }
  142. if c.IsLogged {
  143. // Update issue-user.
  144. if err = issue.ReadBy(c.User.ID); err != nil {
  145. c.ServerError("ReadBy", err)
  146. return nil
  147. }
  148. }
  149. return issue
  150. }
  151. // PrepareMergedViewPullInfo show meta information for a merged pull request view page
  152. func PrepareMergedViewPullInfo(c *context.Context, issue *models.Issue) {
  153. pull := issue.PullRequest
  154. c.Data["HasMerged"] = true
  155. c.Data["HeadTarget"] = issue.PullRequest.HeadUserName + "/" + pull.HeadBranch
  156. c.Data["BaseTarget"] = c.Repo.Owner.Name + "/" + pull.BaseBranch
  157. var err error
  158. c.Data["NumCommits"], err = c.Repo.GitRepo.CommitsCountBetween(pull.MergeBase, pull.MergedCommitID)
  159. if err != nil {
  160. c.ServerError("Repo.GitRepo.CommitsCountBetween", err)
  161. return
  162. }
  163. c.Data["NumFiles"], err = c.Repo.GitRepo.FilesCountBetween(pull.MergeBase, pull.MergedCommitID)
  164. if err != nil {
  165. c.ServerError("Repo.GitRepo.FilesCountBetween", err)
  166. return
  167. }
  168. }
  169. // PrepareViewPullInfo show meta information for a pull request preview page
  170. func PrepareViewPullInfo(c *context.Context, issue *models.Issue) *git.PullRequestInfo {
  171. repo := c.Repo.Repository
  172. pull := issue.PullRequest
  173. c.Data["HeadTarget"] = pull.HeadUserName + "/" + pull.HeadBranch
  174. c.Data["BaseTarget"] = c.Repo.Owner.Name + "/" + pull.BaseBranch
  175. var (
  176. headGitRepo *git.Repository
  177. err error
  178. )
  179. if pull.HeadRepo != nil {
  180. headGitRepo, err = git.OpenRepository(pull.HeadRepo.RepoPath())
  181. if err != nil {
  182. c.ServerError("OpenRepository", err)
  183. return nil
  184. }
  185. }
  186. if pull.HeadRepo == nil || !headGitRepo.IsBranchExist(pull.HeadBranch) {
  187. c.Data["IsPullReuqestBroken"] = true
  188. c.Data["HeadTarget"] = "deleted"
  189. c.Data["NumCommits"] = 0
  190. c.Data["NumFiles"] = 0
  191. return nil
  192. }
  193. prInfo, err := headGitRepo.GetPullRequestInfo(models.RepoPath(repo.Owner.Name, repo.Name),
  194. pull.BaseBranch, pull.HeadBranch)
  195. if err != nil {
  196. if strings.Contains(err.Error(), "fatal: Not a valid object name") {
  197. c.Data["IsPullReuqestBroken"] = true
  198. c.Data["BaseTarget"] = "deleted"
  199. c.Data["NumCommits"] = 0
  200. c.Data["NumFiles"] = 0
  201. return nil
  202. }
  203. c.ServerError("GetPullRequestInfo", err)
  204. return nil
  205. }
  206. c.Data["NumCommits"] = prInfo.Commits.Len()
  207. c.Data["NumFiles"] = prInfo.NumFiles
  208. return prInfo
  209. }
  210. // ViewPullCommits show commits for a pull request
  211. func ViewPullCommits(c *context.Context) {
  212. c.Data["PageIsPullList"] = true
  213. c.Data["PageIsPullCommits"] = true
  214. issue := checkPullInfo(c)
  215. if c.Written() {
  216. return
  217. }
  218. pull := issue.PullRequest
  219. if pull.HeadRepo != nil {
  220. c.Data["Username"] = pull.HeadUserName
  221. c.Data["Reponame"] = pull.HeadRepo.Name
  222. }
  223. var commits *list.List
  224. if pull.HasMerged {
  225. PrepareMergedViewPullInfo(c, issue)
  226. if c.Written() {
  227. return
  228. }
  229. startCommit, err := c.Repo.GitRepo.GetCommit(pull.MergeBase)
  230. if err != nil {
  231. c.ServerError("Repo.GitRepo.GetCommit", err)
  232. return
  233. }
  234. endCommit, err := c.Repo.GitRepo.GetCommit(pull.MergedCommitID)
  235. if err != nil {
  236. c.ServerError("Repo.GitRepo.GetCommit", err)
  237. return
  238. }
  239. commits, err = c.Repo.GitRepo.CommitsBetween(endCommit, startCommit)
  240. if err != nil {
  241. c.ServerError("Repo.GitRepo.CommitsBetween", err)
  242. return
  243. }
  244. } else {
  245. prInfo := PrepareViewPullInfo(c, issue)
  246. if c.Written() {
  247. return
  248. } else if prInfo == nil {
  249. c.NotFound()
  250. return
  251. }
  252. commits = prInfo.Commits
  253. }
  254. commits = models.ValidateCommitsWithEmails(commits)
  255. c.Data["Commits"] = commits
  256. c.Data["CommitsCount"] = commits.Len()
  257. c.Success(PullCommitsTPL)
  258. }
  259. // ViewPullFiles render pull request changed files list page
  260. func ViewPullFiles(c *context.Context) {
  261. c.Data["PageIsPullList"] = true
  262. c.Data["PageIsPullFiles"] = true
  263. issue := checkPullInfo(c)
  264. if c.Written() {
  265. return
  266. }
  267. pull := issue.PullRequest
  268. var (
  269. diffRepoPath string
  270. startCommitID string
  271. endCommitID string
  272. gitRepo *git.Repository
  273. )
  274. if pull.HasMerged {
  275. PrepareMergedViewPullInfo(c, issue)
  276. if c.Written() {
  277. return
  278. }
  279. diffRepoPath = c.Repo.GitRepo.Path
  280. startCommitID = pull.MergeBase
  281. endCommitID = pull.MergedCommitID
  282. gitRepo = c.Repo.GitRepo
  283. } else {
  284. prInfo := PrepareViewPullInfo(c, issue)
  285. if c.Written() {
  286. return
  287. } else if prInfo == nil {
  288. c.Handle(404, "ViewPullFiles", nil)
  289. return
  290. }
  291. headRepoPath := models.RepoPath(pull.HeadUserName, pull.HeadRepo.Name)
  292. headGitRepo, err := git.OpenRepository(headRepoPath)
  293. if err != nil {
  294. c.ServerError("OpenRepository", err)
  295. return
  296. }
  297. headCommitID, err := headGitRepo.GetBranchCommitID(pull.HeadBranch)
  298. if err != nil {
  299. c.ServerError("GetBranchCommitID", err)
  300. return
  301. }
  302. diffRepoPath = headRepoPath
  303. startCommitID = prInfo.MergeBase
  304. endCommitID = headCommitID
  305. gitRepo = headGitRepo
  306. }
  307. diff, err := models.GetDiffRange(diffRepoPath,
  308. startCommitID, endCommitID, setting.Git.MaxGitDiffLines,
  309. setting.Git.MaxGitDiffLineCharacters, setting.Git.MaxGitDiffFiles)
  310. if err != nil {
  311. c.ServerError("GetDiffRange", err)
  312. return
  313. }
  314. c.Data["Diff"] = diff
  315. c.Data["DiffNotAvailable"] = diff.NumFiles() == 0
  316. commit, err := gitRepo.GetCommit(endCommitID)
  317. if err != nil {
  318. c.ServerError("GetCommit", err)
  319. return
  320. }
  321. setEditorconfigIfExists(c)
  322. if c.Written() {
  323. return
  324. }
  325. c.Data["IsSplitStyle"] = c.Query("style") == "split"
  326. c.Data["IsImageFile"] = commit.IsImageFile
  327. // It is possible head repo has been deleted for merged pull requests
  328. if pull.HeadRepo != nil {
  329. c.Data["Username"] = pull.HeadUserName
  330. c.Data["Reponame"] = pull.HeadRepo.Name
  331. headTarget := path.Join(pull.HeadUserName, pull.HeadRepo.Name)
  332. c.Data["SourcePath"] = setting.AppSubURL + "/" + path.Join(headTarget, "src", endCommitID)
  333. c.Data["BeforeSourcePath"] = setting.AppSubURL + "/" + path.Join(headTarget, "src", startCommitID)
  334. c.Data["RawPath"] = setting.AppSubURL + "/" + path.Join(headTarget, "raw", endCommitID)
  335. }
  336. c.Data["RequireHighlightJS"] = true
  337. c.Success(PullFilesTPL)
  338. }
  339. // MergePullRequest response for merging pull request
  340. func MergePullRequest(c *context.Context) {
  341. issue := checkPullInfo(c)
  342. if c.Written() {
  343. return
  344. }
  345. if issue.IsClosed {
  346. c.NotFound()
  347. return
  348. }
  349. pr, err := models.GetPullRequestByIssueID(issue.ID)
  350. if err != nil {
  351. c.NotFoundOrServerError("GetPullRequestByIssueID", models.IsErrPullRequestNotExist, err)
  352. return
  353. }
  354. if !pr.CanAutoMerge() || pr.HasMerged {
  355. c.NotFound()
  356. return
  357. }
  358. pr.Issue = issue
  359. pr.Issue.Repo = c.Repo.Repository
  360. if err = pr.Merge(c.User, c.Repo.GitRepo, models.MergeStyle(c.Query("merge_style")), c.Query("commit_description")); err != nil {
  361. c.ServerError("Merge", err)
  362. return
  363. }
  364. log.Trace("Pull request merged: %d", pr.ID)
  365. c.Redirect(c.Repo.RepoLink + "/pulls/" + com.ToStr(pr.Index))
  366. }
  367. // ParseCompareInfo parse compare info between two commit for preparing pull request
  368. func ParseCompareInfo(c *context.Context) (*models.User, *models.Repository, *git.Repository, *git.PullRequestInfo, string, string) {
  369. baseRepo := c.Repo.Repository
  370. // Get compared branches information
  371. // format: <base branch>...[<head repo>:]<head branch>
  372. // base<-head: master...head:feature
  373. // same repo: master...feature
  374. infos := strings.Split(c.Params("*"), "...")
  375. if len(infos) != 2 {
  376. log.Trace("ParseCompareInfo[%d]: not enough compared branches information %s", baseRepo.ID, infos)
  377. c.NotFound()
  378. return nil, nil, nil, nil, "", ""
  379. }
  380. baseBranch := infos[0]
  381. c.Data["BaseBranch"] = baseBranch
  382. var (
  383. headUser *models.User
  384. headBranch string
  385. isSameRepo bool
  386. err error
  387. )
  388. // If there is no head repository, it means pull request between same repository.
  389. headInfos := strings.Split(infos[1], ":")
  390. if len(headInfos) == 1 {
  391. isSameRepo = true
  392. headUser = c.Repo.Owner
  393. headBranch = headInfos[0]
  394. } else if len(headInfos) == 2 {
  395. headUser, err = models.GetUserByName(headInfos[0])
  396. if err != nil {
  397. c.NotFoundOrServerError("GetUserByName", errors.IsUserNotExist, err)
  398. return nil, nil, nil, nil, "", ""
  399. }
  400. headBranch = headInfos[1]
  401. isSameRepo = headUser.ID == baseRepo.OwnerID
  402. } else {
  403. c.NotFound()
  404. return nil, nil, nil, nil, "", ""
  405. }
  406. c.Data["HeadUser"] = headUser
  407. c.Data["HeadBranch"] = headBranch
  408. c.Repo.PullRequest.SameRepo = isSameRepo
  409. // Check if base branch is valid.
  410. if !c.Repo.GitRepo.IsBranchExist(baseBranch) {
  411. c.NotFound()
  412. return nil, nil, nil, nil, "", ""
  413. }
  414. var (
  415. headRepo *models.Repository
  416. headGitRepo *git.Repository
  417. )
  418. // In case user included redundant head user name for comparison in same repository,
  419. // no need to check the fork relation.
  420. if !isSameRepo {
  421. var has bool
  422. headRepo, has, err = models.HasForkedRepo(headUser.ID, baseRepo.ID)
  423. if err != nil {
  424. c.ServerError("HasForkedRepo", err)
  425. return nil, nil, nil, nil, "", ""
  426. } else if !has {
  427. log.Trace("ParseCompareInfo [base_repo_id: %d]: does not have fork or in same repository", baseRepo.ID)
  428. c.NotFound()
  429. return nil, nil, nil, nil, "", ""
  430. }
  431. headGitRepo, err = git.OpenRepository(models.RepoPath(headUser.Name, headRepo.Name))
  432. if err != nil {
  433. c.ServerError("OpenRepository", err)
  434. return nil, nil, nil, nil, "", ""
  435. }
  436. } else {
  437. headRepo = c.Repo.Repository
  438. headGitRepo = c.Repo.GitRepo
  439. }
  440. if !c.User.IsWriterOfRepo(headRepo) && !c.User.IsAdmin {
  441. log.Trace("ParseCompareInfo [base_repo_id: %d]: does not have write access or site admin", baseRepo.ID)
  442. c.NotFound()
  443. return nil, nil, nil, nil, "", ""
  444. }
  445. // Check if head branch is valid.
  446. if !headGitRepo.IsBranchExist(headBranch) {
  447. c.NotFound()
  448. return nil, nil, nil, nil, "", ""
  449. }
  450. headBranches, err := headGitRepo.GetBranches()
  451. if err != nil {
  452. c.ServerError("GetBranches", err)
  453. return nil, nil, nil, nil, "", ""
  454. }
  455. c.Data["HeadBranches"] = headBranches
  456. prInfo, err := headGitRepo.GetPullRequestInfo(models.RepoPath(baseRepo.Owner.Name, baseRepo.Name), baseBranch, headBranch)
  457. if err != nil {
  458. if git.IsErrNoMergeBase(err) {
  459. c.Data["IsNoMergeBase"] = true
  460. c.Success(ComparePullTPL)
  461. } else {
  462. c.ServerError("GetPullRequestInfo", err)
  463. }
  464. return nil, nil, nil, nil, "", ""
  465. }
  466. c.Data["BeforeCommitID"] = prInfo.MergeBase
  467. return headUser, headRepo, headGitRepo, prInfo, baseBranch, headBranch
  468. }
  469. // PrepareCompareDiff render pull request preview diff page
  470. func PrepareCompareDiff(
  471. c *context.Context,
  472. headUser *models.User,
  473. headRepo *models.Repository,
  474. headGitRepo *git.Repository,
  475. prInfo *git.PullRequestInfo,
  476. baseBranch, headBranch string) bool {
  477. var (
  478. repo = c.Repo.Repository
  479. err error
  480. )
  481. // Get diff information.
  482. c.Data["CommitRepoLink"] = headRepo.Link()
  483. headCommitID, err := headGitRepo.GetBranchCommitID(headBranch)
  484. if err != nil {
  485. c.ServerError("GetBranchCommitID", err)
  486. return false
  487. }
  488. c.Data["AfterCommitID"] = headCommitID
  489. if headCommitID == prInfo.MergeBase {
  490. c.Data["IsNothingToCompare"] = true
  491. return true
  492. }
  493. diff, err := models.GetDiffRange(models.RepoPath(headUser.Name, headRepo.Name),
  494. prInfo.MergeBase, headCommitID, setting.Git.MaxGitDiffLines,
  495. setting.Git.MaxGitDiffLineCharacters, setting.Git.MaxGitDiffFiles)
  496. if err != nil {
  497. c.ServerError("GetDiffRange", err)
  498. return false
  499. }
  500. c.Data["Diff"] = diff
  501. c.Data["DiffNotAvailable"] = diff.NumFiles() == 0
  502. headCommit, err := headGitRepo.GetCommit(headCommitID)
  503. if err != nil {
  504. c.ServerError("GetCommit", err)
  505. return false
  506. }
  507. prInfo.Commits = models.ValidateCommitsWithEmails(prInfo.Commits)
  508. c.Data["Commits"] = prInfo.Commits
  509. c.Data["CommitCount"] = prInfo.Commits.Len()
  510. c.Data["Username"] = headUser.Name
  511. c.Data["Reponame"] = headRepo.Name
  512. c.Data["IsImageFile"] = headCommit.IsImageFile
  513. headTarget := path.Join(headUser.Name, repo.Name)
  514. c.Data["SourcePath"] = setting.AppSubURL + "/" + path.Join(headTarget, "src", headCommitID)
  515. c.Data["BeforeSourcePath"] = setting.AppSubURL + "/" + path.Join(headTarget, "src", prInfo.MergeBase)
  516. c.Data["RawPath"] = setting.AppSubURL + "/" + path.Join(headTarget, "raw", headCommitID)
  517. return false
  518. }
  519. // CompareAndPullRequest render pull request preview page
  520. func CompareAndPullRequest(c *context.Context) {
  521. c.Data["Title"] = c.Tr("repo.pulls.compare_changes")
  522. c.Data["PageIsComparePull"] = true
  523. c.Data["IsDiffCompare"] = true
  524. c.Data["RequireHighlightJS"] = true
  525. setTemplateIfExists(c, PullRequestTemplateKeyTPL, PullRequestTemplateCandidates)
  526. renderAttachmentSettings(c)
  527. headUser, headRepo, headGitRepo, prInfo, baseBranch, headBranch := ParseCompareInfo(c)
  528. if c.Written() {
  529. return
  530. }
  531. pr, err := models.GetUnmergedPullRequest(headRepo.ID, c.Repo.Repository.ID, headBranch, baseBranch)
  532. if err != nil {
  533. if !models.IsErrPullRequestNotExist(err) {
  534. c.ServerError("GetUnmergedPullRequest", err)
  535. return
  536. }
  537. } else {
  538. c.Data["HasPullRequest"] = true
  539. c.Data["PullRequest"] = pr
  540. c.Success(ComparePullTPL)
  541. return
  542. }
  543. nothingToCompare := PrepareCompareDiff(c, headUser, headRepo, headGitRepo, prInfo, baseBranch, headBranch)
  544. if c.Written() {
  545. return
  546. }
  547. if !nothingToCompare {
  548. // Setup information for new form.
  549. RetrieveRepoMetas(c, c.Repo.Repository)
  550. if c.Written() {
  551. return
  552. }
  553. }
  554. setEditorconfigIfExists(c)
  555. if c.Written() {
  556. return
  557. }
  558. c.Data["IsSplitStyle"] = c.Query("style") == "split"
  559. c.Success(ComparePullTPL)
  560. }
  561. // CompareAndPullRequestPost compares branches/forks and create a new pull request
  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, prInfo, 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 setting.AttachmentEnabled {
  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, prInfo, baseBranch, headBranch)
  588. if c.Written() {
  589. return
  590. }
  591. c.Success(ComparePullTPL)
  592. return
  593. }
  594. patch, err := headGitRepo.GetPatch(prInfo.MergeBase, headBranch)
  595. if err != nil {
  596. c.ServerError("GetPatch", err)
  597. return
  598. }
  599. pullIssue := &models.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 := &models.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: prInfo.MergeBase,
  619. Type: models.PullRequestGitote,
  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 := models.NewPullRequest(repo, pullIssue, labelIDs, attachments, pullRequest, patch); err != nil {
  624. c.ServerError("NewPullRequest", err)
  625. return
  626. } else if err := pullRequest.PushToBaseRepo(); err != nil {
  627. c.ServerError("PushToBaseRepo", err)
  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) (*models.User, *models.Repository) {
  634. owner, err := models.GetUserByName(c.Params(":username"))
  635. if err != nil {
  636. c.NotFoundOrServerError("GetUserByName", errors.IsUserNotExist, err)
  637. return nil, nil
  638. }
  639. repo, err := models.GetRepositoryByName(owner.ID, c.Params(":reponame"))
  640. if err != nil {
  641. c.NotFoundOrServerError("GetRepositoryByName", errors.IsRepoNotExist, err)
  642. return nil, nil
  643. }
  644. return owner, repo
  645. }
  646. // TriggerTask response for a trigger task request
  647. func TriggerTask(c *context.Context) {
  648. pusherID := c.QueryInt64("pusher")
  649. branch := c.Query("branch")
  650. secret := c.Query("secret")
  651. if len(branch) == 0 || len(secret) == 0 || pusherID <= 0 {
  652. c.Error(404)
  653. log.Trace("TriggerTask: branch or secret is empty, or pusher ID is not valid")
  654. return
  655. }
  656. owner, repo := parseOwnerAndRepo(c)
  657. if c.Written() {
  658. return
  659. }
  660. if secret != tool.MD5(owner.Salt) {
  661. c.Error(404)
  662. log.Trace("TriggerTask [%s/%s]: invalid secret", owner.Name, repo.Name)
  663. return
  664. }
  665. pusher, err := models.GetUserByID(pusherID)
  666. if err != nil {
  667. c.NotFoundOrServerError("GetUserByID", errors.IsUserNotExist, err)
  668. return
  669. }
  670. log.Trace("TriggerTask '%s/%s' by '%s'", repo.Name, branch, pusher.Name)
  671. go models.HookQueue.Add(repo.ID)
  672. go models.AddTestPullRequestTask(pusher, repo.ID, branch, true)
  673. c.Status(202)
  674. }