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

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