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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548
  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. defer headGitRepo.Close()
  145. }
  146. // user should have permission to read baseRepo's codes and pulls, NOT headRepo's
  147. permBase, err := models.GetUserRepoPermission(baseRepo, ctx.User)
  148. if err != nil {
  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. ctx.NotFound("ParseCompareInfo", nil)
  160. return nil, nil, nil, nil, "", ""
  161. }
  162. if !isSameRepo {
  163. // user should have permission to read headrepo's codes
  164. permHead, err := models.GetUserRepoPermission(headRepo, ctx.User)
  165. if err != nil {
  166. ctx.ServerError("GetUserRepoPermission", err)
  167. return nil, nil, nil, nil, "", ""
  168. }
  169. if !permHead.CanRead(models.UnitTypeCode) {
  170. if log.IsTrace() {
  171. log.Trace("Permission Denied: User: %-v cannot read code in Repo: %-v\nUser in headRepo has Permissions: %-+v",
  172. ctx.User,
  173. headRepo,
  174. permHead)
  175. }
  176. ctx.NotFound("ParseCompareInfo", nil)
  177. return nil, nil, nil, nil, "", ""
  178. }
  179. }
  180. // Check if head branch is valid.
  181. headIsCommit := headGitRepo.IsCommitExist(headBranch)
  182. headIsBranch := headGitRepo.IsBranchExist(headBranch)
  183. headIsTag := headGitRepo.IsTagExist(headBranch)
  184. if !headIsCommit && !headIsBranch && !headIsTag {
  185. // Check if headBranch is short sha commit hash
  186. if headCommit, _ := headGitRepo.GetCommit(headBranch); headCommit != nil {
  187. headBranch = headCommit.ID.String()
  188. ctx.Data["HeadBranch"] = headBranch
  189. headIsCommit = true
  190. } else {
  191. ctx.NotFound("IsRefExist", nil)
  192. return nil, nil, nil, nil, "", ""
  193. }
  194. }
  195. ctx.Data["HeadIsCommit"] = headIsCommit
  196. ctx.Data["HeadIsBranch"] = headIsBranch
  197. ctx.Data["HeadIsTag"] = headIsTag
  198. // Treat as pull request if both references are branches
  199. if ctx.Data["PageIsComparePull"] == nil {
  200. ctx.Data["PageIsComparePull"] = headIsBranch && baseIsBranch
  201. }
  202. if ctx.Data["PageIsComparePull"] == true && !permBase.CanReadIssuesOrPulls(true) {
  203. if log.IsTrace() {
  204. log.Trace("Permission Denied: User: %-v cannot create/read pull requests in Repo: %-v\nUser in baseRepo has Permissions: %-+v",
  205. ctx.User,
  206. baseRepo,
  207. permBase)
  208. }
  209. ctx.NotFound("ParseCompareInfo", nil)
  210. return nil, nil, nil, nil, "", ""
  211. }
  212. compareInfo, err := headGitRepo.GetCompareInfo(baseRepo.RepoPath(), baseBranch, headBranch)
  213. if err != nil {
  214. ctx.ServerError("GetCompareInfo", err)
  215. return nil, nil, nil, nil, "", ""
  216. }
  217. ctx.Data["BeforeCommitID"] = compareInfo.MergeBase
  218. return headUser, headRepo, headGitRepo, compareInfo, baseBranch, headBranch
  219. }
  220. // PrepareCompareDiff renders compare diff page
  221. func PrepareCompareDiff(
  222. ctx *context.Context,
  223. headUser *models.User,
  224. headRepo *models.Repository,
  225. headGitRepo *git.Repository,
  226. compareInfo *git.CompareInfo,
  227. baseBranch, headBranch string) bool {
  228. var (
  229. repo = ctx.Repo.Repository
  230. err error
  231. title string
  232. )
  233. // Get diff information.
  234. ctx.Data["CommitRepoLink"] = headRepo.Link()
  235. headCommitID := headBranch
  236. if ctx.Data["HeadIsCommit"] == false {
  237. if ctx.Data["HeadIsTag"] == true {
  238. headCommitID, err = headGitRepo.GetTagCommitID(headBranch)
  239. } else {
  240. headCommitID, err = headGitRepo.GetBranchCommitID(headBranch)
  241. }
  242. if err != nil {
  243. ctx.ServerError("GetRefCommitID", err)
  244. return false
  245. }
  246. }
  247. ctx.Data["AfterCommitID"] = headCommitID
  248. if headCommitID == compareInfo.MergeBase {
  249. ctx.Data["IsNothingToCompare"] = true
  250. return true
  251. }
  252. diff, err := gitdiff.GetDiffRange(models.RepoPath(headUser.Name, headRepo.Name),
  253. compareInfo.MergeBase, headCommitID, setting.Git.MaxGitDiffLines,
  254. setting.Git.MaxGitDiffLineCharacters, setting.Git.MaxGitDiffFiles)
  255. if err != nil {
  256. ctx.ServerError("GetDiffRange", err)
  257. return false
  258. }
  259. ctx.Data["Diff"] = diff
  260. ctx.Data["DiffNotAvailable"] = diff.NumFiles() == 0
  261. headCommit, err := headGitRepo.GetCommit(headCommitID)
  262. if err != nil {
  263. ctx.ServerError("GetCommit", err)
  264. return false
  265. }
  266. baseGitRepo := ctx.Repo.GitRepo
  267. baseCommitID := baseBranch
  268. if ctx.Data["BaseIsCommit"] == false {
  269. if ctx.Data["BaseIsTag"] == true {
  270. baseCommitID, err = baseGitRepo.GetTagCommitID(baseBranch)
  271. } else {
  272. baseCommitID, err = baseGitRepo.GetBranchCommitID(baseBranch)
  273. }
  274. if err != nil {
  275. ctx.ServerError("GetRefCommitID", err)
  276. return false
  277. }
  278. }
  279. baseCommit, err := baseGitRepo.GetCommit(baseCommitID)
  280. if err != nil {
  281. ctx.ServerError("GetCommit", err)
  282. return false
  283. }
  284. compareInfo.Commits = models.ValidateCommitsWithEmails(compareInfo.Commits)
  285. compareInfo.Commits = models.ParseCommitsWithSignature(compareInfo.Commits, headRepo)
  286. compareInfo.Commits = models.ParseCommitsWithStatus(compareInfo.Commits, headRepo)
  287. ctx.Data["Commits"] = compareInfo.Commits
  288. ctx.Data["CommitCount"] = compareInfo.Commits.Len()
  289. if ctx.Data["CommitCount"] == 0 {
  290. ctx.Data["PageIsComparePull"] = false
  291. }
  292. if compareInfo.Commits.Len() == 1 {
  293. c := compareInfo.Commits.Front().Value.(models.SignCommitWithStatuses)
  294. title = strings.TrimSpace(c.UserCommit.Summary())
  295. body := strings.Split(strings.TrimSpace(c.UserCommit.Message()), "\n")
  296. if len(body) > 1 {
  297. ctx.Data["content"] = strings.Join(body[1:], "\n")
  298. }
  299. } else {
  300. title = headBranch
  301. }
  302. ctx.Data["title"] = title
  303. ctx.Data["Username"] = headUser.Name
  304. ctx.Data["Reponame"] = headRepo.Name
  305. setImageCompareContext(ctx, baseCommit, headCommit)
  306. headTarget := path.Join(headUser.Name, repo.Name)
  307. setPathsCompareContext(ctx, baseCommit, headCommit, headTarget)
  308. return false
  309. }
  310. // parseBaseRepoInfo parse base repository if current repo is forked.
  311. // The "base" here means the repository where current repo forks from,
  312. // not the repository fetch from current URL.
  313. func parseBaseRepoInfo(ctx *context.Context, repo *models.Repository) error {
  314. if !repo.IsFork {
  315. return nil
  316. }
  317. if err := repo.GetBaseRepo(); err != nil {
  318. return err
  319. }
  320. baseGitRepo, err := git.OpenRepository(repo.BaseRepo.RepoPath())
  321. if err != nil {
  322. return err
  323. }
  324. defer baseGitRepo.Close()
  325. ctx.Data["BaseRepoBranches"], err = baseGitRepo.GetBranches()
  326. if err != nil {
  327. return err
  328. }
  329. return nil
  330. }
  331. // CompareDiff show different from one commit to another commit
  332. func CompareDiff(ctx *context.Context) {
  333. headUser, headRepo, headGitRepo, compareInfo, baseBranch, headBranch := ParseCompareInfo(ctx)
  334. if ctx.Written() {
  335. return
  336. }
  337. defer headGitRepo.Close()
  338. var err error
  339. if err = parseBaseRepoInfo(ctx, headRepo); err != nil {
  340. ctx.ServerError("parseBaseRepoInfo", err)
  341. return
  342. }
  343. nothingToCompare := PrepareCompareDiff(ctx, headUser, headRepo, headGitRepo, compareInfo, baseBranch, headBranch)
  344. if ctx.Written() {
  345. return
  346. }
  347. if ctx.Data["PageIsComparePull"] == true {
  348. headBranches, err := headGitRepo.GetBranches()
  349. if err != nil {
  350. ctx.ServerError("GetBranches", err)
  351. return
  352. }
  353. ctx.Data["HeadBranches"] = headBranches
  354. pr, err := models.GetUnmergedPullRequest(headRepo.ID, ctx.Repo.Repository.ID, headBranch, baseBranch)
  355. if err != nil {
  356. if !models.IsErrPullRequestNotExist(err) {
  357. ctx.ServerError("GetUnmergedPullRequest", err)
  358. return
  359. }
  360. } else {
  361. ctx.Data["HasPullRequest"] = true
  362. ctx.Data["PullRequest"] = pr
  363. ctx.HTML(200, tplCompareDiff)
  364. return
  365. }
  366. if !nothingToCompare {
  367. // Setup information for new form.
  368. RetrieveRepoMetas(ctx, ctx.Repo.Repository, true)
  369. if ctx.Written() {
  370. return
  371. }
  372. }
  373. }
  374. beforeCommitID := ctx.Data["BeforeCommitID"].(string)
  375. afterCommitID := ctx.Data["AfterCommitID"].(string)
  376. if ctx.Data["Assignees"], err = ctx.Repo.Repository.GetAssignees(); err != nil {
  377. ctx.ServerError("GetAssignees", err)
  378. return
  379. }
  380. ctx.Data["Title"] = "Comparing " + base.ShortSha(beforeCommitID) + "..." + base.ShortSha(afterCommitID)
  381. ctx.Data["IsRepoToolbarCommits"] = true
  382. ctx.Data["IsDiffCompare"] = true
  383. ctx.Data["RequireHighlightJS"] = true
  384. ctx.Data["RequireTribute"] = true
  385. ctx.Data["RequireSimpleMDE"] = true
  386. ctx.Data["PullRequestWorkInProgressPrefixes"] = setting.Repository.PullRequest.WorkInProgressPrefixes
  387. setTemplateIfExists(ctx, pullRequestTemplateKey, pullRequestTemplateCandidates)
  388. renderAttachmentSettings(ctx)
  389. ctx.HTML(200, tplCompare)
  390. }
  391. // ExcerptBlob render blob excerpt contents
  392. func ExcerptBlob(ctx *context.Context) {
  393. commitID := ctx.Params("sha")
  394. lastLeft := ctx.QueryInt("last_left")
  395. lastRight := ctx.QueryInt("last_right")
  396. idxLeft := ctx.QueryInt("left")
  397. idxRight := ctx.QueryInt("right")
  398. leftHunkSize := ctx.QueryInt("left_hunk_size")
  399. rightHunkSize := ctx.QueryInt("right_hunk_size")
  400. anchor := ctx.Query("anchor")
  401. direction := ctx.Query("direction")
  402. filePath := ctx.Query("path")
  403. gitRepo := ctx.Repo.GitRepo
  404. chunkSize := gitdiff.BlobExceprtChunkSize
  405. commit, err := gitRepo.GetCommit(commitID)
  406. if err != nil {
  407. ctx.Error(500, "GetCommit")
  408. return
  409. }
  410. section := &gitdiff.DiffSection{
  411. Name: filePath,
  412. }
  413. if direction == "up" && (idxLeft-lastLeft) > chunkSize {
  414. idxLeft -= chunkSize
  415. idxRight -= chunkSize
  416. leftHunkSize += chunkSize
  417. rightHunkSize += chunkSize
  418. section.Lines, err = getExcerptLines(commit, filePath, idxLeft-1, idxRight-1, chunkSize)
  419. } else if direction == "down" && (idxLeft-lastLeft) > chunkSize {
  420. section.Lines, err = getExcerptLines(commit, filePath, lastLeft, lastRight, chunkSize)
  421. lastLeft += chunkSize
  422. lastRight += chunkSize
  423. } else {
  424. section.Lines, err = getExcerptLines(commit, filePath, lastLeft, lastRight, idxRight-lastRight-1)
  425. leftHunkSize = 0
  426. rightHunkSize = 0
  427. idxLeft = lastLeft
  428. idxRight = lastRight
  429. }
  430. if err != nil {
  431. ctx.Error(500, "getExcerptLines")
  432. return
  433. }
  434. if idxRight > lastRight {
  435. lineText := " "
  436. if rightHunkSize > 0 || leftHunkSize > 0 {
  437. lineText = fmt.Sprintf("@@ -%d,%d +%d,%d @@\n", idxLeft, leftHunkSize, idxRight, rightHunkSize)
  438. }
  439. lineText = html.EscapeString(lineText)
  440. lineSection := &gitdiff.DiffLine{
  441. Type: gitdiff.DiffLineSection,
  442. Content: lineText,
  443. SectionInfo: &gitdiff.DiffLineSectionInfo{
  444. Path: filePath,
  445. LastLeftIdx: lastLeft,
  446. LastRightIdx: lastRight,
  447. LeftIdx: idxLeft,
  448. RightIdx: idxRight,
  449. LeftHunkSize: leftHunkSize,
  450. RightHunkSize: rightHunkSize,
  451. }}
  452. if direction == "up" {
  453. section.Lines = append([]*gitdiff.DiffLine{lineSection}, section.Lines...)
  454. } else if direction == "down" {
  455. section.Lines = append(section.Lines, lineSection)
  456. }
  457. }
  458. ctx.Data["section"] = section
  459. ctx.Data["fileName"] = filePath
  460. ctx.Data["highlightClass"] = highlight.FileNameToHighlightClass(filepath.Base(filePath))
  461. ctx.Data["AfterCommitID"] = commitID
  462. ctx.Data["Anchor"] = anchor
  463. ctx.HTML(200, tplBlobExcerpt)
  464. }
  465. func getExcerptLines(commit *git.Commit, filePath string, idxLeft int, idxRight int, chunkSize int) ([]*gitdiff.DiffLine, error) {
  466. blob, err := commit.Tree.GetBlobByPath(filePath)
  467. if err != nil {
  468. return nil, err
  469. }
  470. reader, err := blob.DataAsync()
  471. if err != nil {
  472. return nil, err
  473. }
  474. defer reader.Close()
  475. scanner := bufio.NewScanner(reader)
  476. var diffLines []*gitdiff.DiffLine
  477. for line := 0; line < idxRight+chunkSize; line++ {
  478. if ok := scanner.Scan(); !ok {
  479. break
  480. }
  481. if line < idxRight {
  482. continue
  483. }
  484. lineText := scanner.Text()
  485. diffLine := &gitdiff.DiffLine{
  486. LeftIdx: idxLeft + (line - idxRight) + 1,
  487. RightIdx: line + 1,
  488. Type: gitdiff.DiffLinePlain,
  489. Content: " " + lineText,
  490. }
  491. diffLines = append(diffLines, diffLine)
  492. }
  493. return diffLines, nil
  494. }