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

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