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 30KB

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