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

pull.go 28KB

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