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