pull.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786
  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. "container/list"
  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/context"
  13. "gogs.io/gogs/internal/db"
  14. "gogs.io/gogs/internal/db/errors"
  15. "gogs.io/gogs/internal/form"
  16. "gogs.io/gogs/internal/setting"
  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.NotFoundOrServerError("GetRepositoryByID", errors.IsRepoNotExist, err)
  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.ServerError("GetOwner", err)
  54. return nil
  55. }
  56. c.Data["ForkFrom"] = baseRepo.Owner.Name + "/" + baseRepo.Name
  57. if err := c.User.GetOrganizations(true); err != nil {
  58. c.ServerError("GetOrganizations", err)
  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.ServerError("HasForkedRepo", err)
  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.Error(403)
  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 errors.IsReachLimitOfRepo(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.ServerError("ForkPost", err)
  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.NotFoundOrServerError("GetIssueByIndex", errors.IsIssueNotExist, err)
  130. return nil
  131. }
  132. c.Data["Title"] = issue.Title
  133. c.Data["Issue"] = issue
  134. if !issue.IsPull {
  135. c.Handle(404, "ViewPullCommits", nil)
  136. return nil
  137. }
  138. if c.IsLogged {
  139. // Update issue-user.
  140. if err = issue.ReadBy(c.User.ID); err != nil {
  141. c.ServerError("ReadBy", err)
  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.CommitsCountBetween(pull.MergeBase, pull.MergedCommitID)
  154. if err != nil {
  155. c.ServerError("Repo.GitRepo.CommitsCountBetween", err)
  156. return
  157. }
  158. c.Data["NumFiles"], err = c.Repo.GitRepo.FilesCountBetween(pull.MergeBase, pull.MergedCommitID)
  159. if err != nil {
  160. c.ServerError("Repo.GitRepo.FilesCountBetween", err)
  161. return
  162. }
  163. }
  164. func PrepareViewPullInfo(c *context.Context, issue *db.Issue) *git.PullRequestInfo {
  165. repo := c.Repo.Repository
  166. pull := issue.PullRequest
  167. c.Data["HeadTarget"] = pull.HeadUserName + "/" + pull.HeadBranch
  168. c.Data["BaseTarget"] = c.Repo.Owner.Name + "/" + pull.BaseBranch
  169. var (
  170. headGitRepo *git.Repository
  171. err error
  172. )
  173. if pull.HeadRepo != nil {
  174. headGitRepo, err = git.OpenRepository(pull.HeadRepo.RepoPath())
  175. if err != nil {
  176. c.ServerError("OpenRepository", err)
  177. return nil
  178. }
  179. }
  180. if pull.HeadRepo == nil || !headGitRepo.IsBranchExist(pull.HeadBranch) {
  181. c.Data["IsPullReuqestBroken"] = true
  182. c.Data["HeadTarget"] = "deleted"
  183. c.Data["NumCommits"] = 0
  184. c.Data["NumFiles"] = 0
  185. return nil
  186. }
  187. prInfo, err := headGitRepo.GetPullRequestInfo(db.RepoPath(repo.Owner.Name, repo.Name),
  188. pull.BaseBranch, pull.HeadBranch)
  189. if err != nil {
  190. if strings.Contains(err.Error(), "fatal: Not a valid object name") {
  191. c.Data["IsPullReuqestBroken"] = true
  192. c.Data["BaseTarget"] = "deleted"
  193. c.Data["NumCommits"] = 0
  194. c.Data["NumFiles"] = 0
  195. return nil
  196. }
  197. c.ServerError("GetPullRequestInfo", err)
  198. return nil
  199. }
  200. c.Data["NumCommits"] = prInfo.Commits.Len()
  201. c.Data["NumFiles"] = prInfo.NumFiles
  202. return prInfo
  203. }
  204. func ViewPullCommits(c *context.Context) {
  205. c.Data["PageIsPullList"] = true
  206. c.Data["PageIsPullCommits"] = true
  207. issue := checkPullInfo(c)
  208. if c.Written() {
  209. return
  210. }
  211. pull := issue.PullRequest
  212. if pull.HeadRepo != nil {
  213. c.Data["Username"] = pull.HeadUserName
  214. c.Data["Reponame"] = pull.HeadRepo.Name
  215. }
  216. var commits *list.List
  217. if pull.HasMerged {
  218. PrepareMergedViewPullInfo(c, issue)
  219. if c.Written() {
  220. return
  221. }
  222. startCommit, err := c.Repo.GitRepo.GetCommit(pull.MergeBase)
  223. if err != nil {
  224. c.ServerError("Repo.GitRepo.GetCommit", err)
  225. return
  226. }
  227. endCommit, err := c.Repo.GitRepo.GetCommit(pull.MergedCommitID)
  228. if err != nil {
  229. c.ServerError("Repo.GitRepo.GetCommit", err)
  230. return
  231. }
  232. commits, err = c.Repo.GitRepo.CommitsBetween(endCommit, startCommit)
  233. if err != nil {
  234. c.ServerError("Repo.GitRepo.CommitsBetween", err)
  235. return
  236. }
  237. } else {
  238. prInfo := PrepareViewPullInfo(c, issue)
  239. if c.Written() {
  240. return
  241. } else if prInfo == nil {
  242. c.NotFound()
  243. return
  244. }
  245. commits = prInfo.Commits
  246. }
  247. commits = db.ValidateCommitsWithEmails(commits)
  248. c.Data["Commits"] = commits
  249. c.Data["CommitsCount"] = commits.Len()
  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. diffRepoPath string
  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. diffRepoPath = c.Repo.GitRepo.Path
  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.Handle(404, "ViewPullFiles", nil)
  281. return
  282. }
  283. headRepoPath := db.RepoPath(pull.HeadUserName, pull.HeadRepo.Name)
  284. headGitRepo, err := git.OpenRepository(headRepoPath)
  285. if err != nil {
  286. c.ServerError("OpenRepository", err)
  287. return
  288. }
  289. headCommitID, err := headGitRepo.GetBranchCommitID(pull.HeadBranch)
  290. if err != nil {
  291. c.ServerError("GetBranchCommitID", err)
  292. return
  293. }
  294. diffRepoPath = headRepoPath
  295. startCommitID = prInfo.MergeBase
  296. endCommitID = headCommitID
  297. gitRepo = headGitRepo
  298. }
  299. diff, err := db.GetDiffRange(diffRepoPath,
  300. startCommitID, endCommitID, setting.Git.MaxGitDiffLines,
  301. setting.Git.MaxGitDiffLineCharacters, setting.Git.MaxGitDiffFiles)
  302. if err != nil {
  303. c.ServerError("GetDiffRange", err)
  304. return
  305. }
  306. c.Data["Diff"] = diff
  307. c.Data["DiffNotAvailable"] = diff.NumFiles() == 0
  308. commit, err := gitRepo.GetCommit(endCommitID)
  309. if err != nil {
  310. c.ServerError("GetCommit", err)
  311. return
  312. }
  313. setEditorconfigIfExists(c)
  314. if c.Written() {
  315. return
  316. }
  317. c.Data["IsSplitStyle"] = c.Query("style") == "split"
  318. c.Data["IsImageFile"] = commit.IsImageFile
  319. // It is possible head repo has been deleted for merged pull requests
  320. if pull.HeadRepo != nil {
  321. c.Data["Username"] = pull.HeadUserName
  322. c.Data["Reponame"] = pull.HeadRepo.Name
  323. headTarget := path.Join(pull.HeadUserName, pull.HeadRepo.Name)
  324. c.Data["SourcePath"] = setting.AppSubURL + "/" + path.Join(headTarget, "src", endCommitID)
  325. c.Data["BeforeSourcePath"] = setting.AppSubURL + "/" + path.Join(headTarget, "src", startCommitID)
  326. c.Data["RawPath"] = setting.AppSubURL + "/" + path.Join(headTarget, "raw", endCommitID)
  327. }
  328. c.Data["RequireHighlightJS"] = true
  329. c.Success(PULL_FILES)
  330. }
  331. func MergePullRequest(c *context.Context) {
  332. issue := checkPullInfo(c)
  333. if c.Written() {
  334. return
  335. }
  336. if issue.IsClosed {
  337. c.NotFound()
  338. return
  339. }
  340. pr, err := db.GetPullRequestByIssueID(issue.ID)
  341. if err != nil {
  342. c.NotFoundOrServerError("GetPullRequestByIssueID", db.IsErrPullRequestNotExist, err)
  343. return
  344. }
  345. if !pr.CanAutoMerge() || pr.HasMerged {
  346. c.NotFound()
  347. return
  348. }
  349. pr.Issue = issue
  350. pr.Issue.Repo = c.Repo.Repository
  351. if err = pr.Merge(c.User, c.Repo.GitRepo, db.MergeStyle(c.Query("merge_style")), c.Query("commit_description")); err != nil {
  352. c.ServerError("Merge", err)
  353. return
  354. }
  355. log.Trace("Pull request merged: %d", pr.ID)
  356. c.Redirect(c.Repo.RepoLink + "/pulls/" + com.ToStr(pr.Index))
  357. }
  358. func ParseCompareInfo(c *context.Context) (*db.User, *db.Repository, *git.Repository, *git.PullRequestInfo, string, string) {
  359. baseRepo := c.Repo.Repository
  360. // Get compared branches information
  361. // format: <base branch>...[<head repo>:]<head branch>
  362. // base<-head: master...head:feature
  363. // same repo: master...feature
  364. infos := strings.Split(c.Params("*"), "...")
  365. if len(infos) != 2 {
  366. log.Trace("ParseCompareInfo[%d]: not enough compared branches information %s", baseRepo.ID, infos)
  367. c.NotFound()
  368. return nil, nil, nil, nil, "", ""
  369. }
  370. baseBranch := infos[0]
  371. c.Data["BaseBranch"] = baseBranch
  372. var (
  373. headUser *db.User
  374. headBranch string
  375. isSameRepo bool
  376. err error
  377. )
  378. // If there is no head repository, it means pull request between same repository.
  379. headInfos := strings.Split(infos[1], ":")
  380. if len(headInfos) == 1 {
  381. isSameRepo = true
  382. headUser = c.Repo.Owner
  383. headBranch = headInfos[0]
  384. } else if len(headInfos) == 2 {
  385. headUser, err = db.GetUserByName(headInfos[0])
  386. if err != nil {
  387. c.NotFoundOrServerError("GetUserByName", errors.IsUserNotExist, err)
  388. return nil, nil, nil, nil, "", ""
  389. }
  390. headBranch = headInfos[1]
  391. isSameRepo = headUser.ID == baseRepo.OwnerID
  392. } else {
  393. c.NotFound()
  394. return nil, nil, nil, nil, "", ""
  395. }
  396. c.Data["HeadUser"] = headUser
  397. c.Data["HeadBranch"] = headBranch
  398. c.Repo.PullRequest.SameRepo = isSameRepo
  399. // Check if base branch is valid.
  400. if !c.Repo.GitRepo.IsBranchExist(baseBranch) {
  401. c.NotFound()
  402. return nil, nil, nil, nil, "", ""
  403. }
  404. var (
  405. headRepo *db.Repository
  406. headGitRepo *git.Repository
  407. )
  408. // In case user included redundant head user name for comparison in same repository,
  409. // no need to check the fork relation.
  410. if !isSameRepo {
  411. var has bool
  412. headRepo, has, err = db.HasForkedRepo(headUser.ID, baseRepo.ID)
  413. if err != nil {
  414. c.ServerError("HasForkedRepo", err)
  415. return nil, nil, nil, nil, "", ""
  416. } else if !has {
  417. log.Trace("ParseCompareInfo [base_repo_id: %d]: does not have fork or in same repository", baseRepo.ID)
  418. c.NotFound()
  419. return nil, nil, nil, nil, "", ""
  420. }
  421. headGitRepo, err = git.OpenRepository(db.RepoPath(headUser.Name, headRepo.Name))
  422. if err != nil {
  423. c.ServerError("OpenRepository", err)
  424. return nil, nil, nil, nil, "", ""
  425. }
  426. } else {
  427. headRepo = c.Repo.Repository
  428. headGitRepo = c.Repo.GitRepo
  429. }
  430. if !c.User.IsWriterOfRepo(headRepo) && !c.User.IsAdmin {
  431. log.Trace("ParseCompareInfo [base_repo_id: %d]: does not have write access or site admin", baseRepo.ID)
  432. c.NotFound()
  433. return nil, nil, nil, nil, "", ""
  434. }
  435. // Check if head branch is valid.
  436. if !headGitRepo.IsBranchExist(headBranch) {
  437. c.NotFound()
  438. return nil, nil, nil, nil, "", ""
  439. }
  440. headBranches, err := headGitRepo.GetBranches()
  441. if err != nil {
  442. c.ServerError("GetBranches", err)
  443. return nil, nil, nil, nil, "", ""
  444. }
  445. c.Data["HeadBranches"] = headBranches
  446. prInfo, err := headGitRepo.GetPullRequestInfo(db.RepoPath(baseRepo.Owner.Name, baseRepo.Name), baseBranch, headBranch)
  447. if err != nil {
  448. if git.IsErrNoMergeBase(err) {
  449. c.Data["IsNoMergeBase"] = true
  450. c.Success(COMPARE_PULL)
  451. } else {
  452. c.ServerError("GetPullRequestInfo", err)
  453. }
  454. return nil, nil, nil, nil, "", ""
  455. }
  456. c.Data["BeforeCommitID"] = prInfo.MergeBase
  457. return headUser, headRepo, headGitRepo, prInfo, baseBranch, headBranch
  458. }
  459. func PrepareCompareDiff(
  460. c *context.Context,
  461. headUser *db.User,
  462. headRepo *db.Repository,
  463. headGitRepo *git.Repository,
  464. prInfo *git.PullRequestInfo,
  465. baseBranch, headBranch string) bool {
  466. var (
  467. repo = c.Repo.Repository
  468. err error
  469. )
  470. // Get diff information.
  471. c.Data["CommitRepoLink"] = headRepo.Link()
  472. headCommitID, err := headGitRepo.GetBranchCommitID(headBranch)
  473. if err != nil {
  474. c.ServerError("GetBranchCommitID", err)
  475. return false
  476. }
  477. c.Data["AfterCommitID"] = headCommitID
  478. if headCommitID == prInfo.MergeBase {
  479. c.Data["IsNothingToCompare"] = true
  480. return true
  481. }
  482. diff, err := db.GetDiffRange(db.RepoPath(headUser.Name, headRepo.Name),
  483. prInfo.MergeBase, headCommitID, setting.Git.MaxGitDiffLines,
  484. setting.Git.MaxGitDiffLineCharacters, setting.Git.MaxGitDiffFiles)
  485. if err != nil {
  486. c.ServerError("GetDiffRange", err)
  487. return false
  488. }
  489. c.Data["Diff"] = diff
  490. c.Data["DiffNotAvailable"] = diff.NumFiles() == 0
  491. headCommit, err := headGitRepo.GetCommit(headCommitID)
  492. if err != nil {
  493. c.ServerError("GetCommit", err)
  494. return false
  495. }
  496. prInfo.Commits = db.ValidateCommitsWithEmails(prInfo.Commits)
  497. c.Data["Commits"] = prInfo.Commits
  498. c.Data["CommitCount"] = prInfo.Commits.Len()
  499. c.Data["Username"] = headUser.Name
  500. c.Data["Reponame"] = headRepo.Name
  501. c.Data["IsImageFile"] = headCommit.IsImageFile
  502. headTarget := path.Join(headUser.Name, repo.Name)
  503. c.Data["SourcePath"] = setting.AppSubURL + "/" + path.Join(headTarget, "src", headCommitID)
  504. c.Data["BeforeSourcePath"] = setting.AppSubURL + "/" + path.Join(headTarget, "src", prInfo.MergeBase)
  505. c.Data["RawPath"] = setting.AppSubURL + "/" + path.Join(headTarget, "raw", headCommitID)
  506. return false
  507. }
  508. func CompareAndPullRequest(c *context.Context) {
  509. c.Data["Title"] = c.Tr("repo.pulls.compare_changes")
  510. c.Data["PageIsComparePull"] = true
  511. c.Data["IsDiffCompare"] = true
  512. c.Data["RequireHighlightJS"] = true
  513. setTemplateIfExists(c, PULL_REQUEST_TEMPLATE_KEY, PullRequestTemplateCandidates)
  514. renderAttachmentSettings(c)
  515. headUser, headRepo, headGitRepo, prInfo, baseBranch, headBranch := ParseCompareInfo(c)
  516. if c.Written() {
  517. return
  518. }
  519. pr, err := db.GetUnmergedPullRequest(headRepo.ID, c.Repo.Repository.ID, headBranch, baseBranch)
  520. if err != nil {
  521. if !db.IsErrPullRequestNotExist(err) {
  522. c.ServerError("GetUnmergedPullRequest", err)
  523. return
  524. }
  525. } else {
  526. c.Data["HasPullRequest"] = true
  527. c.Data["PullRequest"] = pr
  528. c.Success(COMPARE_PULL)
  529. return
  530. }
  531. nothingToCompare := PrepareCompareDiff(c, headUser, headRepo, headGitRepo, prInfo, baseBranch, headBranch)
  532. if c.Written() {
  533. return
  534. }
  535. if !nothingToCompare {
  536. // Setup information for new form.
  537. RetrieveRepoMetas(c, c.Repo.Repository)
  538. if c.Written() {
  539. return
  540. }
  541. }
  542. setEditorconfigIfExists(c)
  543. if c.Written() {
  544. return
  545. }
  546. c.Data["IsSplitStyle"] = c.Query("style") == "split"
  547. setTemplateIfExists(c, PULL_REQUEST_TITLE_TEMPLATE_KEY, PullRequestTitleTemplateCandidates)
  548. if c.Data[PULL_REQUEST_TITLE_TEMPLATE_KEY] != nil {
  549. customTitle := c.Data[PULL_REQUEST_TITLE_TEMPLATE_KEY].(string)
  550. r := strings.NewReplacer("{{headBranch}}", headBranch, "{{baseBranch}}", baseBranch)
  551. c.Data["title"] = r.Replace(customTitle)
  552. }
  553. c.Success(COMPARE_PULL)
  554. }
  555. func CompareAndPullRequestPost(c *context.Context, f form.NewIssue) {
  556. c.Data["Title"] = c.Tr("repo.pulls.compare_changes")
  557. c.Data["PageIsComparePull"] = true
  558. c.Data["IsDiffCompare"] = true
  559. c.Data["RequireHighlightJS"] = true
  560. renderAttachmentSettings(c)
  561. var (
  562. repo = c.Repo.Repository
  563. attachments []string
  564. )
  565. headUser, headRepo, headGitRepo, prInfo, baseBranch, headBranch := ParseCompareInfo(c)
  566. if c.Written() {
  567. return
  568. }
  569. labelIDs, milestoneID, assigneeID := ValidateRepoMetas(c, f)
  570. if c.Written() {
  571. return
  572. }
  573. if setting.AttachmentEnabled {
  574. attachments = f.Files
  575. }
  576. if c.HasError() {
  577. form.Assign(f, c.Data)
  578. // This stage is already stop creating new pull request, so it does not matter if it has
  579. // something to compare or not.
  580. PrepareCompareDiff(c, headUser, headRepo, headGitRepo, prInfo, baseBranch, headBranch)
  581. if c.Written() {
  582. return
  583. }
  584. c.Success(COMPARE_PULL)
  585. return
  586. }
  587. patch, err := headGitRepo.GetPatch(prInfo.MergeBase, headBranch)
  588. if err != nil {
  589. c.ServerError("GetPatch", err)
  590. return
  591. }
  592. pullIssue := &db.Issue{
  593. RepoID: repo.ID,
  594. Index: repo.NextIssueIndex(),
  595. Title: f.Title,
  596. PosterID: c.User.ID,
  597. Poster: c.User,
  598. MilestoneID: milestoneID,
  599. AssigneeID: assigneeID,
  600. IsPull: true,
  601. Content: f.Content,
  602. }
  603. pullRequest := &db.PullRequest{
  604. HeadRepoID: headRepo.ID,
  605. BaseRepoID: repo.ID,
  606. HeadUserName: headUser.Name,
  607. HeadBranch: headBranch,
  608. BaseBranch: baseBranch,
  609. HeadRepo: headRepo,
  610. BaseRepo: repo,
  611. MergeBase: prInfo.MergeBase,
  612. Type: db.PULL_REQUEST_GOGS,
  613. }
  614. // FIXME: check error in the case two people send pull request at almost same time, give nice error prompt
  615. // instead of 500.
  616. if err := db.NewPullRequest(repo, pullIssue, labelIDs, attachments, pullRequest, patch); err != nil {
  617. c.ServerError("NewPullRequest", err)
  618. return
  619. } else if err := pullRequest.PushToBaseRepo(); err != nil {
  620. c.ServerError("PushToBaseRepo", err)
  621. return
  622. }
  623. log.Trace("Pull request created: %d/%d", repo.ID, pullIssue.ID)
  624. c.Redirect(c.Repo.RepoLink + "/pulls/" + com.ToStr(pullIssue.Index))
  625. }
  626. func parseOwnerAndRepo(c *context.Context) (*db.User, *db.Repository) {
  627. owner, err := db.GetUserByName(c.Params(":username"))
  628. if err != nil {
  629. c.NotFoundOrServerError("GetUserByName", errors.IsUserNotExist, err)
  630. return nil, nil
  631. }
  632. repo, err := db.GetRepositoryByName(owner.ID, c.Params(":reponame"))
  633. if err != nil {
  634. c.NotFoundOrServerError("GetRepositoryByName", errors.IsRepoNotExist, err)
  635. return nil, nil
  636. }
  637. return owner, repo
  638. }
  639. func TriggerTask(c *context.Context) {
  640. pusherID := c.QueryInt64("pusher")
  641. branch := c.Query("branch")
  642. secret := c.Query("secret")
  643. if len(branch) == 0 || len(secret) == 0 || pusherID <= 0 {
  644. c.Error(404)
  645. log.Trace("TriggerTask: branch or secret is empty, or pusher ID is not valid")
  646. return
  647. }
  648. owner, repo := parseOwnerAndRepo(c)
  649. if c.Written() {
  650. return
  651. }
  652. if secret != tool.MD5(owner.Salt) {
  653. c.Error(404)
  654. log.Trace("TriggerTask [%s/%s]: invalid secret", owner.Name, repo.Name)
  655. return
  656. }
  657. pusher, err := db.GetUserByID(pusherID)
  658. if err != nil {
  659. c.NotFoundOrServerError("GetUserByID", errors.IsUserNotExist, err)
  660. return
  661. }
  662. log.Trace("TriggerTask '%s/%s' by '%s'", repo.Name, branch, pusher.Name)
  663. go db.HookQueue.Add(repo.ID)
  664. go db.AddTestPullRequestTask(pusher, repo.ID, branch, true)
  665. c.Status(202)
  666. }