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

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