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.

compare.go 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547
  1. // Copyright 2019 The Gitea Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package repo
  5. import (
  6. "bufio"
  7. "fmt"
  8. "html"
  9. "path"
  10. "path/filepath"
  11. "strings"
  12. "code.gitea.io/gitea/models"
  13. "code.gitea.io/gitea/modules/base"
  14. "code.gitea.io/gitea/modules/context"
  15. "code.gitea.io/gitea/modules/git"
  16. "code.gitea.io/gitea/modules/highlight"
  17. "code.gitea.io/gitea/modules/log"
  18. "code.gitea.io/gitea/modules/setting"
  19. "code.gitea.io/gitea/services/gitdiff"
  20. )
  21. const (
  22. tplCompare base.TplName = "repo/diff/compare"
  23. tplBlobExcerpt base.TplName = "repo/diff/blob_excerpt"
  24. )
  25. // setPathsCompareContext sets context data for source and raw paths
  26. func setPathsCompareContext(ctx *context.Context, base *git.Commit, head *git.Commit, headTarget string) {
  27. sourcePath := setting.AppSubURL + "/%s/src/commit/%s"
  28. rawPath := setting.AppSubURL + "/%s/raw/commit/%s"
  29. ctx.Data["SourcePath"] = fmt.Sprintf(sourcePath, headTarget, head.ID)
  30. ctx.Data["RawPath"] = fmt.Sprintf(rawPath, headTarget, head.ID)
  31. if base != nil {
  32. baseTarget := path.Join(ctx.Repo.Owner.Name, ctx.Repo.Repository.Name)
  33. ctx.Data["BeforeSourcePath"] = fmt.Sprintf(sourcePath, baseTarget, base.ID)
  34. ctx.Data["BeforeRawPath"] = fmt.Sprintf(rawPath, baseTarget, base.ID)
  35. }
  36. }
  37. // setImageCompareContext sets context data that is required by image compare template
  38. func setImageCompareContext(ctx *context.Context, base *git.Commit, head *git.Commit) {
  39. ctx.Data["IsImageFileInHead"] = head.IsImageFile
  40. ctx.Data["IsImageFileInBase"] = base.IsImageFile
  41. ctx.Data["ImageInfoBase"] = func(name string) *git.ImageMetaData {
  42. if base == nil {
  43. return nil
  44. }
  45. result, err := base.ImageInfo(name)
  46. if err != nil {
  47. log.Error("ImageInfo failed: %v", err)
  48. return nil
  49. }
  50. return result
  51. }
  52. ctx.Data["ImageInfo"] = func(name string) *git.ImageMetaData {
  53. result, err := head.ImageInfo(name)
  54. if err != nil {
  55. log.Error("ImageInfo failed: %v", err)
  56. return nil
  57. }
  58. return result
  59. }
  60. }
  61. // ParseCompareInfo parse compare info between two commit for preparing comparing references
  62. func ParseCompareInfo(ctx *context.Context) (*models.User, *models.Repository, *git.Repository, *git.CompareInfo, string, string) {
  63. baseRepo := ctx.Repo.Repository
  64. // Get compared branches information
  65. // format: <base branch>...[<head repo>:]<head branch>
  66. // base<-head: master...head:feature
  67. // same repo: master...feature
  68. var (
  69. headUser *models.User
  70. headBranch string
  71. isSameRepo bool
  72. infoPath string
  73. err error
  74. )
  75. infoPath = ctx.Params("*")
  76. infos := strings.Split(infoPath, "...")
  77. if len(infos) != 2 {
  78. log.Trace("ParseCompareInfo[%d]: not enough compared branches information %s", baseRepo.ID, infos)
  79. ctx.NotFound("CompareAndPullRequest", nil)
  80. return nil, nil, nil, nil, "", ""
  81. }
  82. baseBranch := infos[0]
  83. ctx.Data["BaseBranch"] = baseBranch
  84. // If there is no head repository, it means compare between same repository.
  85. headInfos := strings.Split(infos[1], ":")
  86. if len(headInfos) == 1 {
  87. isSameRepo = true
  88. headUser = ctx.Repo.Owner
  89. headBranch = headInfos[0]
  90. } else if len(headInfos) == 2 {
  91. headUser, err = models.GetUserByName(headInfos[0])
  92. if err != nil {
  93. if models.IsErrUserNotExist(err) {
  94. ctx.NotFound("GetUserByName", nil)
  95. } else {
  96. ctx.ServerError("GetUserByName", err)
  97. }
  98. return nil, nil, nil, nil, "", ""
  99. }
  100. headBranch = headInfos[1]
  101. isSameRepo = headUser.ID == ctx.Repo.Owner.ID
  102. } else {
  103. ctx.NotFound("CompareAndPullRequest", nil)
  104. return nil, nil, nil, nil, "", ""
  105. }
  106. ctx.Data["HeadUser"] = headUser
  107. ctx.Data["HeadBranch"] = headBranch
  108. ctx.Repo.PullRequest.SameRepo = isSameRepo
  109. // Check if base branch is valid.
  110. baseIsCommit := ctx.Repo.GitRepo.IsCommitExist(baseBranch)
  111. baseIsBranch := ctx.Repo.GitRepo.IsBranchExist(baseBranch)
  112. baseIsTag := ctx.Repo.GitRepo.IsTagExist(baseBranch)
  113. if !baseIsCommit && !baseIsBranch && !baseIsTag {
  114. // Check if baseBranch is short sha commit hash
  115. if baseCommit, _ := ctx.Repo.GitRepo.GetCommit(baseBranch); baseCommit != nil {
  116. baseBranch = baseCommit.ID.String()
  117. ctx.Data["BaseBranch"] = baseBranch
  118. baseIsCommit = true
  119. } else {
  120. ctx.NotFound("IsRefExist", nil)
  121. return nil, nil, nil, nil, "", ""
  122. }
  123. }
  124. ctx.Data["BaseIsCommit"] = baseIsCommit
  125. ctx.Data["BaseIsBranch"] = baseIsBranch
  126. ctx.Data["BaseIsTag"] = baseIsTag
  127. // Check if current user has fork of repository or in the same repository.
  128. headRepo, has := models.HasForkedRepo(headUser.ID, baseRepo.ID)
  129. if !has && !isSameRepo {
  130. ctx.Data["PageIsComparePull"] = false
  131. }
  132. var headGitRepo *git.Repository
  133. if isSameRepo {
  134. headRepo = ctx.Repo.Repository
  135. headGitRepo = ctx.Repo.GitRepo
  136. ctx.Data["BaseName"] = headUser.Name
  137. } else {
  138. headGitRepo, err = git.OpenRepository(models.RepoPath(headUser.Name, headRepo.Name))
  139. ctx.Data["BaseName"] = baseRepo.OwnerName
  140. if err != nil {
  141. ctx.ServerError("OpenRepository", err)
  142. return nil, nil, nil, nil, "", ""
  143. }
  144. }
  145. // user should have permission to read baseRepo's codes and pulls, NOT headRepo's
  146. permBase, err := models.GetUserRepoPermission(baseRepo, ctx.User)
  147. if err != nil {
  148. headGitRepo.Close()
  149. ctx.ServerError("GetUserRepoPermission", err)
  150. return nil, nil, nil, nil, "", ""
  151. }
  152. if !permBase.CanRead(models.UnitTypeCode) {
  153. if log.IsTrace() {
  154. log.Trace("Permission Denied: User: %-v cannot read code in Repo: %-v\nUser in baseRepo has Permissions: %-+v",
  155. ctx.User,
  156. baseRepo,
  157. permBase)
  158. }
  159. headGitRepo.Close()
  160. ctx.NotFound("ParseCompareInfo", nil)
  161. return nil, nil, nil, nil, "", ""
  162. }
  163. // user should have permission to read headrepo's codes
  164. permHead, err := models.GetUserRepoPermission(headRepo, ctx.User)
  165. if err != nil {
  166. headGitRepo.Close()
  167. ctx.ServerError("GetUserRepoPermission", err)
  168. return nil, nil, nil, nil, "", ""
  169. }
  170. if !permHead.CanRead(models.UnitTypeCode) {
  171. if log.IsTrace() {
  172. log.Trace("Permission Denied: User: %-v cannot read code in Repo: %-v\nUser in headRepo has Permissions: %-+v",
  173. ctx.User,
  174. headRepo,
  175. permHead)
  176. }
  177. headGitRepo.Close()
  178. ctx.NotFound("ParseCompareInfo", nil)
  179. return nil, nil, nil, nil, "", ""
  180. }
  181. // Check if head branch is valid.
  182. headIsCommit := ctx.Repo.GitRepo.IsCommitExist(headBranch)
  183. headIsBranch := headGitRepo.IsBranchExist(headBranch)
  184. headIsTag := headGitRepo.IsTagExist(headBranch)
  185. if !headIsCommit && !headIsBranch && !headIsTag {
  186. // Check if headBranch is short sha commit hash
  187. if headCommit, _ := ctx.Repo.GitRepo.GetCommit(headBranch); headCommit != nil {
  188. headBranch = headCommit.ID.String()
  189. ctx.Data["HeadBranch"] = headBranch
  190. headIsCommit = true
  191. } else {
  192. headGitRepo.Close()
  193. ctx.NotFound("IsRefExist", nil)
  194. return nil, nil, nil, nil, "", ""
  195. }
  196. }
  197. ctx.Data["HeadIsCommit"] = headIsCommit
  198. ctx.Data["HeadIsBranch"] = headIsBranch
  199. ctx.Data["HeadIsTag"] = headIsTag
  200. // Treat as pull request if both references are branches
  201. if ctx.Data["PageIsComparePull"] == nil {
  202. ctx.Data["PageIsComparePull"] = headIsBranch && baseIsBranch
  203. }
  204. if ctx.Data["PageIsComparePull"] == true && !permBase.CanReadIssuesOrPulls(true) {
  205. if log.IsTrace() {
  206. log.Trace("Permission Denied: User: %-v cannot create/read pull requests in Repo: %-v\nUser in baseRepo has Permissions: %-+v",
  207. ctx.User,
  208. baseRepo,
  209. permBase)
  210. }
  211. headGitRepo.Close()
  212. ctx.NotFound("ParseCompareInfo", nil)
  213. return nil, nil, nil, nil, "", ""
  214. }
  215. compareInfo, err := headGitRepo.GetCompareInfo(models.RepoPath(baseRepo.Owner.Name, baseRepo.Name), baseBranch, headBranch)
  216. if err != nil {
  217. headGitRepo.Close()
  218. ctx.ServerError("GetCompareInfo", err)
  219. return nil, nil, nil, nil, "", ""
  220. }
  221. ctx.Data["BeforeCommitID"] = compareInfo.MergeBase
  222. return headUser, headRepo, headGitRepo, compareInfo, baseBranch, headBranch
  223. }
  224. // PrepareCompareDiff renders compare diff page
  225. func PrepareCompareDiff(
  226. ctx *context.Context,
  227. headUser *models.User,
  228. headRepo *models.Repository,
  229. headGitRepo *git.Repository,
  230. compareInfo *git.CompareInfo,
  231. baseBranch, headBranch string) bool {
  232. var (
  233. repo = ctx.Repo.Repository
  234. err error
  235. title string
  236. )
  237. // Get diff information.
  238. ctx.Data["CommitRepoLink"] = headRepo.Link()
  239. headCommitID := headBranch
  240. if ctx.Data["HeadIsCommit"] == false {
  241. if ctx.Data["HeadIsTag"] == true {
  242. headCommitID, err = headGitRepo.GetTagCommitID(headBranch)
  243. } else {
  244. headCommitID, err = headGitRepo.GetBranchCommitID(headBranch)
  245. }
  246. if err != nil {
  247. ctx.ServerError("GetRefCommitID", err)
  248. return false
  249. }
  250. }
  251. ctx.Data["AfterCommitID"] = headCommitID
  252. if headCommitID == compareInfo.MergeBase {
  253. ctx.Data["IsNothingToCompare"] = true
  254. return true
  255. }
  256. diff, err := gitdiff.GetDiffRange(models.RepoPath(headUser.Name, headRepo.Name),
  257. compareInfo.MergeBase, headCommitID, setting.Git.MaxGitDiffLines,
  258. setting.Git.MaxGitDiffLineCharacters, setting.Git.MaxGitDiffFiles)
  259. if err != nil {
  260. ctx.ServerError("GetDiffRange", err)
  261. return false
  262. }
  263. ctx.Data["Diff"] = diff
  264. ctx.Data["DiffNotAvailable"] = diff.NumFiles() == 0
  265. headCommit, err := headGitRepo.GetCommit(headCommitID)
  266. if err != nil {
  267. ctx.ServerError("GetCommit", err)
  268. return false
  269. }
  270. baseGitRepo := ctx.Repo.GitRepo
  271. baseCommitID := baseBranch
  272. if ctx.Data["BaseIsCommit"] == false {
  273. if ctx.Data["BaseIsTag"] == true {
  274. baseCommitID, err = baseGitRepo.GetTagCommitID(baseBranch)
  275. } else {
  276. baseCommitID, err = baseGitRepo.GetBranchCommitID(baseBranch)
  277. }
  278. if err != nil {
  279. ctx.ServerError("GetRefCommitID", err)
  280. return false
  281. }
  282. }
  283. baseCommit, err := baseGitRepo.GetCommit(baseCommitID)
  284. if err != nil {
  285. ctx.ServerError("GetCommit", err)
  286. return false
  287. }
  288. compareInfo.Commits = models.ValidateCommitsWithEmails(compareInfo.Commits)
  289. compareInfo.Commits = models.ParseCommitsWithSignature(compareInfo.Commits)
  290. compareInfo.Commits = models.ParseCommitsWithStatus(compareInfo.Commits, headRepo)
  291. ctx.Data["Commits"] = compareInfo.Commits
  292. ctx.Data["CommitCount"] = compareInfo.Commits.Len()
  293. if ctx.Data["CommitCount"] == 0 {
  294. ctx.Data["PageIsComparePull"] = false
  295. }
  296. if compareInfo.Commits.Len() == 1 {
  297. c := compareInfo.Commits.Front().Value.(models.SignCommitWithStatuses)
  298. title = strings.TrimSpace(c.UserCommit.Summary())
  299. body := strings.Split(strings.TrimSpace(c.UserCommit.Message()), "\n")
  300. if len(body) > 1 {
  301. ctx.Data["content"] = strings.Join(body[1:], "\n")
  302. }
  303. } else {
  304. title = headBranch
  305. }
  306. ctx.Data["title"] = title
  307. ctx.Data["Username"] = headUser.Name
  308. ctx.Data["Reponame"] = headRepo.Name
  309. setImageCompareContext(ctx, baseCommit, headCommit)
  310. headTarget := path.Join(headUser.Name, repo.Name)
  311. setPathsCompareContext(ctx, baseCommit, headCommit, headTarget)
  312. return false
  313. }
  314. // parseBaseRepoInfo parse base repository if current repo is forked.
  315. // The "base" here means the repository where current repo forks from,
  316. // not the repository fetch from current URL.
  317. func parseBaseRepoInfo(ctx *context.Context, repo *models.Repository) error {
  318. if !repo.IsFork {
  319. return nil
  320. }
  321. if err := repo.GetBaseRepo(); err != nil {
  322. return err
  323. }
  324. if err := repo.BaseRepo.GetOwnerName(); err != nil {
  325. return err
  326. }
  327. baseGitRepo, err := git.OpenRepository(models.RepoPath(repo.BaseRepo.OwnerName, repo.BaseRepo.Name))
  328. if err != nil {
  329. return err
  330. }
  331. defer baseGitRepo.Close()
  332. ctx.Data["BaseRepoBranches"], err = baseGitRepo.GetBranches()
  333. if err != nil {
  334. return err
  335. }
  336. return nil
  337. }
  338. // CompareDiff show different from one commit to another commit
  339. func CompareDiff(ctx *context.Context) {
  340. headUser, headRepo, headGitRepo, compareInfo, baseBranch, headBranch := ParseCompareInfo(ctx)
  341. if ctx.Written() {
  342. return
  343. }
  344. defer headGitRepo.Close()
  345. if err := parseBaseRepoInfo(ctx, headRepo); err != nil {
  346. ctx.ServerError("parseBaseRepoInfo", err)
  347. return
  348. }
  349. nothingToCompare := PrepareCompareDiff(ctx, headUser, headRepo, headGitRepo, compareInfo, baseBranch, headBranch)
  350. if ctx.Written() {
  351. return
  352. }
  353. if ctx.Data["PageIsComparePull"] == true {
  354. headBranches, err := headGitRepo.GetBranches()
  355. if err != nil {
  356. ctx.ServerError("GetBranches", err)
  357. return
  358. }
  359. ctx.Data["HeadBranches"] = headBranches
  360. pr, err := models.GetUnmergedPullRequest(headRepo.ID, ctx.Repo.Repository.ID, headBranch, baseBranch)
  361. if err != nil {
  362. if !models.IsErrPullRequestNotExist(err) {
  363. ctx.ServerError("GetUnmergedPullRequest", err)
  364. return
  365. }
  366. } else {
  367. ctx.Data["HasPullRequest"] = true
  368. ctx.Data["PullRequest"] = pr
  369. ctx.HTML(200, tplCompareDiff)
  370. return
  371. }
  372. if !nothingToCompare {
  373. // Setup information for new form.
  374. RetrieveRepoMetas(ctx, ctx.Repo.Repository)
  375. if ctx.Written() {
  376. return
  377. }
  378. }
  379. }
  380. beforeCommitID := ctx.Data["BeforeCommitID"].(string)
  381. afterCommitID := ctx.Data["AfterCommitID"].(string)
  382. ctx.Data["Title"] = "Comparing " + base.ShortSha(beforeCommitID) + "..." + base.ShortSha(afterCommitID)
  383. ctx.Data["IsRepoToolbarCommits"] = true
  384. ctx.Data["IsDiffCompare"] = true
  385. ctx.Data["RequireHighlightJS"] = true
  386. ctx.Data["RequireTribute"] = true
  387. ctx.Data["PullRequestWorkInProgressPrefixes"] = setting.Repository.PullRequest.WorkInProgressPrefixes
  388. setTemplateIfExists(ctx, pullRequestTemplateKey, pullRequestTemplateCandidates)
  389. renderAttachmentSettings(ctx)
  390. ctx.HTML(200, tplCompare)
  391. }
  392. // ExcerptBlob render blob excerpt contents
  393. func ExcerptBlob(ctx *context.Context) {
  394. commitID := ctx.Params("sha")
  395. lastLeft := ctx.QueryInt("last_left")
  396. lastRight := ctx.QueryInt("last_right")
  397. idxLeft := ctx.QueryInt("left")
  398. idxRight := ctx.QueryInt("right")
  399. leftHunkSize := ctx.QueryInt("left_hunk_size")
  400. rightHunkSize := ctx.QueryInt("right_hunk_size")
  401. anchor := ctx.Query("anchor")
  402. direction := ctx.Query("direction")
  403. filePath := ctx.Query("path")
  404. gitRepo := ctx.Repo.GitRepo
  405. chunkSize := gitdiff.BlobExceprtChunkSize
  406. commit, err := gitRepo.GetCommit(commitID)
  407. if err != nil {
  408. ctx.Error(500, "GetCommit")
  409. return
  410. }
  411. section := &gitdiff.DiffSection{
  412. Name: filePath,
  413. }
  414. if direction == "up" && (idxLeft-lastLeft) > chunkSize {
  415. idxLeft -= chunkSize
  416. idxRight -= chunkSize
  417. leftHunkSize += chunkSize
  418. rightHunkSize += chunkSize
  419. section.Lines, err = getExcerptLines(commit, filePath, idxLeft-1, idxRight-1, chunkSize)
  420. } else if direction == "down" && (idxLeft-lastLeft) > chunkSize {
  421. section.Lines, err = getExcerptLines(commit, filePath, lastLeft, lastRight, chunkSize)
  422. lastLeft += chunkSize
  423. lastRight += chunkSize
  424. } else {
  425. section.Lines, err = getExcerptLines(commit, filePath, lastLeft, lastRight, idxRight-lastRight-1)
  426. leftHunkSize = 0
  427. rightHunkSize = 0
  428. idxLeft = lastLeft
  429. idxRight = lastRight
  430. }
  431. if err != nil {
  432. ctx.Error(500, "getExcerptLines")
  433. return
  434. }
  435. if idxRight > lastRight {
  436. lineText := " "
  437. if rightHunkSize > 0 || leftHunkSize > 0 {
  438. lineText = fmt.Sprintf("@@ -%d,%d +%d,%d @@\n", idxLeft, leftHunkSize, idxRight, rightHunkSize)
  439. }
  440. lineText = html.EscapeString(lineText)
  441. lineSection := &gitdiff.DiffLine{
  442. Type: gitdiff.DiffLineSection,
  443. Content: lineText,
  444. SectionInfo: &gitdiff.DiffLineSectionInfo{
  445. Path: filePath,
  446. LastLeftIdx: lastLeft,
  447. LastRightIdx: lastRight,
  448. LeftIdx: idxLeft,
  449. RightIdx: idxRight,
  450. LeftHunkSize: leftHunkSize,
  451. RightHunkSize: rightHunkSize,
  452. }}
  453. if direction == "up" {
  454. section.Lines = append([]*gitdiff.DiffLine{lineSection}, section.Lines...)
  455. } else if direction == "down" {
  456. section.Lines = append(section.Lines, lineSection)
  457. }
  458. }
  459. ctx.Data["section"] = section
  460. ctx.Data["fileName"] = filePath
  461. ctx.Data["highlightClass"] = highlight.FileNameToHighlightClass(filepath.Base(filePath))
  462. ctx.Data["AfterCommitID"] = commitID
  463. ctx.Data["Anchor"] = anchor
  464. ctx.HTML(200, tplBlobExcerpt)
  465. }
  466. func getExcerptLines(commit *git.Commit, filePath string, idxLeft int, idxRight int, chunkSize int) ([]*gitdiff.DiffLine, error) {
  467. blob, err := commit.Tree.GetBlobByPath(filePath)
  468. if err != nil {
  469. return nil, err
  470. }
  471. reader, err := blob.DataAsync()
  472. if err != nil {
  473. return nil, err
  474. }
  475. defer reader.Close()
  476. scanner := bufio.NewScanner(reader)
  477. var diffLines []*gitdiff.DiffLine
  478. for line := 0; line < idxRight+chunkSize; line++ {
  479. if ok := scanner.Scan(); !ok {
  480. break
  481. }
  482. if line < idxRight {
  483. continue
  484. }
  485. lineText := scanner.Text()
  486. diffLine := &gitdiff.DiffLine{
  487. LeftIdx: idxLeft + (line - idxRight) + 1,
  488. RightIdx: line + 1,
  489. Type: gitdiff.DiffLinePlain,
  490. Content: " " + lineText,
  491. }
  492. diffLines = append(diffLines, diffLine)
  493. }
  494. return diffLines, nil
  495. }