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

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