Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

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