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 30KB

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