You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

pull.go 28KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056
  1. // Copyright 2018 The Gitea Authors.
  2. // Copyright 2014 The Gogs Authors.
  3. // All rights reserved.
  4. // Use of this source code is governed by a MIT-style
  5. // license that can be found in the LICENSE file.
  6. package repo
  7. import (
  8. "container/list"
  9. "fmt"
  10. "path"
  11. "strings"
  12. "code.gitea.io/git"
  13. "code.gitea.io/gitea/models"
  14. "code.gitea.io/gitea/modules/auth"
  15. "code.gitea.io/gitea/modules/base"
  16. "code.gitea.io/gitea/modules/context"
  17. "code.gitea.io/gitea/modules/log"
  18. "code.gitea.io/gitea/modules/notification"
  19. "code.gitea.io/gitea/modules/setting"
  20. "github.com/Unknwon/com"
  21. )
  22. const (
  23. tplFork base.TplName = "repo/pulls/fork"
  24. tplComparePull base.TplName = "repo/pulls/compare"
  25. tplPullCommits base.TplName = "repo/pulls/commits"
  26. tplPullFiles base.TplName = "repo/pulls/files"
  27. pullRequestTemplateKey = "PullRequestTemplate"
  28. )
  29. var (
  30. pullRequestTemplateCandidates = []string{
  31. "PULL_REQUEST_TEMPLATE.md",
  32. "pull_request_template.md",
  33. ".gitea/PULL_REQUEST_TEMPLATE.md",
  34. ".gitea/pull_request_template.md",
  35. ".github/PULL_REQUEST_TEMPLATE.md",
  36. ".github/pull_request_template.md",
  37. }
  38. )
  39. func getForkRepository(ctx *context.Context) *models.Repository {
  40. forkRepo, err := models.GetRepositoryByID(ctx.ParamsInt64(":repoid"))
  41. if err != nil {
  42. if models.IsErrRepoNotExist(err) {
  43. ctx.Handle(404, "GetRepositoryByID", nil)
  44. } else {
  45. ctx.Handle(500, "GetRepositoryByID", err)
  46. }
  47. return nil
  48. }
  49. if !forkRepo.CanBeForked() || !forkRepo.HasAccess(ctx.User) {
  50. ctx.Handle(404, "getForkRepository", nil)
  51. return nil
  52. }
  53. ctx.Data["repo_name"] = forkRepo.Name
  54. ctx.Data["description"] = forkRepo.Description
  55. ctx.Data["IsPrivate"] = forkRepo.IsPrivate
  56. canForkToUser := forkRepo.OwnerID != ctx.User.ID && !ctx.User.HasForkedRepo(forkRepo.ID)
  57. if err = forkRepo.GetOwner(); err != nil {
  58. ctx.Handle(500, "GetOwner", err)
  59. return nil
  60. }
  61. ctx.Data["ForkFrom"] = forkRepo.Owner.Name + "/" + forkRepo.Name
  62. ctx.Data["ForkFromOwnerID"] = forkRepo.Owner.ID
  63. if err := ctx.User.GetOwnedOrganizations(); err != nil {
  64. ctx.Handle(500, "GetOwnedOrganizations", err)
  65. return nil
  66. }
  67. var orgs []*models.User
  68. for _, org := range ctx.User.OwnedOrgs {
  69. if forkRepo.OwnerID != org.ID && !org.HasForkedRepo(forkRepo.ID) {
  70. orgs = append(orgs, org)
  71. }
  72. }
  73. var traverseParentRepo = forkRepo
  74. for {
  75. if ctx.User.ID == traverseParentRepo.OwnerID {
  76. canForkToUser = false
  77. } else {
  78. for i, org := range orgs {
  79. if org.ID == traverseParentRepo.OwnerID {
  80. orgs = append(orgs[:i], orgs[i+1:]...)
  81. break
  82. }
  83. }
  84. }
  85. if !traverseParentRepo.IsFork {
  86. break
  87. }
  88. traverseParentRepo, err = models.GetRepositoryByID(traverseParentRepo.ForkID)
  89. if err != nil {
  90. ctx.Handle(500, "GetRepositoryByID", err)
  91. return nil
  92. }
  93. }
  94. ctx.Data["CanForkToUser"] = canForkToUser
  95. ctx.Data["Orgs"] = orgs
  96. if canForkToUser {
  97. ctx.Data["ContextUser"] = ctx.User
  98. } else if len(orgs) > 0 {
  99. ctx.Data["ContextUser"] = orgs[0]
  100. }
  101. return forkRepo
  102. }
  103. // Fork render repository fork page
  104. func Fork(ctx *context.Context) {
  105. ctx.Data["Title"] = ctx.Tr("new_fork")
  106. getForkRepository(ctx)
  107. if ctx.Written() {
  108. return
  109. }
  110. ctx.HTML(200, tplFork)
  111. }
  112. // ForkPost response for forking a repository
  113. func ForkPost(ctx *context.Context, form auth.CreateRepoForm) {
  114. ctx.Data["Title"] = ctx.Tr("new_fork")
  115. ctxUser := checkContextUser(ctx, form.UID)
  116. if ctx.Written() {
  117. return
  118. }
  119. forkRepo := getForkRepository(ctx)
  120. if ctx.Written() {
  121. return
  122. }
  123. ctx.Data["ContextUser"] = ctxUser
  124. if ctx.HasError() {
  125. ctx.HTML(200, tplFork)
  126. return
  127. }
  128. var err error
  129. var traverseParentRepo = forkRepo
  130. for {
  131. if ctxUser.ID == traverseParentRepo.OwnerID {
  132. ctx.RenderWithErr(ctx.Tr("repo.settings.new_owner_has_same_repo"), tplFork, &form)
  133. return
  134. }
  135. repo, has := models.HasForkedRepo(ctxUser.ID, traverseParentRepo.ID)
  136. if has {
  137. ctx.Redirect(setting.AppSubURL + "/" + ctxUser.Name + "/" + repo.Name)
  138. return
  139. }
  140. if !traverseParentRepo.IsFork {
  141. break
  142. }
  143. traverseParentRepo, err = models.GetRepositoryByID(traverseParentRepo.ForkID)
  144. if err != nil {
  145. ctx.Handle(500, "GetRepositoryByID", err)
  146. return
  147. }
  148. }
  149. // Check ownership of organization.
  150. if ctxUser.IsOrganization() {
  151. isOwner, err := ctxUser.IsOwnedBy(ctx.User.ID)
  152. if err != nil {
  153. ctx.Handle(500, "IsOwnedBy", err)
  154. return
  155. } else if !isOwner {
  156. ctx.Error(403)
  157. return
  158. }
  159. }
  160. repo, err := models.ForkRepository(ctx.User, ctxUser, forkRepo, form.RepoName, form.Description)
  161. if err != nil {
  162. ctx.Data["Err_RepoName"] = true
  163. switch {
  164. case models.IsErrRepoAlreadyExist(err):
  165. ctx.RenderWithErr(ctx.Tr("repo.settings.new_owner_has_same_repo"), tplFork, &form)
  166. case models.IsErrNameReserved(err):
  167. ctx.RenderWithErr(ctx.Tr("repo.form.name_reserved", err.(models.ErrNameReserved).Name), tplFork, &form)
  168. case models.IsErrNamePatternNotAllowed(err):
  169. ctx.RenderWithErr(ctx.Tr("repo.form.name_pattern_not_allowed", err.(models.ErrNamePatternNotAllowed).Pattern), tplFork, &form)
  170. default:
  171. ctx.Handle(500, "ForkPost", err)
  172. }
  173. return
  174. }
  175. log.Trace("Repository forked[%d]: %s/%s", forkRepo.ID, ctxUser.Name, repo.Name)
  176. ctx.Redirect(setting.AppSubURL + "/" + ctxUser.Name + "/" + repo.Name)
  177. }
  178. func checkPullInfo(ctx *context.Context) *models.Issue {
  179. issue, err := models.GetIssueByIndex(ctx.Repo.Repository.ID, ctx.ParamsInt64(":index"))
  180. if err != nil {
  181. if models.IsErrIssueNotExist(err) {
  182. ctx.Handle(404, "GetIssueByIndex", err)
  183. } else {
  184. ctx.Handle(500, "GetIssueByIndex", err)
  185. }
  186. return nil
  187. }
  188. ctx.Data["Title"] = fmt.Sprintf("#%d - %s", issue.Index, issue.Title)
  189. ctx.Data["Issue"] = issue
  190. if !issue.IsPull {
  191. ctx.Handle(404, "ViewPullCommits", nil)
  192. return nil
  193. }
  194. if err = issue.PullRequest.GetHeadRepo(); err != nil {
  195. ctx.Handle(500, "GetHeadRepo", err)
  196. return nil
  197. }
  198. if ctx.IsSigned {
  199. // Update issue-user.
  200. if err = issue.ReadBy(ctx.User.ID); err != nil {
  201. ctx.Handle(500, "ReadBy", err)
  202. return nil
  203. }
  204. }
  205. return issue
  206. }
  207. func setMergeTarget(ctx *context.Context, pull *models.PullRequest) {
  208. if ctx.Repo.Owner.Name == pull.HeadUserName {
  209. ctx.Data["HeadTarget"] = pull.HeadBranch
  210. } else if pull.HeadRepo == nil {
  211. ctx.Data["HeadTarget"] = pull.HeadUserName + ":" + pull.HeadBranch
  212. } else {
  213. ctx.Data["HeadTarget"] = pull.HeadUserName + "/" + pull.HeadRepo.Name + ":" + pull.HeadBranch
  214. }
  215. ctx.Data["BaseTarget"] = pull.BaseBranch
  216. }
  217. // PrepareMergedViewPullInfo show meta information for a merged pull request view page
  218. func PrepareMergedViewPullInfo(ctx *context.Context, issue *models.Issue) {
  219. pull := issue.PullRequest
  220. var err error
  221. if err = pull.GetHeadRepo(); err != nil {
  222. ctx.Handle(500, "GetHeadRepo", err)
  223. return
  224. }
  225. setMergeTarget(ctx, pull)
  226. ctx.Data["HasMerged"] = true
  227. mergedCommit, err := ctx.Repo.GitRepo.GetCommit(pull.MergedCommitID)
  228. if err != nil {
  229. ctx.Handle(500, "GetCommit", err)
  230. return
  231. }
  232. // the ID of the last commit in the PR (not including the merge commit)
  233. endCommitID, err := mergedCommit.ParentID(mergedCommit.ParentCount() - 1)
  234. if err != nil {
  235. ctx.Handle(500, "ParentID", err)
  236. return
  237. }
  238. ctx.Data["NumCommits"], err = ctx.Repo.GitRepo.CommitsCountBetween(pull.MergeBase, endCommitID.String())
  239. if err != nil {
  240. ctx.Handle(500, "Repo.GitRepo.CommitsCountBetween", err)
  241. return
  242. }
  243. ctx.Data["NumFiles"], err = ctx.Repo.GitRepo.FilesCountBetween(pull.MergeBase, endCommitID.String())
  244. if err != nil {
  245. ctx.Handle(500, "Repo.GitRepo.FilesCountBetween", err)
  246. return
  247. }
  248. }
  249. // PrepareViewPullInfo show meta information for a pull request preview page
  250. func PrepareViewPullInfo(ctx *context.Context, issue *models.Issue) *git.PullRequestInfo {
  251. repo := ctx.Repo.Repository
  252. pull := issue.PullRequest
  253. var err error
  254. if err = pull.GetHeadRepo(); err != nil {
  255. ctx.Handle(500, "GetHeadRepo", err)
  256. return nil
  257. }
  258. setMergeTarget(ctx, pull)
  259. var headGitRepo *git.Repository
  260. if pull.HeadRepo != nil {
  261. headGitRepo, err = git.OpenRepository(pull.HeadRepo.RepoPath())
  262. if err != nil {
  263. ctx.Handle(500, "OpenRepository", err)
  264. return nil
  265. }
  266. }
  267. if pull.HeadRepo == nil || !headGitRepo.IsBranchExist(pull.HeadBranch) {
  268. ctx.Data["IsPullReuqestBroken"] = true
  269. ctx.Data["HeadTarget"] = "deleted"
  270. ctx.Data["NumCommits"] = 0
  271. ctx.Data["NumFiles"] = 0
  272. return nil
  273. }
  274. prInfo, err := headGitRepo.GetPullRequestInfo(models.RepoPath(repo.Owner.Name, repo.Name),
  275. pull.BaseBranch, pull.HeadBranch)
  276. if err != nil {
  277. if strings.Contains(err.Error(), "fatal: Not a valid object name") {
  278. ctx.Data["IsPullReuqestBroken"] = true
  279. ctx.Data["BaseTarget"] = "deleted"
  280. ctx.Data["NumCommits"] = 0
  281. ctx.Data["NumFiles"] = 0
  282. return nil
  283. }
  284. ctx.Handle(500, "GetPullRequestInfo", err)
  285. return nil
  286. }
  287. ctx.Data["NumCommits"] = prInfo.Commits.Len()
  288. ctx.Data["NumFiles"] = prInfo.NumFiles
  289. return prInfo
  290. }
  291. // ViewPullCommits show commits for a pull request
  292. func ViewPullCommits(ctx *context.Context) {
  293. ctx.Data["PageIsPullList"] = true
  294. ctx.Data["PageIsPullCommits"] = true
  295. issue := checkPullInfo(ctx)
  296. if ctx.Written() {
  297. return
  298. }
  299. pull := issue.PullRequest
  300. var commits *list.List
  301. if pull.HasMerged {
  302. PrepareMergedViewPullInfo(ctx, issue)
  303. if ctx.Written() {
  304. return
  305. }
  306. ctx.Data["Username"] = ctx.Repo.Owner.Name
  307. ctx.Data["Reponame"] = ctx.Repo.Repository.Name
  308. mergedCommit, err := ctx.Repo.GitRepo.GetCommit(pull.MergedCommitID)
  309. if err != nil {
  310. ctx.Handle(500, "Repo.GitRepo.GetCommit", err)
  311. return
  312. }
  313. endCommitID, err := mergedCommit.ParentID(mergedCommit.ParentCount() - 1)
  314. if err != nil {
  315. ctx.Handle(500, "ParentID", err)
  316. return
  317. }
  318. commits, err = ctx.Repo.GitRepo.CommitsBetweenIDs(endCommitID.String(), pull.MergeBase)
  319. if err != nil {
  320. ctx.Handle(500, "Repo.GitRepo.CommitsBetweenIDs", err)
  321. return
  322. }
  323. } else {
  324. prInfo := PrepareViewPullInfo(ctx, issue)
  325. if ctx.Written() {
  326. return
  327. } else if prInfo == nil {
  328. ctx.Handle(404, "ViewPullCommits", nil)
  329. return
  330. }
  331. ctx.Data["Username"] = pull.HeadUserName
  332. ctx.Data["Reponame"] = pull.HeadRepo.Name
  333. commits = prInfo.Commits
  334. }
  335. commits = models.ValidateCommitsWithEmails(commits)
  336. commits = models.ParseCommitsWithSignature(commits)
  337. commits = models.ParseCommitsWithStatus(commits, ctx.Repo.Repository)
  338. ctx.Data["Commits"] = commits
  339. ctx.Data["CommitCount"] = commits.Len()
  340. ctx.HTML(200, tplPullCommits)
  341. }
  342. // ViewPullFiles render pull request changed files list page
  343. func ViewPullFiles(ctx *context.Context) {
  344. ctx.Data["PageIsPullList"] = true
  345. ctx.Data["PageIsPullFiles"] = true
  346. issue := checkPullInfo(ctx)
  347. if ctx.Written() {
  348. return
  349. }
  350. pull := issue.PullRequest
  351. var (
  352. diffRepoPath string
  353. startCommitID string
  354. endCommitID string
  355. gitRepo *git.Repository
  356. )
  357. var headTarget string
  358. if pull.HasMerged {
  359. PrepareMergedViewPullInfo(ctx, issue)
  360. if ctx.Written() {
  361. return
  362. }
  363. diffRepoPath = ctx.Repo.GitRepo.Path
  364. startCommitID = pull.MergeBase
  365. mergedCommit, err := ctx.Repo.GitRepo.GetCommit(pull.MergedCommitID)
  366. if err != nil {
  367. ctx.Handle(500, "GetCommit", err)
  368. return
  369. }
  370. endCommitSha, err := mergedCommit.ParentID(mergedCommit.ParentCount() - 1)
  371. if err != nil {
  372. ctx.Handle(500, "ParentID", err)
  373. return
  374. }
  375. endCommitID = endCommitSha.String()
  376. gitRepo = ctx.Repo.GitRepo
  377. headTarget = path.Join(ctx.Repo.Owner.Name, ctx.Repo.Repository.Name)
  378. ctx.Data["Username"] = ctx.Repo.Owner.Name
  379. ctx.Data["Reponame"] = ctx.Repo.Repository.Name
  380. } else {
  381. prInfo := PrepareViewPullInfo(ctx, issue)
  382. if ctx.Written() {
  383. return
  384. } else if prInfo == nil {
  385. ctx.Handle(404, "ViewPullFiles", nil)
  386. return
  387. }
  388. headRepoPath := models.RepoPath(pull.HeadUserName, pull.HeadRepo.Name)
  389. headGitRepo, err := git.OpenRepository(headRepoPath)
  390. if err != nil {
  391. ctx.Handle(500, "OpenRepository", err)
  392. return
  393. }
  394. headCommitID, err := headGitRepo.GetBranchCommitID(pull.HeadBranch)
  395. if err != nil {
  396. ctx.Handle(500, "GetBranchCommitID", err)
  397. return
  398. }
  399. diffRepoPath = headRepoPath
  400. startCommitID = prInfo.MergeBase
  401. endCommitID = headCommitID
  402. gitRepo = headGitRepo
  403. headTarget = path.Join(pull.HeadUserName, pull.HeadRepo.Name)
  404. ctx.Data["Username"] = pull.HeadUserName
  405. ctx.Data["Reponame"] = pull.HeadRepo.Name
  406. }
  407. diff, err := models.GetDiffRange(diffRepoPath,
  408. startCommitID, endCommitID, setting.Git.MaxGitDiffLines,
  409. setting.Git.MaxGitDiffLineCharacters, setting.Git.MaxGitDiffFiles)
  410. if err != nil {
  411. ctx.Handle(500, "GetDiffRange", err)
  412. return
  413. }
  414. ctx.Data["Diff"] = diff
  415. ctx.Data["DiffNotAvailable"] = diff.NumFiles() == 0
  416. commit, err := gitRepo.GetCommit(endCommitID)
  417. if err != nil {
  418. ctx.Handle(500, "GetCommit", err)
  419. return
  420. }
  421. ctx.Data["IsImageFile"] = commit.IsImageFile
  422. ctx.Data["SourcePath"] = setting.AppSubURL + "/" + path.Join(headTarget, "src", "commit", endCommitID)
  423. ctx.Data["BeforeSourcePath"] = setting.AppSubURL + "/" + path.Join(headTarget, "src", "commit", startCommitID)
  424. ctx.Data["RawPath"] = setting.AppSubURL + "/" + path.Join(headTarget, "raw", "commit", endCommitID)
  425. ctx.Data["RequireHighlightJS"] = true
  426. ctx.HTML(200, tplPullFiles)
  427. }
  428. // MergePullRequest response for merging pull request
  429. func MergePullRequest(ctx *context.Context, form auth.MergePullRequestForm) {
  430. issue := checkPullInfo(ctx)
  431. if ctx.Written() {
  432. return
  433. }
  434. if issue.IsClosed {
  435. ctx.Handle(404, "MergePullRequest", nil)
  436. return
  437. }
  438. pr, err := models.GetPullRequestByIssueID(issue.ID)
  439. if err != nil {
  440. if models.IsErrPullRequestNotExist(err) {
  441. ctx.Handle(404, "GetPullRequestByIssueID", nil)
  442. } else {
  443. ctx.Handle(500, "GetPullRequestByIssueID", err)
  444. }
  445. return
  446. }
  447. pr.Issue = issue
  448. if !pr.CanAutoMerge() || pr.HasMerged {
  449. ctx.Handle(404, "MergePullRequest", nil)
  450. return
  451. }
  452. if ctx.HasError() {
  453. ctx.Flash.Error(ctx.Data["ErrorMsg"].(string))
  454. ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(pr.Index))
  455. return
  456. }
  457. message := strings.TrimSpace(form.MergeTitleField)
  458. if len(message) == 0 {
  459. if models.MergeStyle(form.Do) == models.MergeStyleMerge {
  460. message = pr.GetDefaultMergeMessage()
  461. }
  462. if models.MergeStyle(form.Do) == models.MergeStyleSquash {
  463. message = pr.GetDefaultSquashMessage()
  464. }
  465. }
  466. form.MergeMessageField = strings.TrimSpace(form.MergeMessageField)
  467. if len(form.MergeMessageField) > 0 {
  468. message += "\n\n" + form.MergeMessageField
  469. }
  470. pr.Issue = issue
  471. pr.Issue.Repo = ctx.Repo.Repository
  472. if err = pr.Merge(ctx.User, ctx.Repo.GitRepo, models.MergeStyle(form.Do), message); err != nil {
  473. if models.IsErrInvalidMergeStyle(err) {
  474. ctx.Flash.Error(ctx.Tr("repo.pulls.invalid_merge_option"))
  475. ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(pr.Index))
  476. return
  477. }
  478. ctx.Handle(500, "Merge", err)
  479. return
  480. }
  481. notification.Service.NotifyIssue(pr.Issue, ctx.User.ID)
  482. log.Trace("Pull request merged: %d", pr.ID)
  483. ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(pr.Index))
  484. }
  485. // ParseCompareInfo parse compare info between two commit for preparing pull request
  486. func ParseCompareInfo(ctx *context.Context) (*models.User, *models.Repository, *git.Repository, *git.PullRequestInfo, string, string) {
  487. baseRepo := ctx.Repo.Repository
  488. // Get compared branches information
  489. // format: <base branch>...[<head repo>:]<head branch>
  490. // base<-head: master...head:feature
  491. // same repo: master...feature
  492. infos := strings.Split(ctx.Params("*"), "...")
  493. if len(infos) != 2 {
  494. log.Trace("ParseCompareInfo[%d]: not enough compared branches information %s", baseRepo.ID, infos)
  495. ctx.Handle(404, "CompareAndPullRequest", nil)
  496. return nil, nil, nil, nil, "", ""
  497. }
  498. baseBranch := infos[0]
  499. ctx.Data["BaseBranch"] = baseBranch
  500. var (
  501. headUser *models.User
  502. headBranch string
  503. isSameRepo bool
  504. err error
  505. )
  506. // If there is no head repository, it means pull request between same repository.
  507. headInfos := strings.Split(infos[1], ":")
  508. if len(headInfos) == 1 {
  509. isSameRepo = true
  510. headUser = ctx.Repo.Owner
  511. headBranch = headInfos[0]
  512. } else if len(headInfos) == 2 {
  513. headUser, err = models.GetUserByName(headInfos[0])
  514. if err != nil {
  515. if models.IsErrUserNotExist(err) {
  516. ctx.Handle(404, "GetUserByName", nil)
  517. } else {
  518. ctx.Handle(500, "GetUserByName", err)
  519. }
  520. return nil, nil, nil, nil, "", ""
  521. }
  522. headBranch = headInfos[1]
  523. isSameRepo = headUser.ID == ctx.Repo.Owner.ID
  524. } else {
  525. ctx.Handle(404, "CompareAndPullRequest", nil)
  526. return nil, nil, nil, nil, "", ""
  527. }
  528. ctx.Data["HeadUser"] = headUser
  529. ctx.Data["HeadBranch"] = headBranch
  530. ctx.Repo.PullRequest.SameRepo = isSameRepo
  531. // Check if base branch is valid.
  532. if !ctx.Repo.GitRepo.IsBranchExist(baseBranch) {
  533. ctx.Handle(404, "IsBranchExist", nil)
  534. return nil, nil, nil, nil, "", ""
  535. }
  536. // Check if current user has fork of repository or in the same repository.
  537. headRepo, has := models.HasForkedRepo(headUser.ID, baseRepo.ID)
  538. if !has && !isSameRepo {
  539. log.Trace("ParseCompareInfo[%d]: does not have fork or in same repository", baseRepo.ID)
  540. ctx.Handle(404, "ParseCompareInfo", nil)
  541. return nil, nil, nil, nil, "", ""
  542. }
  543. var headGitRepo *git.Repository
  544. if isSameRepo {
  545. headRepo = ctx.Repo.Repository
  546. headGitRepo = ctx.Repo.GitRepo
  547. } else {
  548. headGitRepo, err = git.OpenRepository(models.RepoPath(headUser.Name, headRepo.Name))
  549. if err != nil {
  550. ctx.Handle(500, "OpenRepository", err)
  551. return nil, nil, nil, nil, "", ""
  552. }
  553. }
  554. if !ctx.User.IsWriterOfRepo(headRepo) && !ctx.User.IsAdmin {
  555. log.Trace("ParseCompareInfo[%d]: does not have write access or site admin", baseRepo.ID)
  556. ctx.Handle(404, "ParseCompareInfo", nil)
  557. return nil, nil, nil, nil, "", ""
  558. }
  559. // Check if head branch is valid.
  560. if !headGitRepo.IsBranchExist(headBranch) {
  561. ctx.Handle(404, "IsBranchExist", nil)
  562. return nil, nil, nil, nil, "", ""
  563. }
  564. headBranches, err := headGitRepo.GetBranches()
  565. if err != nil {
  566. ctx.Handle(500, "GetBranches", err)
  567. return nil, nil, nil, nil, "", ""
  568. }
  569. ctx.Data["HeadBranches"] = headBranches
  570. prInfo, err := headGitRepo.GetPullRequestInfo(models.RepoPath(baseRepo.Owner.Name, baseRepo.Name), baseBranch, headBranch)
  571. if err != nil {
  572. ctx.Handle(500, "GetPullRequestInfo", err)
  573. return nil, nil, nil, nil, "", ""
  574. }
  575. ctx.Data["BeforeCommitID"] = prInfo.MergeBase
  576. return headUser, headRepo, headGitRepo, prInfo, baseBranch, headBranch
  577. }
  578. // PrepareCompareDiff render pull request preview diff page
  579. func PrepareCompareDiff(
  580. ctx *context.Context,
  581. headUser *models.User,
  582. headRepo *models.Repository,
  583. headGitRepo *git.Repository,
  584. prInfo *git.PullRequestInfo,
  585. baseBranch, headBranch string) bool {
  586. var (
  587. repo = ctx.Repo.Repository
  588. err error
  589. )
  590. // Get diff information.
  591. ctx.Data["CommitRepoLink"] = headRepo.Link()
  592. headCommitID, err := headGitRepo.GetBranchCommitID(headBranch)
  593. if err != nil {
  594. ctx.Handle(500, "GetBranchCommitID", err)
  595. return false
  596. }
  597. ctx.Data["AfterCommitID"] = headCommitID
  598. if headCommitID == prInfo.MergeBase {
  599. ctx.Data["IsNothingToCompare"] = true
  600. return true
  601. }
  602. diff, err := models.GetDiffRange(models.RepoPath(headUser.Name, headRepo.Name),
  603. prInfo.MergeBase, headCommitID, setting.Git.MaxGitDiffLines,
  604. setting.Git.MaxGitDiffLineCharacters, setting.Git.MaxGitDiffFiles)
  605. if err != nil {
  606. ctx.Handle(500, "GetDiffRange", err)
  607. return false
  608. }
  609. ctx.Data["Diff"] = diff
  610. ctx.Data["DiffNotAvailable"] = diff.NumFiles() == 0
  611. headCommit, err := headGitRepo.GetCommit(headCommitID)
  612. if err != nil {
  613. ctx.Handle(500, "GetCommit", err)
  614. return false
  615. }
  616. prInfo.Commits = models.ValidateCommitsWithEmails(prInfo.Commits)
  617. prInfo.Commits = models.ParseCommitsWithSignature(prInfo.Commits)
  618. prInfo.Commits = models.ParseCommitsWithStatus(prInfo.Commits, headRepo)
  619. ctx.Data["Commits"] = prInfo.Commits
  620. ctx.Data["CommitCount"] = prInfo.Commits.Len()
  621. ctx.Data["Username"] = headUser.Name
  622. ctx.Data["Reponame"] = headRepo.Name
  623. ctx.Data["IsImageFile"] = headCommit.IsImageFile
  624. headTarget := path.Join(headUser.Name, repo.Name)
  625. ctx.Data["SourcePath"] = setting.AppSubURL + "/" + path.Join(headTarget, "src", "commit", headCommitID)
  626. ctx.Data["BeforeSourcePath"] = setting.AppSubURL + "/" + path.Join(headTarget, "src", "commit", prInfo.MergeBase)
  627. ctx.Data["RawPath"] = setting.AppSubURL + "/" + path.Join(headTarget, "raw", "commit", headCommitID)
  628. return false
  629. }
  630. // CompareAndPullRequest render pull request preview page
  631. func CompareAndPullRequest(ctx *context.Context) {
  632. ctx.Data["Title"] = ctx.Tr("repo.pulls.compare_changes")
  633. ctx.Data["PageIsComparePull"] = true
  634. ctx.Data["IsDiffCompare"] = true
  635. ctx.Data["RequireHighlightJS"] = true
  636. ctx.Data["RequireTribute"] = true
  637. setTemplateIfExists(ctx, pullRequestTemplateKey, pullRequestTemplateCandidates)
  638. renderAttachmentSettings(ctx)
  639. headUser, headRepo, headGitRepo, prInfo, baseBranch, headBranch := ParseCompareInfo(ctx)
  640. if ctx.Written() {
  641. return
  642. }
  643. pr, err := models.GetUnmergedPullRequest(headRepo.ID, ctx.Repo.Repository.ID, headBranch, baseBranch)
  644. if err != nil {
  645. if !models.IsErrPullRequestNotExist(err) {
  646. ctx.Handle(500, "GetUnmergedPullRequest", err)
  647. return
  648. }
  649. } else {
  650. ctx.Data["HasPullRequest"] = true
  651. ctx.Data["PullRequest"] = pr
  652. ctx.HTML(200, tplComparePull)
  653. return
  654. }
  655. nothingToCompare := PrepareCompareDiff(ctx, headUser, headRepo, headGitRepo, prInfo, baseBranch, headBranch)
  656. if ctx.Written() {
  657. return
  658. }
  659. if !nothingToCompare {
  660. // Setup information for new form.
  661. RetrieveRepoMetas(ctx, ctx.Repo.Repository)
  662. if ctx.Written() {
  663. return
  664. }
  665. }
  666. ctx.HTML(200, tplComparePull)
  667. }
  668. // CompareAndPullRequestPost response for creating pull request
  669. func CompareAndPullRequestPost(ctx *context.Context, form auth.CreateIssueForm) {
  670. ctx.Data["Title"] = ctx.Tr("repo.pulls.compare_changes")
  671. ctx.Data["PageIsComparePull"] = true
  672. ctx.Data["IsDiffCompare"] = true
  673. ctx.Data["RequireHighlightJS"] = true
  674. renderAttachmentSettings(ctx)
  675. var (
  676. repo = ctx.Repo.Repository
  677. attachments []string
  678. )
  679. headUser, headRepo, headGitRepo, prInfo, baseBranch, headBranch := ParseCompareInfo(ctx)
  680. if ctx.Written() {
  681. return
  682. }
  683. labelIDs, milestoneID, assigneeID := ValidateRepoMetas(ctx, form)
  684. if ctx.Written() {
  685. return
  686. }
  687. if setting.AttachmentEnabled {
  688. attachments = form.Files
  689. }
  690. if ctx.HasError() {
  691. auth.AssignForm(form, ctx.Data)
  692. // This stage is already stop creating new pull request, so it does not matter if it has
  693. // something to compare or not.
  694. PrepareCompareDiff(ctx, headUser, headRepo, headGitRepo, prInfo, baseBranch, headBranch)
  695. if ctx.Written() {
  696. return
  697. }
  698. ctx.HTML(200, tplComparePull)
  699. return
  700. }
  701. patch, err := headGitRepo.GetPatch(prInfo.MergeBase, headBranch)
  702. if err != nil {
  703. ctx.Handle(500, "GetPatch", err)
  704. return
  705. }
  706. pullIssue := &models.Issue{
  707. RepoID: repo.ID,
  708. Index: repo.NextIssueIndex(),
  709. Title: form.Title,
  710. PosterID: ctx.User.ID,
  711. Poster: ctx.User,
  712. MilestoneID: milestoneID,
  713. AssigneeID: assigneeID,
  714. IsPull: true,
  715. Content: form.Content,
  716. }
  717. pullRequest := &models.PullRequest{
  718. HeadRepoID: headRepo.ID,
  719. BaseRepoID: repo.ID,
  720. HeadUserName: headUser.Name,
  721. HeadBranch: headBranch,
  722. BaseBranch: baseBranch,
  723. HeadRepo: headRepo,
  724. BaseRepo: repo,
  725. MergeBase: prInfo.MergeBase,
  726. Type: models.PullRequestGitea,
  727. }
  728. // FIXME: check error in the case two people send pull request at almost same time, give nice error prompt
  729. // instead of 500.
  730. if err := models.NewPullRequest(repo, pullIssue, labelIDs, attachments, pullRequest, patch); err != nil {
  731. ctx.Handle(500, "NewPullRequest", err)
  732. return
  733. } else if err := pullRequest.PushToBaseRepo(); err != nil {
  734. ctx.Handle(500, "PushToBaseRepo", err)
  735. return
  736. }
  737. notification.Service.NotifyIssue(pullIssue, ctx.User.ID)
  738. log.Trace("Pull request created: %d/%d", repo.ID, pullIssue.ID)
  739. ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(pullIssue.Index))
  740. }
  741. // TriggerTask response for a trigger task request
  742. func TriggerTask(ctx *context.Context) {
  743. pusherID := ctx.QueryInt64("pusher")
  744. branch := ctx.Query("branch")
  745. secret := ctx.Query("secret")
  746. if len(branch) == 0 || len(secret) == 0 || pusherID <= 0 {
  747. ctx.Error(404)
  748. log.Trace("TriggerTask: branch or secret is empty, or pusher ID is not valid")
  749. return
  750. }
  751. owner, repo := parseOwnerAndRepo(ctx)
  752. if ctx.Written() {
  753. return
  754. }
  755. if secret != base.EncodeMD5(owner.Salt) {
  756. ctx.Error(404)
  757. log.Trace("TriggerTask [%s/%s]: invalid secret", owner.Name, repo.Name)
  758. return
  759. }
  760. pusher, err := models.GetUserByID(pusherID)
  761. if err != nil {
  762. if models.IsErrUserNotExist(err) {
  763. ctx.Error(404)
  764. } else {
  765. ctx.Handle(500, "GetUserByID", err)
  766. }
  767. return
  768. }
  769. log.Trace("TriggerTask '%s/%s' by %s", repo.Name, branch, pusher.Name)
  770. go models.HookQueue.Add(repo.ID)
  771. go models.AddTestPullRequestTask(pusher, repo.ID, branch, true)
  772. ctx.Status(202)
  773. }
  774. // CleanUpPullRequest responses for delete merged branch when PR has been merged
  775. func CleanUpPullRequest(ctx *context.Context) {
  776. issue := checkPullInfo(ctx)
  777. if ctx.Written() {
  778. return
  779. }
  780. pr, err := models.GetPullRequestByIssueID(issue.ID)
  781. if err != nil {
  782. if models.IsErrPullRequestNotExist(err) {
  783. ctx.Handle(404, "GetPullRequestByIssueID", nil)
  784. } else {
  785. ctx.Handle(500, "GetPullRequestByIssueID", err)
  786. }
  787. return
  788. }
  789. // Allow cleanup only for merged PR
  790. if !pr.HasMerged {
  791. ctx.Handle(404, "CleanUpPullRequest", nil)
  792. return
  793. }
  794. if err = pr.GetHeadRepo(); err != nil {
  795. ctx.Handle(500, "GetHeadRepo", err)
  796. return
  797. } else if pr.HeadRepo == nil {
  798. // Forked repository has already been deleted
  799. ctx.Handle(404, "CleanUpPullRequest", nil)
  800. return
  801. } else if pr.GetBaseRepo(); err != nil {
  802. ctx.Handle(500, "GetBaseRepo", err)
  803. return
  804. } else if pr.HeadRepo.GetOwner(); err != nil {
  805. ctx.Handle(500, "HeadRepo.GetOwner", err)
  806. return
  807. }
  808. if !ctx.User.IsWriterOfRepo(pr.HeadRepo) {
  809. ctx.Handle(403, "CleanUpPullRequest", nil)
  810. return
  811. }
  812. fullBranchName := pr.HeadRepo.Owner.Name + "/" + pr.HeadBranch
  813. gitRepo, err := git.OpenRepository(pr.HeadRepo.RepoPath())
  814. if err != nil {
  815. ctx.Handle(500, fmt.Sprintf("OpenRepository[%s]", pr.HeadRepo.RepoPath()), err)
  816. return
  817. }
  818. gitBaseRepo, err := git.OpenRepository(pr.BaseRepo.RepoPath())
  819. if err != nil {
  820. ctx.Handle(500, fmt.Sprintf("OpenRepository[%s]", pr.BaseRepo.RepoPath()), err)
  821. return
  822. }
  823. defer func() {
  824. ctx.JSON(200, map[string]interface{}{
  825. "redirect": pr.BaseRepo.Link() + "/pulls/" + com.ToStr(issue.Index),
  826. })
  827. }()
  828. if pr.HeadBranch == pr.HeadRepo.DefaultBranch || !gitRepo.IsBranchExist(pr.HeadBranch) {
  829. ctx.Flash.Error(ctx.Tr("repo.branch.deletion_failed", fullBranchName))
  830. return
  831. }
  832. // Check if branch is not protected
  833. if protected, err := pr.HeadRepo.IsProtectedBranch(pr.HeadBranch, ctx.User); err != nil || protected {
  834. if err != nil {
  835. log.Error(4, "HeadRepo.IsProtectedBranch: %v", err)
  836. }
  837. ctx.Flash.Error(ctx.Tr("repo.branch.deletion_failed", fullBranchName))
  838. return
  839. }
  840. // Check if branch has no new commits
  841. if len(pr.MergedCommitID) > 0 {
  842. branchCommitID, err := gitRepo.GetBranchCommitID(pr.HeadBranch)
  843. if err != nil {
  844. log.Error(4, "GetBranchCommitID: %v", err)
  845. ctx.Flash.Error(ctx.Tr("repo.branch.deletion_failed", fullBranchName))
  846. return
  847. }
  848. commit, err := gitBaseRepo.GetCommit(pr.MergedCommitID)
  849. if err != nil {
  850. log.Error(4, "GetCommit: %v", err)
  851. ctx.Flash.Error(ctx.Tr("repo.branch.deletion_failed", fullBranchName))
  852. return
  853. }
  854. isParent := false
  855. for i := 0; i < commit.ParentCount(); i++ {
  856. if parent, err := commit.Parent(i); err != nil {
  857. log.Error(4, "Parent: %v", err)
  858. ctx.Flash.Error(ctx.Tr("repo.branch.deletion_failed", fullBranchName))
  859. return
  860. } else if parent.ID.String() == branchCommitID {
  861. isParent = true
  862. break
  863. }
  864. }
  865. if !isParent {
  866. ctx.Flash.Error(ctx.Tr("repo.branch.delete_branch_has_new_commits", fullBranchName))
  867. return
  868. }
  869. }
  870. if err := gitRepo.DeleteBranch(pr.HeadBranch, git.DeleteBranchOptions{
  871. Force: true,
  872. }); err != nil {
  873. log.Error(4, "DeleteBranch: %v", err)
  874. ctx.Flash.Error(ctx.Tr("repo.branch.deletion_failed", fullBranchName))
  875. return
  876. }
  877. if err := models.AddDeletePRBranchComment(ctx.User, pr.BaseRepo, issue.ID, pr.HeadBranch); err != nil {
  878. // Do not fail here as branch has already been deleted
  879. log.Error(4, "DeleteBranch: %v", err)
  880. }
  881. ctx.Flash.Success(ctx.Tr("repo.branch.deletion_success", fullBranchName))
  882. }
  883. // DownloadPullDiff render a pull's raw diff
  884. func DownloadPullDiff(ctx *context.Context) {
  885. issue, err := models.GetIssueByIndex(ctx.Repo.Repository.ID, ctx.ParamsInt64(":index"))
  886. if err != nil {
  887. if models.IsErrIssueNotExist(err) {
  888. ctx.Handle(404, "GetIssueByIndex", err)
  889. } else {
  890. ctx.Handle(500, "GetIssueByIndex", err)
  891. }
  892. return
  893. }
  894. // Redirect elsewhere if it's not a pull request
  895. if !issue.IsPull {
  896. ctx.Handle(404, "DownloadPullDiff",
  897. fmt.Errorf("Issue is not a pull request"))
  898. return
  899. }
  900. pr := issue.PullRequest
  901. if err = pr.GetBaseRepo(); err != nil {
  902. ctx.Handle(500, "GetBaseRepo", err)
  903. return
  904. }
  905. patch, err := pr.BaseRepo.PatchPath(pr.Index)
  906. if err != nil {
  907. ctx.Handle(500, "PatchPath", err)
  908. return
  909. }
  910. ctx.ServeFileContent(patch)
  911. }