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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186
  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. "path"
  12. "strings"
  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/git"
  18. "code.gitea.io/gitea/modules/log"
  19. "code.gitea.io/gitea/modules/notification"
  20. "code.gitea.io/gitea/modules/setting"
  21. "code.gitea.io/gitea/modules/util"
  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.IsEmpty || !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. if pull.IsFilesConflicted() {
  297. ctx.Data["IsPullFilesConflicted"] = true
  298. ctx.Data["ConflictedFiles"] = pull.ConflictedFiles
  299. }
  300. ctx.Data["NumCommits"] = prInfo.Commits.Len()
  301. ctx.Data["NumFiles"] = prInfo.NumFiles
  302. return prInfo
  303. }
  304. // ViewPullCommits show commits for a pull request
  305. func ViewPullCommits(ctx *context.Context) {
  306. ctx.Data["PageIsPullList"] = true
  307. ctx.Data["PageIsPullCommits"] = true
  308. issue := checkPullInfo(ctx)
  309. if ctx.Written() {
  310. return
  311. }
  312. pull := issue.PullRequest
  313. var commits *list.List
  314. if pull.HasMerged {
  315. prInfo := PrepareMergedViewPullInfo(ctx, issue)
  316. if ctx.Written() {
  317. return
  318. } else if prInfo == nil {
  319. ctx.NotFound("ViewPullCommits", nil)
  320. return
  321. }
  322. ctx.Data["Username"] = ctx.Repo.Owner.Name
  323. ctx.Data["Reponame"] = ctx.Repo.Repository.Name
  324. commits = prInfo.Commits
  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. whitespaceFlags := map[string]string{
  354. "ignore-all": "-w",
  355. "ignore-change": "-b",
  356. "ignore-eol": "--ignore-space-at-eol",
  357. "": ""}
  358. var (
  359. diffRepoPath string
  360. startCommitID string
  361. endCommitID string
  362. gitRepo *git.Repository
  363. )
  364. var headTarget string
  365. if pull.HasMerged {
  366. prInfo := PrepareMergedViewPullInfo(ctx, issue)
  367. if ctx.Written() {
  368. return
  369. } else if prInfo == nil {
  370. ctx.NotFound("ViewPullFiles", nil)
  371. return
  372. }
  373. diffRepoPath = ctx.Repo.GitRepo.Path
  374. gitRepo = ctx.Repo.GitRepo
  375. headCommitID, err := gitRepo.GetRefCommitID(pull.GetGitRefName())
  376. if err != nil {
  377. ctx.ServerError("GetRefCommitID", err)
  378. return
  379. }
  380. startCommitID = prInfo.MergeBase
  381. endCommitID = headCommitID
  382. headTarget = path.Join(ctx.Repo.Owner.Name, ctx.Repo.Repository.Name)
  383. ctx.Data["Username"] = ctx.Repo.Owner.Name
  384. ctx.Data["Reponame"] = ctx.Repo.Repository.Name
  385. } else {
  386. prInfo := PrepareViewPullInfo(ctx, issue)
  387. if ctx.Written() {
  388. return
  389. } else if prInfo == nil {
  390. ctx.NotFound("ViewPullFiles", nil)
  391. return
  392. }
  393. headRepoPath := models.RepoPath(pull.HeadUserName, pull.HeadRepo.Name)
  394. headGitRepo, err := git.OpenRepository(headRepoPath)
  395. if err != nil {
  396. ctx.ServerError("OpenRepository", err)
  397. return
  398. }
  399. headCommitID, err := headGitRepo.GetBranchCommitID(pull.HeadBranch)
  400. if err != nil {
  401. ctx.ServerError("GetBranchCommitID", err)
  402. return
  403. }
  404. diffRepoPath = headRepoPath
  405. startCommitID = prInfo.MergeBase
  406. endCommitID = headCommitID
  407. gitRepo = headGitRepo
  408. headTarget = path.Join(pull.HeadUserName, pull.HeadRepo.Name)
  409. ctx.Data["Username"] = pull.HeadUserName
  410. ctx.Data["Reponame"] = pull.HeadRepo.Name
  411. }
  412. diff, err := models.GetDiffRangeWithWhitespaceBehavior(diffRepoPath,
  413. startCommitID, endCommitID, setting.Git.MaxGitDiffLines,
  414. setting.Git.MaxGitDiffLineCharacters, setting.Git.MaxGitDiffFiles,
  415. whitespaceFlags[ctx.Data["WhitespaceBehavior"].(string)])
  416. if err != nil {
  417. ctx.ServerError("GetDiffRangeWithWhitespaceBehavior", err)
  418. return
  419. }
  420. if err = diff.LoadComments(issue, ctx.User); err != nil {
  421. ctx.ServerError("LoadComments", err)
  422. return
  423. }
  424. ctx.Data["Diff"] = diff
  425. ctx.Data["DiffNotAvailable"] = diff.NumFiles() == 0
  426. commit, err := gitRepo.GetCommit(endCommitID)
  427. if err != nil {
  428. ctx.ServerError("GetCommit", err)
  429. return
  430. }
  431. ctx.Data["IsImageFile"] = commit.IsImageFile
  432. ctx.Data["SourcePath"] = setting.AppSubURL + "/" + path.Join(headTarget, "src", "commit", endCommitID)
  433. ctx.Data["BeforeSourcePath"] = setting.AppSubURL + "/" + path.Join(headTarget, "src", "commit", startCommitID)
  434. ctx.Data["RawPath"] = setting.AppSubURL + "/" + path.Join(headTarget, "raw", "commit", endCommitID)
  435. ctx.Data["RequireHighlightJS"] = true
  436. ctx.Data["RequireTribute"] = true
  437. if ctx.Data["Assignees"], err = ctx.Repo.Repository.GetAssignees(); err != nil {
  438. ctx.ServerError("GetAssignees", err)
  439. return
  440. }
  441. ctx.Data["CurrentReview"], err = models.GetCurrentReview(ctx.User, issue)
  442. if err != nil && !models.IsErrReviewNotExist(err) {
  443. ctx.ServerError("GetCurrentReview", err)
  444. return
  445. }
  446. ctx.HTML(200, tplPullFiles)
  447. }
  448. // MergePullRequest response for merging pull request
  449. func MergePullRequest(ctx *context.Context, form auth.MergePullRequestForm) {
  450. issue := checkPullInfo(ctx)
  451. if ctx.Written() {
  452. return
  453. }
  454. if issue.IsClosed {
  455. ctx.NotFound("MergePullRequest", nil)
  456. return
  457. }
  458. pr := issue.PullRequest
  459. if !pr.CanAutoMerge() || pr.HasMerged {
  460. ctx.NotFound("MergePullRequest", nil)
  461. return
  462. }
  463. if pr.IsWorkInProgress() {
  464. ctx.Flash.Error(ctx.Tr("repo.pulls.no_merge_wip"))
  465. ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(pr.Index))
  466. return
  467. }
  468. if ctx.HasError() {
  469. ctx.Flash.Error(ctx.Data["ErrorMsg"].(string))
  470. ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(pr.Index))
  471. return
  472. }
  473. message := strings.TrimSpace(form.MergeTitleField)
  474. if len(message) == 0 {
  475. if models.MergeStyle(form.Do) == models.MergeStyleMerge {
  476. message = pr.GetDefaultMergeMessage()
  477. }
  478. if models.MergeStyle(form.Do) == models.MergeStyleRebaseMerge {
  479. message = pr.GetDefaultMergeMessage()
  480. }
  481. if models.MergeStyle(form.Do) == models.MergeStyleSquash {
  482. message = pr.GetDefaultSquashMessage()
  483. }
  484. }
  485. form.MergeMessageField = strings.TrimSpace(form.MergeMessageField)
  486. if len(form.MergeMessageField) > 0 {
  487. message += "\n\n" + form.MergeMessageField
  488. }
  489. pr.Issue = issue
  490. pr.Issue.Repo = ctx.Repo.Repository
  491. noDeps, err := models.IssueNoDependenciesLeft(issue)
  492. if err != nil {
  493. return
  494. }
  495. if !noDeps {
  496. ctx.Flash.Error(ctx.Tr("repo.issues.dependency.pr_close_blocked"))
  497. ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(pr.Index))
  498. return
  499. }
  500. if err = pr.Merge(ctx.User, ctx.Repo.GitRepo, models.MergeStyle(form.Do), message); err != nil {
  501. if models.IsErrInvalidMergeStyle(err) {
  502. ctx.Flash.Error(ctx.Tr("repo.pulls.invalid_merge_option"))
  503. ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(pr.Index))
  504. return
  505. }
  506. ctx.ServerError("Merge", err)
  507. return
  508. }
  509. if err := stopTimerIfAvailable(ctx.User, issue); err != nil {
  510. ctx.ServerError("CreateOrStopIssueStopwatch", err)
  511. return
  512. }
  513. notification.NotifyMergePullRequest(pr, ctx.User, ctx.Repo.GitRepo)
  514. log.Trace("Pull request merged: %d", pr.ID)
  515. ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(pr.Index))
  516. }
  517. func stopTimerIfAvailable(user *models.User, issue *models.Issue) error {
  518. if models.StopwatchExists(user.ID, issue.ID) {
  519. if err := models.CreateOrStopIssueStopwatch(user, issue); err != nil {
  520. return err
  521. }
  522. }
  523. return nil
  524. }
  525. // ParseCompareInfo parse compare info between two commit for preparing pull request
  526. func ParseCompareInfo(ctx *context.Context) (*models.User, *models.Repository, *git.Repository, *git.PullRequestInfo, string, string) {
  527. baseRepo := ctx.Repo.Repository
  528. // Get compared branches information
  529. // format: <base branch>...[<head repo>:]<head branch>
  530. // base<-head: master...head:feature
  531. // same repo: master...feature
  532. var (
  533. headUser *models.User
  534. headBranch string
  535. isSameRepo bool
  536. infoPath string
  537. err error
  538. )
  539. infoPath = ctx.Params("*")
  540. infos := strings.Split(infoPath, "...")
  541. if len(infos) != 2 {
  542. log.Trace("ParseCompareInfo[%d]: not enough compared branches information %s", baseRepo.ID, infos)
  543. ctx.NotFound("CompareAndPullRequest", nil)
  544. return nil, nil, nil, nil, "", ""
  545. }
  546. baseBranch := infos[0]
  547. ctx.Data["BaseBranch"] = baseBranch
  548. // If there is no head repository, it means pull request between same repository.
  549. headInfos := strings.Split(infos[1], ":")
  550. if len(headInfos) == 1 {
  551. isSameRepo = true
  552. headUser = ctx.Repo.Owner
  553. headBranch = headInfos[0]
  554. } else if len(headInfos) == 2 {
  555. headUser, err = models.GetUserByName(headInfos[0])
  556. if err != nil {
  557. if models.IsErrUserNotExist(err) {
  558. ctx.NotFound("GetUserByName", nil)
  559. } else {
  560. ctx.ServerError("GetUserByName", err)
  561. }
  562. return nil, nil, nil, nil, "", ""
  563. }
  564. headBranch = headInfos[1]
  565. isSameRepo = headUser.ID == ctx.Repo.Owner.ID
  566. } else {
  567. ctx.NotFound("CompareAndPullRequest", nil)
  568. return nil, nil, nil, nil, "", ""
  569. }
  570. ctx.Data["HeadUser"] = headUser
  571. ctx.Data["HeadBranch"] = headBranch
  572. ctx.Repo.PullRequest.SameRepo = isSameRepo
  573. // Check if base branch is valid.
  574. if !ctx.Repo.GitRepo.IsBranchExist(baseBranch) {
  575. ctx.NotFound("IsBranchExist", nil)
  576. return nil, nil, nil, nil, "", ""
  577. }
  578. // Check if current user has fork of repository or in the same repository.
  579. headRepo, has := models.HasForkedRepo(headUser.ID, baseRepo.ID)
  580. if !has && !isSameRepo {
  581. log.Trace("ParseCompareInfo[%d]: does not have fork or in same repository", baseRepo.ID)
  582. ctx.NotFound("ParseCompareInfo", nil)
  583. return nil, nil, nil, nil, "", ""
  584. }
  585. var headGitRepo *git.Repository
  586. if isSameRepo {
  587. headRepo = ctx.Repo.Repository
  588. headGitRepo = ctx.Repo.GitRepo
  589. ctx.Data["BaseName"] = headUser.Name
  590. } else {
  591. headGitRepo, err = git.OpenRepository(models.RepoPath(headUser.Name, headRepo.Name))
  592. ctx.Data["BaseName"] = baseRepo.OwnerName
  593. if err != nil {
  594. ctx.ServerError("OpenRepository", err)
  595. return nil, nil, nil, nil, "", ""
  596. }
  597. }
  598. perm, err := models.GetUserRepoPermission(headRepo, ctx.User)
  599. if err != nil {
  600. ctx.ServerError("GetUserRepoPermission", err)
  601. return nil, nil, nil, nil, "", ""
  602. }
  603. if !perm.CanReadIssuesOrPulls(true) {
  604. log.Trace("ParseCompareInfo[%d]: cannot create/read pull requests", baseRepo.ID)
  605. ctx.NotFound("ParseCompareInfo", nil)
  606. return nil, nil, nil, nil, "", ""
  607. }
  608. // Check if head branch is valid.
  609. if !headGitRepo.IsBranchExist(headBranch) {
  610. ctx.NotFound("IsBranchExist", nil)
  611. return nil, nil, nil, nil, "", ""
  612. }
  613. headBranches, err := headGitRepo.GetBranches()
  614. if err != nil {
  615. ctx.ServerError("GetBranches", err)
  616. return nil, nil, nil, nil, "", ""
  617. }
  618. ctx.Data["HeadBranches"] = headBranches
  619. prInfo, err := headGitRepo.GetPullRequestInfo(models.RepoPath(baseRepo.Owner.Name, baseRepo.Name), baseBranch, headBranch)
  620. if err != nil {
  621. ctx.ServerError("GetPullRequestInfo", err)
  622. return nil, nil, nil, nil, "", ""
  623. }
  624. ctx.Data["BeforeCommitID"] = prInfo.MergeBase
  625. return headUser, headRepo, headGitRepo, prInfo, baseBranch, headBranch
  626. }
  627. // PrepareCompareDiff render pull request preview diff page
  628. func PrepareCompareDiff(
  629. ctx *context.Context,
  630. headUser *models.User,
  631. headRepo *models.Repository,
  632. headGitRepo *git.Repository,
  633. prInfo *git.PullRequestInfo,
  634. baseBranch, headBranch string) bool {
  635. var (
  636. repo = ctx.Repo.Repository
  637. err error
  638. title string
  639. )
  640. // Get diff information.
  641. ctx.Data["CommitRepoLink"] = headRepo.Link()
  642. headCommitID, err := headGitRepo.GetBranchCommitID(headBranch)
  643. if err != nil {
  644. ctx.ServerError("GetBranchCommitID", err)
  645. return false
  646. }
  647. ctx.Data["AfterCommitID"] = headCommitID
  648. if headCommitID == prInfo.MergeBase {
  649. ctx.Data["IsNothingToCompare"] = true
  650. return true
  651. }
  652. diff, err := models.GetDiffRange(models.RepoPath(headUser.Name, headRepo.Name),
  653. prInfo.MergeBase, headCommitID, setting.Git.MaxGitDiffLines,
  654. setting.Git.MaxGitDiffLineCharacters, setting.Git.MaxGitDiffFiles)
  655. if err != nil {
  656. ctx.ServerError("GetDiffRange", err)
  657. return false
  658. }
  659. ctx.Data["Diff"] = diff
  660. ctx.Data["DiffNotAvailable"] = diff.NumFiles() == 0
  661. headCommit, err := headGitRepo.GetCommit(headCommitID)
  662. if err != nil {
  663. ctx.ServerError("GetCommit", err)
  664. return false
  665. }
  666. prInfo.Commits = models.ValidateCommitsWithEmails(prInfo.Commits)
  667. prInfo.Commits = models.ParseCommitsWithSignature(prInfo.Commits)
  668. prInfo.Commits = models.ParseCommitsWithStatus(prInfo.Commits, headRepo)
  669. ctx.Data["Commits"] = prInfo.Commits
  670. ctx.Data["CommitCount"] = prInfo.Commits.Len()
  671. if prInfo.Commits.Len() == 1 {
  672. c := prInfo.Commits.Front().Value.(models.SignCommitWithStatuses)
  673. title = strings.TrimSpace(c.UserCommit.Summary())
  674. body := strings.Split(strings.TrimSpace(c.UserCommit.Message()), "\n")
  675. if len(body) > 1 {
  676. ctx.Data["content"] = strings.Join(body[1:], "\n")
  677. }
  678. } else {
  679. title = headBranch
  680. }
  681. ctx.Data["title"] = title
  682. ctx.Data["Username"] = headUser.Name
  683. ctx.Data["Reponame"] = headRepo.Name
  684. ctx.Data["IsImageFile"] = headCommit.IsImageFile
  685. headTarget := path.Join(headUser.Name, repo.Name)
  686. ctx.Data["SourcePath"] = setting.AppSubURL + "/" + path.Join(headTarget, "src", "commit", headCommitID)
  687. ctx.Data["BeforeSourcePath"] = setting.AppSubURL + "/" + path.Join(headTarget, "src", "commit", prInfo.MergeBase)
  688. ctx.Data["RawPath"] = setting.AppSubURL + "/" + path.Join(headTarget, "raw", "commit", headCommitID)
  689. return false
  690. }
  691. // CompareAndPullRequest render pull request preview page
  692. func CompareAndPullRequest(ctx *context.Context) {
  693. ctx.Data["Title"] = ctx.Tr("repo.pulls.compare_changes")
  694. ctx.Data["PageIsComparePull"] = true
  695. ctx.Data["IsDiffCompare"] = true
  696. ctx.Data["RequireHighlightJS"] = true
  697. ctx.Data["RequireTribute"] = true
  698. ctx.Data["PullRequestWorkInProgressPrefixes"] = setting.Repository.PullRequest.WorkInProgressPrefixes
  699. setTemplateIfExists(ctx, pullRequestTemplateKey, pullRequestTemplateCandidates)
  700. renderAttachmentSettings(ctx)
  701. headUser, headRepo, headGitRepo, prInfo, baseBranch, headBranch := ParseCompareInfo(ctx)
  702. if ctx.Written() {
  703. return
  704. }
  705. pr, err := models.GetUnmergedPullRequest(headRepo.ID, ctx.Repo.Repository.ID, headBranch, baseBranch)
  706. if err != nil {
  707. if !models.IsErrPullRequestNotExist(err) {
  708. ctx.ServerError("GetUnmergedPullRequest", err)
  709. return
  710. }
  711. } else {
  712. ctx.Data["HasPullRequest"] = true
  713. ctx.Data["PullRequest"] = pr
  714. ctx.HTML(200, tplComparePull)
  715. return
  716. }
  717. nothingToCompare := PrepareCompareDiff(ctx, headUser, headRepo, headGitRepo, prInfo, baseBranch, headBranch)
  718. if ctx.Written() {
  719. return
  720. }
  721. if !nothingToCompare {
  722. // Setup information for new form.
  723. RetrieveRepoMetas(ctx, ctx.Repo.Repository)
  724. if ctx.Written() {
  725. return
  726. }
  727. }
  728. ctx.HTML(200, tplComparePull)
  729. }
  730. // CompareAndPullRequestPost response for creating pull request
  731. func CompareAndPullRequestPost(ctx *context.Context, form auth.CreateIssueForm) {
  732. ctx.Data["Title"] = ctx.Tr("repo.pulls.compare_changes")
  733. ctx.Data["PageIsComparePull"] = true
  734. ctx.Data["IsDiffCompare"] = true
  735. ctx.Data["RequireHighlightJS"] = true
  736. ctx.Data["PullRequestWorkInProgressPrefixes"] = setting.Repository.PullRequest.WorkInProgressPrefixes
  737. renderAttachmentSettings(ctx)
  738. var (
  739. repo = ctx.Repo.Repository
  740. attachments []string
  741. )
  742. headUser, headRepo, headGitRepo, prInfo, baseBranch, headBranch := ParseCompareInfo(ctx)
  743. if ctx.Written() {
  744. return
  745. }
  746. labelIDs, assigneeIDs, milestoneID := ValidateRepoMetas(ctx, form, true)
  747. if ctx.Written() {
  748. return
  749. }
  750. if setting.AttachmentEnabled {
  751. attachments = form.Files
  752. }
  753. if ctx.HasError() {
  754. auth.AssignForm(form, ctx.Data)
  755. // This stage is already stop creating new pull request, so it does not matter if it has
  756. // something to compare or not.
  757. PrepareCompareDiff(ctx, headUser, headRepo, headGitRepo, prInfo, baseBranch, headBranch)
  758. if ctx.Written() {
  759. return
  760. }
  761. ctx.HTML(200, tplComparePull)
  762. return
  763. }
  764. if util.IsEmptyString(form.Title) {
  765. PrepareCompareDiff(ctx, headUser, headRepo, headGitRepo, prInfo, baseBranch, headBranch)
  766. if ctx.Written() {
  767. return
  768. }
  769. ctx.RenderWithErr(ctx.Tr("repo.issues.new.title_empty"), tplComparePull, form)
  770. return
  771. }
  772. patch, err := headGitRepo.GetPatch(prInfo.MergeBase, headBranch)
  773. if err != nil {
  774. ctx.ServerError("GetPatch", err)
  775. return
  776. }
  777. pullIssue := &models.Issue{
  778. RepoID: repo.ID,
  779. Index: repo.NextIssueIndex(),
  780. Title: form.Title,
  781. PosterID: ctx.User.ID,
  782. Poster: ctx.User,
  783. MilestoneID: milestoneID,
  784. IsPull: true,
  785. Content: form.Content,
  786. }
  787. pullRequest := &models.PullRequest{
  788. HeadRepoID: headRepo.ID,
  789. BaseRepoID: repo.ID,
  790. HeadUserName: headUser.Name,
  791. HeadBranch: headBranch,
  792. BaseBranch: baseBranch,
  793. HeadRepo: headRepo,
  794. BaseRepo: repo,
  795. MergeBase: prInfo.MergeBase,
  796. Type: models.PullRequestGitea,
  797. }
  798. // FIXME: check error in the case two people send pull request at almost same time, give nice error prompt
  799. // instead of 500.
  800. if err := models.NewPullRequest(repo, pullIssue, labelIDs, attachments, pullRequest, patch, assigneeIDs); err != nil {
  801. if models.IsErrUserDoesNotHaveAccessToRepo(err) {
  802. ctx.Error(400, "UserDoesNotHaveAccessToRepo", err.Error())
  803. return
  804. }
  805. ctx.ServerError("NewPullRequest", err)
  806. return
  807. } else if err := pullRequest.PushToBaseRepo(); err != nil {
  808. ctx.ServerError("PushToBaseRepo", err)
  809. return
  810. }
  811. notification.NotifyNewPullRequest(pullRequest)
  812. log.Trace("Pull request created: %d/%d", repo.ID, pullIssue.ID)
  813. ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(pullIssue.Index))
  814. }
  815. // TriggerTask response for a trigger task request
  816. func TriggerTask(ctx *context.Context) {
  817. pusherID := ctx.QueryInt64("pusher")
  818. branch := ctx.Query("branch")
  819. secret := ctx.Query("secret")
  820. if len(branch) == 0 || len(secret) == 0 || pusherID <= 0 {
  821. ctx.Error(404)
  822. log.Trace("TriggerTask: branch or secret is empty, or pusher ID is not valid")
  823. return
  824. }
  825. owner, repo := parseOwnerAndRepo(ctx)
  826. if ctx.Written() {
  827. return
  828. }
  829. if secret != base.EncodeMD5(owner.Salt) {
  830. ctx.Error(404)
  831. log.Trace("TriggerTask [%s/%s]: invalid secret", owner.Name, repo.Name)
  832. return
  833. }
  834. pusher, err := models.GetUserByID(pusherID)
  835. if err != nil {
  836. if models.IsErrUserNotExist(err) {
  837. ctx.Error(404)
  838. } else {
  839. ctx.ServerError("GetUserByID", err)
  840. }
  841. return
  842. }
  843. log.Trace("TriggerTask '%s/%s' by %s", repo.Name, branch, pusher.Name)
  844. go models.HookQueue.Add(repo.ID)
  845. go models.AddTestPullRequestTask(pusher, repo.ID, branch, true)
  846. ctx.Status(202)
  847. }
  848. // CleanUpPullRequest responses for delete merged branch when PR has been merged
  849. func CleanUpPullRequest(ctx *context.Context) {
  850. issue := checkPullInfo(ctx)
  851. if ctx.Written() {
  852. return
  853. }
  854. pr := issue.PullRequest
  855. // Don't cleanup unmerged and unclosed PRs
  856. if !pr.HasMerged && !issue.IsClosed {
  857. ctx.NotFound("CleanUpPullRequest", nil)
  858. return
  859. }
  860. if err := pr.GetHeadRepo(); err != nil {
  861. ctx.ServerError("GetHeadRepo", err)
  862. return
  863. } else if pr.HeadRepo == nil {
  864. // Forked repository has already been deleted
  865. ctx.NotFound("CleanUpPullRequest", nil)
  866. return
  867. } else if pr.GetBaseRepo(); err != nil {
  868. ctx.ServerError("GetBaseRepo", err)
  869. return
  870. } else if pr.HeadRepo.GetOwner(); err != nil {
  871. ctx.ServerError("HeadRepo.GetOwner", err)
  872. return
  873. }
  874. perm, err := models.GetUserRepoPermission(pr.HeadRepo, ctx.User)
  875. if err != nil {
  876. ctx.ServerError("GetUserRepoPermission", err)
  877. return
  878. }
  879. if !perm.CanWrite(models.UnitTypeCode) {
  880. ctx.NotFound("CleanUpPullRequest", nil)
  881. return
  882. }
  883. fullBranchName := pr.HeadRepo.Owner.Name + "/" + pr.HeadBranch
  884. gitRepo, err := git.OpenRepository(pr.HeadRepo.RepoPath())
  885. if err != nil {
  886. ctx.ServerError(fmt.Sprintf("OpenRepository[%s]", pr.HeadRepo.RepoPath()), err)
  887. return
  888. }
  889. gitBaseRepo, err := git.OpenRepository(pr.BaseRepo.RepoPath())
  890. if err != nil {
  891. ctx.ServerError(fmt.Sprintf("OpenRepository[%s]", pr.BaseRepo.RepoPath()), err)
  892. return
  893. }
  894. defer func() {
  895. ctx.JSON(200, map[string]interface{}{
  896. "redirect": pr.BaseRepo.Link() + "/pulls/" + com.ToStr(issue.Index),
  897. })
  898. }()
  899. if pr.HeadBranch == pr.HeadRepo.DefaultBranch || !gitRepo.IsBranchExist(pr.HeadBranch) {
  900. ctx.Flash.Error(ctx.Tr("repo.branch.deletion_failed", fullBranchName))
  901. return
  902. }
  903. // Check if branch is not protected
  904. if protected, err := pr.HeadRepo.IsProtectedBranch(pr.HeadBranch, ctx.User); err != nil || protected {
  905. if err != nil {
  906. log.Error("HeadRepo.IsProtectedBranch: %v", err)
  907. }
  908. ctx.Flash.Error(ctx.Tr("repo.branch.deletion_failed", fullBranchName))
  909. return
  910. }
  911. // Check if branch has no new commits
  912. headCommitID, err := gitBaseRepo.GetRefCommitID(pr.GetGitRefName())
  913. if err != nil {
  914. log.Error("GetRefCommitID: %v", err)
  915. ctx.Flash.Error(ctx.Tr("repo.branch.deletion_failed", fullBranchName))
  916. return
  917. }
  918. branchCommitID, err := gitRepo.GetBranchCommitID(pr.HeadBranch)
  919. if err != nil {
  920. log.Error("GetBranchCommitID: %v", err)
  921. ctx.Flash.Error(ctx.Tr("repo.branch.deletion_failed", fullBranchName))
  922. return
  923. }
  924. if headCommitID != branchCommitID {
  925. ctx.Flash.Error(ctx.Tr("repo.branch.delete_branch_has_new_commits", fullBranchName))
  926. return
  927. }
  928. if err := gitRepo.DeleteBranch(pr.HeadBranch, git.DeleteBranchOptions{
  929. Force: true,
  930. }); err != nil {
  931. log.Error("DeleteBranch: %v", err)
  932. ctx.Flash.Error(ctx.Tr("repo.branch.deletion_failed", fullBranchName))
  933. return
  934. }
  935. if err := models.AddDeletePRBranchComment(ctx.User, pr.BaseRepo, issue.ID, pr.HeadBranch); err != nil {
  936. // Do not fail here as branch has already been deleted
  937. log.Error("DeleteBranch: %v", err)
  938. }
  939. ctx.Flash.Success(ctx.Tr("repo.branch.deletion_success", fullBranchName))
  940. }
  941. // DownloadPullDiff render a pull's raw diff
  942. func DownloadPullDiff(ctx *context.Context) {
  943. issue, err := models.GetIssueByIndex(ctx.Repo.Repository.ID, ctx.ParamsInt64(":index"))
  944. if err != nil {
  945. if models.IsErrIssueNotExist(err) {
  946. ctx.NotFound("GetIssueByIndex", err)
  947. } else {
  948. ctx.ServerError("GetIssueByIndex", err)
  949. }
  950. return
  951. }
  952. // Return not found if it's not a pull request
  953. if !issue.IsPull {
  954. ctx.NotFound("DownloadPullDiff",
  955. fmt.Errorf("Issue is not a pull request"))
  956. return
  957. }
  958. if err = issue.LoadPullRequest(); err != nil {
  959. ctx.ServerError("LoadPullRequest", err)
  960. return
  961. }
  962. pr := issue.PullRequest
  963. if err = pr.GetBaseRepo(); err != nil {
  964. ctx.ServerError("GetBaseRepo", err)
  965. return
  966. }
  967. patch, err := pr.BaseRepo.PatchPath(pr.Index)
  968. if err != nil {
  969. ctx.ServerError("PatchPath", err)
  970. return
  971. }
  972. ctx.ServeFileContent(patch)
  973. }
  974. // DownloadPullPatch render a pull's raw patch
  975. func DownloadPullPatch(ctx *context.Context) {
  976. issue, err := models.GetIssueByIndex(ctx.Repo.Repository.ID, ctx.ParamsInt64(":index"))
  977. if err != nil {
  978. if models.IsErrIssueNotExist(err) {
  979. ctx.NotFound("GetIssueByIndex", err)
  980. } else {
  981. ctx.ServerError("GetIssueByIndex", err)
  982. }
  983. return
  984. }
  985. // Return not found if it's not a pull request
  986. if !issue.IsPull {
  987. ctx.NotFound("DownloadPullDiff",
  988. fmt.Errorf("Issue is not a pull request"))
  989. return
  990. }
  991. if err = issue.LoadPullRequest(); err != nil {
  992. ctx.ServerError("LoadPullRequest", err)
  993. return
  994. }
  995. pr := issue.PullRequest
  996. if err = pr.GetHeadRepo(); err != nil {
  997. ctx.ServerError("GetHeadRepo", err)
  998. return
  999. }
  1000. headGitRepo, err := git.OpenRepository(pr.HeadRepo.RepoPath())
  1001. if err != nil {
  1002. ctx.ServerError("OpenRepository", err)
  1003. return
  1004. }
  1005. patch, err := headGitRepo.GetFormatPatch(pr.MergeBase, pr.HeadBranch)
  1006. if err != nil {
  1007. ctx.ServerError("GetFormatPatch", err)
  1008. return
  1009. }
  1010. _, err = io.Copy(ctx, patch)
  1011. if err != nil {
  1012. ctx.ServerError("io.Copy", err)
  1013. return
  1014. }
  1015. }