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

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