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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068
  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. defer headGitRepo.Close()
  307. headBranchExist = headGitRepo.IsBranchExist(pull.HeadBranch)
  308. if headBranchExist {
  309. sha, err := headGitRepo.GetBranchCommitID(pull.HeadBranch)
  310. if err != nil {
  311. ctx.ServerError("GetBranchCommitID", err)
  312. return nil
  313. }
  314. commitStatuses, err := models.GetLatestCommitStatus(repo, sha, 0)
  315. if err != nil {
  316. ctx.ServerError("GetLatestCommitStatus", err)
  317. return nil
  318. }
  319. if len(commitStatuses) > 0 {
  320. ctx.Data["LatestCommitStatuses"] = commitStatuses
  321. ctx.Data["LatestCommitStatus"] = models.CalcCommitStatus(commitStatuses)
  322. }
  323. if pull.ProtectedBranch != nil && pull.ProtectedBranch.EnableStatusCheck {
  324. ctx.Data["is_context_required"] = func(context string) bool {
  325. for _, c := range pull.ProtectedBranch.StatusCheckContexts {
  326. if c == context {
  327. return true
  328. }
  329. }
  330. return false
  331. }
  332. ctx.Data["IsRequiredStatusCheckSuccess"] = pull_service.IsCommitStatusContextSuccess(commitStatuses, pull.ProtectedBranch.StatusCheckContexts)
  333. }
  334. }
  335. }
  336. if pull.HeadRepo == nil || !headBranchExist {
  337. ctx.Data["IsPullRequestBroken"] = true
  338. ctx.Data["HeadTarget"] = "deleted"
  339. ctx.Data["NumCommits"] = 0
  340. ctx.Data["NumFiles"] = 0
  341. return nil
  342. }
  343. compareInfo, err := headGitRepo.GetCompareInfo(models.RepoPath(repo.Owner.Name, repo.Name),
  344. pull.BaseBranch, pull.HeadBranch)
  345. if err != nil {
  346. if strings.Contains(err.Error(), "fatal: Not a valid object name") {
  347. ctx.Data["IsPullRequestBroken"] = true
  348. ctx.Data["BaseTarget"] = "deleted"
  349. ctx.Data["NumCommits"] = 0
  350. ctx.Data["NumFiles"] = 0
  351. return nil
  352. }
  353. ctx.ServerError("GetCompareInfo", err)
  354. return nil
  355. }
  356. if pull.IsWorkInProgress() {
  357. ctx.Data["IsPullWorkInProgress"] = true
  358. ctx.Data["WorkInProgressPrefix"] = pull.GetWorkInProgressPrefix()
  359. }
  360. if pull.IsFilesConflicted() {
  361. ctx.Data["IsPullFilesConflicted"] = true
  362. ctx.Data["ConflictedFiles"] = pull.ConflictedFiles
  363. }
  364. ctx.Data["NumCommits"] = compareInfo.Commits.Len()
  365. ctx.Data["NumFiles"] = compareInfo.NumFiles
  366. return compareInfo
  367. }
  368. // ViewPullCommits show commits for a pull request
  369. func ViewPullCommits(ctx *context.Context) {
  370. ctx.Data["PageIsPullList"] = true
  371. ctx.Data["PageIsPullCommits"] = true
  372. issue := checkPullInfo(ctx)
  373. if ctx.Written() {
  374. return
  375. }
  376. pull := issue.PullRequest
  377. var commits *list.List
  378. if pull.HasMerged {
  379. prInfo := PrepareMergedViewPullInfo(ctx, issue)
  380. if ctx.Written() {
  381. return
  382. } else if prInfo == nil {
  383. ctx.NotFound("ViewPullCommits", nil)
  384. return
  385. }
  386. ctx.Data["Username"] = ctx.Repo.Owner.Name
  387. ctx.Data["Reponame"] = ctx.Repo.Repository.Name
  388. commits = prInfo.Commits
  389. } else {
  390. prInfo := PrepareViewPullInfo(ctx, issue)
  391. if ctx.Written() {
  392. return
  393. } else if prInfo == nil {
  394. ctx.NotFound("ViewPullCommits", nil)
  395. return
  396. }
  397. ctx.Data["Username"] = pull.MustHeadUserName()
  398. ctx.Data["Reponame"] = pull.HeadRepo.Name
  399. commits = prInfo.Commits
  400. }
  401. commits = models.ValidateCommitsWithEmails(commits)
  402. commits = models.ParseCommitsWithSignature(commits)
  403. commits = models.ParseCommitsWithStatus(commits, ctx.Repo.Repository)
  404. ctx.Data["Commits"] = commits
  405. ctx.Data["CommitCount"] = commits.Len()
  406. ctx.HTML(200, tplPullCommits)
  407. }
  408. // ViewPullFiles render pull request changed files list page
  409. func ViewPullFiles(ctx *context.Context) {
  410. ctx.Data["PageIsPullList"] = true
  411. ctx.Data["PageIsPullFiles"] = true
  412. issue := checkPullInfo(ctx)
  413. if ctx.Written() {
  414. return
  415. }
  416. pull := issue.PullRequest
  417. whitespaceFlags := map[string]string{
  418. "ignore-all": "-w",
  419. "ignore-change": "-b",
  420. "ignore-eol": "--ignore-space-at-eol",
  421. "": ""}
  422. var (
  423. diffRepoPath string
  424. startCommitID string
  425. endCommitID string
  426. gitRepo *git.Repository
  427. )
  428. var headTarget string
  429. if pull.HasMerged {
  430. prInfo := PrepareMergedViewPullInfo(ctx, issue)
  431. if ctx.Written() {
  432. return
  433. } else if prInfo == nil {
  434. ctx.NotFound("ViewPullFiles", nil)
  435. return
  436. }
  437. diffRepoPath = ctx.Repo.GitRepo.Path
  438. gitRepo = ctx.Repo.GitRepo
  439. headCommitID, err := gitRepo.GetRefCommitID(pull.GetGitRefName())
  440. if err != nil {
  441. ctx.ServerError("GetRefCommitID", err)
  442. return
  443. }
  444. startCommitID = prInfo.MergeBase
  445. endCommitID = headCommitID
  446. headTarget = path.Join(ctx.Repo.Owner.Name, ctx.Repo.Repository.Name)
  447. ctx.Data["Username"] = ctx.Repo.Owner.Name
  448. ctx.Data["Reponame"] = ctx.Repo.Repository.Name
  449. } else {
  450. prInfo := PrepareViewPullInfo(ctx, issue)
  451. if ctx.Written() {
  452. return
  453. } else if prInfo == nil {
  454. ctx.NotFound("ViewPullFiles", nil)
  455. return
  456. }
  457. headRepoPath := pull.HeadRepo.RepoPath()
  458. headGitRepo, err := git.OpenRepository(headRepoPath)
  459. if err != nil {
  460. ctx.ServerError("OpenRepository", err)
  461. return
  462. }
  463. defer headGitRepo.Close()
  464. headCommitID, err := headGitRepo.GetBranchCommitID(pull.HeadBranch)
  465. if err != nil {
  466. ctx.ServerError("GetBranchCommitID", err)
  467. return
  468. }
  469. diffRepoPath = headRepoPath
  470. startCommitID = prInfo.MergeBase
  471. endCommitID = headCommitID
  472. gitRepo = headGitRepo
  473. headTarget = path.Join(pull.MustHeadUserName(), pull.HeadRepo.Name)
  474. ctx.Data["Username"] = pull.MustHeadUserName()
  475. ctx.Data["Reponame"] = pull.HeadRepo.Name
  476. }
  477. diff, err := gitdiff.GetDiffRangeWithWhitespaceBehavior(diffRepoPath,
  478. startCommitID, endCommitID, setting.Git.MaxGitDiffLines,
  479. setting.Git.MaxGitDiffLineCharacters, setting.Git.MaxGitDiffFiles,
  480. whitespaceFlags[ctx.Data["WhitespaceBehavior"].(string)])
  481. if err != nil {
  482. ctx.ServerError("GetDiffRangeWithWhitespaceBehavior", err)
  483. return
  484. }
  485. if err = diff.LoadComments(issue, ctx.User); err != nil {
  486. ctx.ServerError("LoadComments", err)
  487. return
  488. }
  489. ctx.Data["Diff"] = diff
  490. ctx.Data["DiffNotAvailable"] = diff.NumFiles() == 0
  491. baseCommit, err := ctx.Repo.GitRepo.GetCommit(startCommitID)
  492. if err != nil {
  493. ctx.ServerError("GetCommit", err)
  494. return
  495. }
  496. commit, err := gitRepo.GetCommit(endCommitID)
  497. if err != nil {
  498. ctx.ServerError("GetCommit", err)
  499. return
  500. }
  501. setImageCompareContext(ctx, baseCommit, commit)
  502. setPathsCompareContext(ctx, baseCommit, commit, headTarget)
  503. ctx.Data["RequireHighlightJS"] = true
  504. ctx.Data["RequireTribute"] = true
  505. if ctx.Data["Assignees"], err = ctx.Repo.Repository.GetAssignees(); err != nil {
  506. ctx.ServerError("GetAssignees", err)
  507. return
  508. }
  509. ctx.Data["CurrentReview"], err = models.GetCurrentReview(ctx.User, issue)
  510. if err != nil && !models.IsErrReviewNotExist(err) {
  511. ctx.ServerError("GetCurrentReview", err)
  512. return
  513. }
  514. ctx.HTML(200, tplPullFiles)
  515. }
  516. // MergePullRequest response for merging pull request
  517. func MergePullRequest(ctx *context.Context, form auth.MergePullRequestForm) {
  518. issue := checkPullInfo(ctx)
  519. if ctx.Written() {
  520. return
  521. }
  522. if issue.IsClosed {
  523. ctx.NotFound("MergePullRequest", nil)
  524. return
  525. }
  526. pr := issue.PullRequest
  527. if !pr.CanAutoMerge() || pr.HasMerged {
  528. ctx.NotFound("MergePullRequest", nil)
  529. return
  530. }
  531. if pr.IsWorkInProgress() {
  532. ctx.Flash.Error(ctx.Tr("repo.pulls.no_merge_wip"))
  533. ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(pr.Index))
  534. return
  535. }
  536. isPass, err := pull_service.IsPullCommitStatusPass(pr)
  537. if err != nil {
  538. ctx.ServerError("IsPullCommitStatusPass", err)
  539. return
  540. }
  541. if !isPass && !ctx.IsUserRepoAdmin() {
  542. ctx.Flash.Error(ctx.Tr("repo.pulls.no_merge_status_check"))
  543. ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(pr.Index))
  544. return
  545. }
  546. if ctx.HasError() {
  547. ctx.Flash.Error(ctx.Data["ErrorMsg"].(string))
  548. ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(pr.Index))
  549. return
  550. }
  551. message := strings.TrimSpace(form.MergeTitleField)
  552. if len(message) == 0 {
  553. if models.MergeStyle(form.Do) == models.MergeStyleMerge {
  554. message = pr.GetDefaultMergeMessage()
  555. }
  556. if models.MergeStyle(form.Do) == models.MergeStyleRebaseMerge {
  557. message = pr.GetDefaultMergeMessage()
  558. }
  559. if models.MergeStyle(form.Do) == models.MergeStyleSquash {
  560. message = pr.GetDefaultSquashMessage()
  561. }
  562. }
  563. form.MergeMessageField = strings.TrimSpace(form.MergeMessageField)
  564. if len(form.MergeMessageField) > 0 {
  565. message += "\n\n" + form.MergeMessageField
  566. }
  567. pr.Issue = issue
  568. pr.Issue.Repo = ctx.Repo.Repository
  569. noDeps, err := models.IssueNoDependenciesLeft(issue)
  570. if err != nil {
  571. return
  572. }
  573. if !noDeps {
  574. ctx.Flash.Error(ctx.Tr("repo.issues.dependency.pr_close_blocked"))
  575. ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(pr.Index))
  576. return
  577. }
  578. if err = pull_service.Merge(pr, ctx.User, ctx.Repo.GitRepo, models.MergeStyle(form.Do), message); err != nil {
  579. sanitize := func(x string) string {
  580. runes := []rune(x)
  581. if len(runes) > 512 {
  582. x = "..." + string(runes[len(runes)-512:])
  583. }
  584. return strings.Replace(html.EscapeString(x), "\n", "<br>", -1)
  585. }
  586. if models.IsErrInvalidMergeStyle(err) {
  587. ctx.Flash.Error(ctx.Tr("repo.pulls.invalid_merge_option"))
  588. ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(pr.Index))
  589. return
  590. } else if models.IsErrMergeConflicts(err) {
  591. conflictError := err.(models.ErrMergeConflicts)
  592. ctx.Flash.Error(ctx.Tr("repo.pulls.merge_conflict", sanitize(conflictError.StdErr), sanitize(conflictError.StdOut)))
  593. ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(pr.Index))
  594. return
  595. } else if models.IsErrRebaseConflicts(err) {
  596. conflictError := err.(models.ErrRebaseConflicts)
  597. ctx.Flash.Error(ctx.Tr("repo.pulls.rebase_conflict", sanitize(conflictError.CommitSHA), sanitize(conflictError.StdErr), sanitize(conflictError.StdOut)))
  598. ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(pr.Index))
  599. return
  600. } else if models.IsErrMergeUnrelatedHistories(err) {
  601. log.Debug("MergeUnrelatedHistories error: %v", err)
  602. ctx.Flash.Error(ctx.Tr("repo.pulls.unrelated_histories"))
  603. ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(pr.Index))
  604. return
  605. } else if models.IsErrMergePushOutOfDate(err) {
  606. log.Debug("MergePushOutOfDate error: %v", err)
  607. ctx.Flash.Error(ctx.Tr("repo.pulls.merge_out_of_date"))
  608. ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(pr.Index))
  609. return
  610. }
  611. ctx.ServerError("Merge", err)
  612. return
  613. }
  614. if err := stopTimerIfAvailable(ctx.User, issue); err != nil {
  615. ctx.ServerError("CreateOrStopIssueStopwatch", err)
  616. return
  617. }
  618. notification.NotifyMergePullRequest(pr, ctx.User, ctx.Repo.GitRepo)
  619. log.Trace("Pull request merged: %d", pr.ID)
  620. ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(pr.Index))
  621. }
  622. func stopTimerIfAvailable(user *models.User, issue *models.Issue) error {
  623. if models.StopwatchExists(user.ID, issue.ID) {
  624. if err := models.CreateOrStopIssueStopwatch(user, issue); err != nil {
  625. return err
  626. }
  627. }
  628. return nil
  629. }
  630. // CompareAndPullRequestPost response for creating pull request
  631. func CompareAndPullRequestPost(ctx *context.Context, form auth.CreateIssueForm) {
  632. ctx.Data["Title"] = ctx.Tr("repo.pulls.compare_changes")
  633. ctx.Data["PageIsComparePull"] = true
  634. ctx.Data["IsDiffCompare"] = true
  635. ctx.Data["RequireHighlightJS"] = true
  636. ctx.Data["PullRequestWorkInProgressPrefixes"] = setting.Repository.PullRequest.WorkInProgressPrefixes
  637. renderAttachmentSettings(ctx)
  638. var (
  639. repo = ctx.Repo.Repository
  640. attachments []string
  641. )
  642. headUser, headRepo, headGitRepo, prInfo, baseBranch, headBranch := ParseCompareInfo(ctx)
  643. if ctx.Written() {
  644. return
  645. }
  646. defer headGitRepo.Close()
  647. labelIDs, assigneeIDs, milestoneID := ValidateRepoMetas(ctx, form, true)
  648. if ctx.Written() {
  649. return
  650. }
  651. if setting.AttachmentEnabled {
  652. attachments = form.Files
  653. }
  654. if ctx.HasError() {
  655. auth.AssignForm(form, ctx.Data)
  656. // This stage is already stop creating new pull request, so it does not matter if it has
  657. // something to compare or not.
  658. PrepareCompareDiff(ctx, headUser, headRepo, headGitRepo, prInfo, baseBranch, headBranch)
  659. if ctx.Written() {
  660. return
  661. }
  662. ctx.HTML(200, tplCompareDiff)
  663. return
  664. }
  665. if util.IsEmptyString(form.Title) {
  666. PrepareCompareDiff(ctx, headUser, headRepo, headGitRepo, prInfo, baseBranch, headBranch)
  667. if ctx.Written() {
  668. return
  669. }
  670. ctx.RenderWithErr(ctx.Tr("repo.issues.new.title_empty"), tplCompareDiff, form)
  671. return
  672. }
  673. patch, err := headGitRepo.GetPatch(prInfo.MergeBase, headBranch)
  674. if err != nil {
  675. ctx.ServerError("GetPatch", err)
  676. return
  677. }
  678. pullIssue := &models.Issue{
  679. RepoID: repo.ID,
  680. Title: form.Title,
  681. PosterID: ctx.User.ID,
  682. Poster: ctx.User,
  683. MilestoneID: milestoneID,
  684. IsPull: true,
  685. Content: form.Content,
  686. }
  687. pullRequest := &models.PullRequest{
  688. HeadRepoID: headRepo.ID,
  689. BaseRepoID: repo.ID,
  690. HeadBranch: headBranch,
  691. BaseBranch: baseBranch,
  692. HeadRepo: headRepo,
  693. BaseRepo: repo,
  694. MergeBase: prInfo.MergeBase,
  695. Type: models.PullRequestGitea,
  696. }
  697. // FIXME: check error in the case two people send pull request at almost same time, give nice error prompt
  698. // instead of 500.
  699. if err := pull_service.NewPullRequest(repo, pullIssue, labelIDs, attachments, pullRequest, patch, assigneeIDs); err != nil {
  700. if models.IsErrUserDoesNotHaveAccessToRepo(err) {
  701. ctx.Error(400, "UserDoesNotHaveAccessToRepo", err.Error())
  702. return
  703. }
  704. ctx.ServerError("NewPullRequest", err)
  705. return
  706. } else if err := pullRequest.PushToBaseRepo(); err != nil {
  707. ctx.ServerError("PushToBaseRepo", err)
  708. return
  709. }
  710. notification.NotifyNewPullRequest(pullRequest)
  711. log.Trace("Pull request created: %d/%d", repo.ID, pullIssue.ID)
  712. ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(pullIssue.Index))
  713. }
  714. // TriggerTask response for a trigger task request
  715. func TriggerTask(ctx *context.Context) {
  716. pusherID := ctx.QueryInt64("pusher")
  717. branch := ctx.Query("branch")
  718. secret := ctx.Query("secret")
  719. if len(branch) == 0 || len(secret) == 0 || pusherID <= 0 {
  720. ctx.Error(404)
  721. log.Trace("TriggerTask: branch or secret is empty, or pusher ID is not valid")
  722. return
  723. }
  724. owner, repo := parseOwnerAndRepo(ctx)
  725. if ctx.Written() {
  726. return
  727. }
  728. got := []byte(base.EncodeMD5(owner.Salt))
  729. want := []byte(secret)
  730. if subtle.ConstantTimeCompare(got, want) != 1 {
  731. ctx.Error(404)
  732. log.Trace("TriggerTask [%s/%s]: invalid secret", owner.Name, repo.Name)
  733. return
  734. }
  735. pusher, err := models.GetUserByID(pusherID)
  736. if err != nil {
  737. if models.IsErrUserNotExist(err) {
  738. ctx.Error(404)
  739. } else {
  740. ctx.ServerError("GetUserByID", err)
  741. }
  742. return
  743. }
  744. log.Trace("TriggerTask '%s/%s' by %s", repo.Name, branch, pusher.Name)
  745. go pull_service.AddTestPullRequestTask(pusher, repo.ID, branch, true)
  746. ctx.Status(202)
  747. }
  748. // CleanUpPullRequest responses for delete merged branch when PR has been merged
  749. func CleanUpPullRequest(ctx *context.Context) {
  750. issue := checkPullInfo(ctx)
  751. if ctx.Written() {
  752. return
  753. }
  754. pr := issue.PullRequest
  755. // Don't cleanup unmerged and unclosed PRs
  756. if !pr.HasMerged && !issue.IsClosed {
  757. ctx.NotFound("CleanUpPullRequest", nil)
  758. return
  759. }
  760. if err := pr.GetHeadRepo(); err != nil {
  761. ctx.ServerError("GetHeadRepo", err)
  762. return
  763. } else if pr.HeadRepo == nil {
  764. // Forked repository has already been deleted
  765. ctx.NotFound("CleanUpPullRequest", nil)
  766. return
  767. } else if err = pr.GetBaseRepo(); err != nil {
  768. ctx.ServerError("GetBaseRepo", err)
  769. return
  770. } else if err = pr.HeadRepo.GetOwner(); err != nil {
  771. ctx.ServerError("HeadRepo.GetOwner", err)
  772. return
  773. }
  774. perm, err := models.GetUserRepoPermission(pr.HeadRepo, ctx.User)
  775. if err != nil {
  776. ctx.ServerError("GetUserRepoPermission", err)
  777. return
  778. }
  779. if !perm.CanWrite(models.UnitTypeCode) {
  780. ctx.NotFound("CleanUpPullRequest", nil)
  781. return
  782. }
  783. fullBranchName := pr.HeadRepo.Owner.Name + "/" + pr.HeadBranch
  784. gitRepo, err := git.OpenRepository(pr.HeadRepo.RepoPath())
  785. if err != nil {
  786. ctx.ServerError(fmt.Sprintf("OpenRepository[%s]", pr.HeadRepo.RepoPath()), err)
  787. return
  788. }
  789. defer gitRepo.Close()
  790. gitBaseRepo, err := git.OpenRepository(pr.BaseRepo.RepoPath())
  791. if err != nil {
  792. ctx.ServerError(fmt.Sprintf("OpenRepository[%s]", pr.BaseRepo.RepoPath()), err)
  793. return
  794. }
  795. defer gitBaseRepo.Close()
  796. defer func() {
  797. ctx.JSON(200, map[string]interface{}{
  798. "redirect": pr.BaseRepo.Link() + "/pulls/" + com.ToStr(issue.Index),
  799. })
  800. }()
  801. if pr.HeadBranch == pr.HeadRepo.DefaultBranch || !gitRepo.IsBranchExist(pr.HeadBranch) {
  802. ctx.Flash.Error(ctx.Tr("repo.branch.deletion_failed", fullBranchName))
  803. return
  804. }
  805. // Check if branch is not protected
  806. if protected, err := pr.HeadRepo.IsProtectedBranch(pr.HeadBranch, ctx.User); err != nil || protected {
  807. if err != nil {
  808. log.Error("HeadRepo.IsProtectedBranch: %v", err)
  809. }
  810. ctx.Flash.Error(ctx.Tr("repo.branch.deletion_failed", fullBranchName))
  811. return
  812. }
  813. // Check if branch has no new commits
  814. headCommitID, err := gitBaseRepo.GetRefCommitID(pr.GetGitRefName())
  815. if err != nil {
  816. log.Error("GetRefCommitID: %v", err)
  817. ctx.Flash.Error(ctx.Tr("repo.branch.deletion_failed", fullBranchName))
  818. return
  819. }
  820. branchCommitID, err := gitRepo.GetBranchCommitID(pr.HeadBranch)
  821. if err != nil {
  822. log.Error("GetBranchCommitID: %v", err)
  823. ctx.Flash.Error(ctx.Tr("repo.branch.deletion_failed", fullBranchName))
  824. return
  825. }
  826. if headCommitID != branchCommitID {
  827. ctx.Flash.Error(ctx.Tr("repo.branch.delete_branch_has_new_commits", fullBranchName))
  828. return
  829. }
  830. if err := gitRepo.DeleteBranch(pr.HeadBranch, git.DeleteBranchOptions{
  831. Force: true,
  832. }); err != nil {
  833. log.Error("DeleteBranch: %v", err)
  834. ctx.Flash.Error(ctx.Tr("repo.branch.deletion_failed", fullBranchName))
  835. return
  836. }
  837. if err := models.AddDeletePRBranchComment(ctx.User, pr.BaseRepo, issue.ID, pr.HeadBranch); err != nil {
  838. // Do not fail here as branch has already been deleted
  839. log.Error("DeleteBranch: %v", err)
  840. }
  841. ctx.Flash.Success(ctx.Tr("repo.branch.deletion_success", fullBranchName))
  842. }
  843. // DownloadPullDiff render a pull's raw diff
  844. func DownloadPullDiff(ctx *context.Context) {
  845. issue, err := models.GetIssueByIndex(ctx.Repo.Repository.ID, ctx.ParamsInt64(":index"))
  846. if err != nil {
  847. if models.IsErrIssueNotExist(err) {
  848. ctx.NotFound("GetIssueByIndex", err)
  849. } else {
  850. ctx.ServerError("GetIssueByIndex", err)
  851. }
  852. return
  853. }
  854. // Return not found if it's not a pull request
  855. if !issue.IsPull {
  856. ctx.NotFound("DownloadPullDiff",
  857. fmt.Errorf("Issue is not a pull request"))
  858. return
  859. }
  860. if err = issue.LoadPullRequest(); err != nil {
  861. ctx.ServerError("LoadPullRequest", err)
  862. return
  863. }
  864. pr := issue.PullRequest
  865. if err = pr.GetBaseRepo(); err != nil {
  866. ctx.ServerError("GetBaseRepo", err)
  867. return
  868. }
  869. patch, err := pr.BaseRepo.PatchPath(pr.Index)
  870. if err != nil {
  871. ctx.ServerError("PatchPath", err)
  872. return
  873. }
  874. ctx.ServeFileContent(patch)
  875. }
  876. // DownloadPullPatch render a pull's raw patch
  877. func DownloadPullPatch(ctx *context.Context) {
  878. issue, err := models.GetIssueByIndex(ctx.Repo.Repository.ID, ctx.ParamsInt64(":index"))
  879. if err != nil {
  880. if models.IsErrIssueNotExist(err) {
  881. ctx.NotFound("GetIssueByIndex", err)
  882. } else {
  883. ctx.ServerError("GetIssueByIndex", err)
  884. }
  885. return
  886. }
  887. // Return not found if it's not a pull request
  888. if !issue.IsPull {
  889. ctx.NotFound("DownloadPullDiff",
  890. fmt.Errorf("Issue is not a pull request"))
  891. return
  892. }
  893. if err = issue.LoadPullRequest(); err != nil {
  894. ctx.ServerError("LoadPullRequest", err)
  895. return
  896. }
  897. pr := issue.PullRequest
  898. if err = pr.GetHeadRepo(); err != nil {
  899. ctx.ServerError("GetHeadRepo", err)
  900. return
  901. }
  902. headGitRepo, err := git.OpenRepository(pr.HeadRepo.RepoPath())
  903. if err != nil {
  904. ctx.ServerError("OpenRepository", err)
  905. return
  906. }
  907. defer headGitRepo.Close()
  908. patch, err := headGitRepo.GetFormatPatch(pr.MergeBase, pr.HeadBranch)
  909. if err != nil {
  910. ctx.ServerError("GetFormatPatch", err)
  911. return
  912. }
  913. _, err = io.Copy(ctx, patch)
  914. if err != nil {
  915. ctx.ServerError("io.Copy", err)
  916. return
  917. }
  918. }