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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691
  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. "strings"
  11. "code.gitea.io/gitea/models"
  12. "code.gitea.io/gitea/modules/base"
  13. "code.gitea.io/gitea/modules/context"
  14. "code.gitea.io/gitea/modules/git"
  15. "code.gitea.io/gitea/modules/log"
  16. "code.gitea.io/gitea/modules/setting"
  17. "code.gitea.io/gitea/services/gitdiff"
  18. )
  19. const (
  20. tplCompare base.TplName = "repo/diff/compare"
  21. tplBlobExcerpt base.TplName = "repo/diff/blob_excerpt"
  22. )
  23. // setPathsCompareContext sets context data for source and raw paths
  24. func setPathsCompareContext(ctx *context.Context, base *git.Commit, head *git.Commit, headTarget string) {
  25. sourcePath := setting.AppSubURL + "/%s/src/commit/%s"
  26. rawPath := setting.AppSubURL + "/%s/raw/commit/%s"
  27. ctx.Data["SourcePath"] = fmt.Sprintf(sourcePath, headTarget, head.ID)
  28. ctx.Data["RawPath"] = fmt.Sprintf(rawPath, headTarget, head.ID)
  29. if base != nil {
  30. baseTarget := path.Join(ctx.Repo.Owner.Name, ctx.Repo.Repository.Name)
  31. ctx.Data["BeforeSourcePath"] = fmt.Sprintf(sourcePath, baseTarget, base.ID)
  32. ctx.Data["BeforeRawPath"] = fmt.Sprintf(rawPath, baseTarget, base.ID)
  33. }
  34. }
  35. // setImageCompareContext sets context data that is required by image compare template
  36. func setImageCompareContext(ctx *context.Context, base *git.Commit, head *git.Commit) {
  37. ctx.Data["IsImageFileInHead"] = head.IsImageFile
  38. ctx.Data["IsImageFileInBase"] = base.IsImageFile
  39. ctx.Data["ImageInfoBase"] = func(name string) *git.ImageMetaData {
  40. if base == nil {
  41. return nil
  42. }
  43. result, err := base.ImageInfo(name)
  44. if err != nil {
  45. log.Error("ImageInfo failed: %v", err)
  46. return nil
  47. }
  48. return result
  49. }
  50. ctx.Data["ImageInfo"] = func(name string) *git.ImageMetaData {
  51. result, err := head.ImageInfo(name)
  52. if err != nil {
  53. log.Error("ImageInfo failed: %v", err)
  54. return nil
  55. }
  56. return result
  57. }
  58. }
  59. // ParseCompareInfo parse compare info between two commit for preparing comparing references
  60. func ParseCompareInfo(ctx *context.Context) (*models.User, *models.Repository, *git.Repository, *git.CompareInfo, string, string) {
  61. baseRepo := ctx.Repo.Repository
  62. // Get compared branches information
  63. // A full compare url is of the form:
  64. //
  65. // 1. /{:baseOwner}/{:baseRepoName}/compare/{:baseBranch}...{:headBranch}
  66. // 2. /{:baseOwner}/{:baseRepoName}/compare/{:baseBranch}...{:headOwner}:{:headBranch}
  67. // 3. /{:baseOwner}/{:baseRepoName}/compare/{:baseBranch}...{:headOwner}/{:headRepoName}:{:headBranch}
  68. //
  69. // Here we obtain the infoPath "{:baseBranch}...[{:headOwner}/{:headRepoName}:]{:headBranch}" as ctx.Params("*")
  70. // with the :baseRepo in ctx.Repo.
  71. //
  72. // Note: Generally :headRepoName is not provided here - we are only passed :headOwner.
  73. //
  74. // How do we determine the :headRepo?
  75. //
  76. // 1. If :headOwner is not set then the :headRepo = :baseRepo
  77. // 2. If :headOwner is set - then look for the fork of :baseRepo owned by :headOwner
  78. // 3. But... :baseRepo could be a fork of :headOwner's repo - so check that
  79. // 4. Now, :baseRepo and :headRepos could be forks of the same repo - so check that
  80. //
  81. // format: <base branch>...[<head repo>:]<head branch>
  82. // base<-head: master...head:feature
  83. // same repo: master...feature
  84. var (
  85. headUser *models.User
  86. headRepo *models.Repository
  87. headBranch string
  88. isSameRepo bool
  89. infoPath string
  90. err error
  91. )
  92. infoPath = ctx.Params("*")
  93. infos := strings.SplitN(infoPath, "...", 2)
  94. if len(infos) != 2 {
  95. log.Trace("ParseCompareInfo[%d]: not enough compared branches information %s", baseRepo.ID, infos)
  96. ctx.NotFound("CompareAndPullRequest", nil)
  97. return nil, nil, nil, nil, "", ""
  98. }
  99. ctx.Data["BaseName"] = baseRepo.OwnerName
  100. baseBranch := infos[0]
  101. ctx.Data["BaseBranch"] = baseBranch
  102. // If there is no head repository, it means compare between same repository.
  103. headInfos := strings.Split(infos[1], ":")
  104. if len(headInfos) == 1 {
  105. isSameRepo = true
  106. headUser = ctx.Repo.Owner
  107. headBranch = headInfos[0]
  108. } else if len(headInfos) == 2 {
  109. headInfosSplit := strings.Split(headInfos[0], "/")
  110. if len(headInfosSplit) == 1 {
  111. headUser, err = models.GetUserByName(headInfos[0])
  112. if err != nil {
  113. if models.IsErrUserNotExist(err) {
  114. ctx.NotFound("GetUserByName", nil)
  115. } else {
  116. ctx.ServerError("GetUserByName", err)
  117. }
  118. return nil, nil, nil, nil, "", ""
  119. }
  120. headBranch = headInfos[1]
  121. isSameRepo = headUser.ID == ctx.Repo.Owner.ID
  122. if isSameRepo {
  123. headRepo = baseRepo
  124. }
  125. } else {
  126. headRepo, err = models.GetRepositoryByOwnerAndName(headInfosSplit[0], headInfosSplit[1])
  127. if err != nil {
  128. if models.IsErrRepoNotExist(err) {
  129. ctx.NotFound("GetRepositoryByOwnerAndName", nil)
  130. } else {
  131. ctx.ServerError("GetRepositoryByOwnerAndName", err)
  132. }
  133. return nil, nil, nil, nil, "", ""
  134. }
  135. if err := headRepo.GetOwner(); err != nil {
  136. if models.IsErrUserNotExist(err) {
  137. ctx.NotFound("GetUserByName", nil)
  138. } else {
  139. ctx.ServerError("GetUserByName", err)
  140. }
  141. return nil, nil, nil, nil, "", ""
  142. }
  143. headBranch = headInfos[1]
  144. headUser = headRepo.Owner
  145. isSameRepo = headRepo.ID == ctx.Repo.Repository.ID
  146. }
  147. } else {
  148. ctx.NotFound("CompareAndPullRequest", nil)
  149. return nil, nil, nil, nil, "", ""
  150. }
  151. ctx.Data["HeadUser"] = headUser
  152. ctx.Data["HeadBranch"] = headBranch
  153. ctx.Repo.PullRequest.SameRepo = isSameRepo
  154. // Check if base branch is valid.
  155. baseIsCommit := ctx.Repo.GitRepo.IsCommitExist(baseBranch)
  156. baseIsBranch := ctx.Repo.GitRepo.IsBranchExist(baseBranch)
  157. baseIsTag := ctx.Repo.GitRepo.IsTagExist(baseBranch)
  158. if !baseIsCommit && !baseIsBranch && !baseIsTag {
  159. // Check if baseBranch is short sha commit hash
  160. if baseCommit, _ := ctx.Repo.GitRepo.GetCommit(baseBranch); baseCommit != nil {
  161. baseBranch = baseCommit.ID.String()
  162. ctx.Data["BaseBranch"] = baseBranch
  163. baseIsCommit = true
  164. } else {
  165. ctx.NotFound("IsRefExist", nil)
  166. return nil, nil, nil, nil, "", ""
  167. }
  168. }
  169. ctx.Data["BaseIsCommit"] = baseIsCommit
  170. ctx.Data["BaseIsBranch"] = baseIsBranch
  171. ctx.Data["BaseIsTag"] = baseIsTag
  172. // Now we have the repository that represents the base
  173. // The current base and head repositories and branches may not
  174. // actually be the intended branches that the user wants to
  175. // create a pull-request from - but also determining the head
  176. // repo is difficult.
  177. // We will want therefore to offer a few repositories to set as
  178. // our base and head
  179. // 1. First if the baseRepo is a fork get the "RootRepo" it was
  180. // forked from
  181. var rootRepo *models.Repository
  182. if baseRepo.IsFork {
  183. err = baseRepo.GetBaseRepo()
  184. if err != nil {
  185. if !models.IsErrRepoNotExist(err) {
  186. ctx.ServerError("Unable to find root repo", err)
  187. return nil, nil, nil, nil, "", ""
  188. }
  189. } else {
  190. rootRepo = baseRepo.BaseRepo
  191. }
  192. }
  193. // 2. Now if the current user is not the owner of the baseRepo,
  194. // check if they have a fork of the base repo and offer that as
  195. // "OwnForkRepo"
  196. var ownForkRepo *models.Repository
  197. if ctx.User != nil && baseRepo.OwnerID != ctx.User.ID {
  198. repo, has := models.HasForkedRepo(ctx.User.ID, baseRepo.ID)
  199. if has {
  200. ownForkRepo = repo
  201. ctx.Data["OwnForkRepo"] = ownForkRepo
  202. }
  203. }
  204. has := headRepo != nil
  205. // 3. If the base is a forked from "RootRepo" and the owner of
  206. // the "RootRepo" is the :headUser - set headRepo to that
  207. if !has && rootRepo != nil && rootRepo.OwnerID == headUser.ID {
  208. headRepo = rootRepo
  209. has = true
  210. }
  211. // 4. If the ctx.User has their own fork of the baseRepo and the headUser is the ctx.User
  212. // set the headRepo to the ownFork
  213. if !has && ownForkRepo != nil && ownForkRepo.OwnerID == headUser.ID {
  214. headRepo = ownForkRepo
  215. has = true
  216. }
  217. // 5. If the headOwner has a fork of the baseRepo - use that
  218. if !has {
  219. headRepo, has = models.HasForkedRepo(headUser.ID, baseRepo.ID)
  220. }
  221. // 6. If the baseRepo is a fork and the headUser has a fork of that use that
  222. if !has && baseRepo.IsFork {
  223. headRepo, has = models.HasForkedRepo(headUser.ID, baseRepo.ForkID)
  224. }
  225. // 7. Otherwise if we're not the same repo and haven't found a repo give up
  226. if !isSameRepo && !has {
  227. ctx.Data["PageIsComparePull"] = false
  228. }
  229. // 8. Finally open the git repo
  230. var headGitRepo *git.Repository
  231. if isSameRepo {
  232. headRepo = ctx.Repo.Repository
  233. headGitRepo = ctx.Repo.GitRepo
  234. } else if has {
  235. headGitRepo, err = git.OpenRepository(headRepo.RepoPath())
  236. if err != nil {
  237. ctx.ServerError("OpenRepository", err)
  238. return nil, nil, nil, nil, "", ""
  239. }
  240. defer headGitRepo.Close()
  241. }
  242. ctx.Data["HeadRepo"] = headRepo
  243. // Now we need to assert that the ctx.User has permission to read
  244. // the baseRepo's code and pulls
  245. // (NOT headRepo's)
  246. permBase, err := models.GetUserRepoPermission(baseRepo, ctx.User)
  247. if err != nil {
  248. ctx.ServerError("GetUserRepoPermission", err)
  249. return nil, nil, nil, nil, "", ""
  250. }
  251. if !permBase.CanRead(models.UnitTypeCode) {
  252. if log.IsTrace() {
  253. log.Trace("Permission Denied: User: %-v cannot read code in Repo: %-v\nUser in baseRepo has Permissions: %-+v",
  254. ctx.User,
  255. baseRepo,
  256. permBase)
  257. }
  258. ctx.NotFound("ParseCompareInfo", nil)
  259. return nil, nil, nil, nil, "", ""
  260. }
  261. // If we're not merging from the same repo:
  262. if !isSameRepo {
  263. // Assert ctx.User has permission to read headRepo's codes
  264. permHead, err := models.GetUserRepoPermission(headRepo, ctx.User)
  265. if err != nil {
  266. ctx.ServerError("GetUserRepoPermission", err)
  267. return nil, nil, nil, nil, "", ""
  268. }
  269. if !permHead.CanRead(models.UnitTypeCode) {
  270. if log.IsTrace() {
  271. log.Trace("Permission Denied: User: %-v cannot read code in Repo: %-v\nUser in headRepo has Permissions: %-+v",
  272. ctx.User,
  273. headRepo,
  274. permHead)
  275. }
  276. ctx.NotFound("ParseCompareInfo", nil)
  277. return nil, nil, nil, nil, "", ""
  278. }
  279. }
  280. // If we have a rootRepo and it's different from:
  281. // 1. the computed base
  282. // 2. the computed head
  283. // then get the branches of it
  284. if rootRepo != nil &&
  285. rootRepo.ID != headRepo.ID &&
  286. rootRepo.ID != baseRepo.ID {
  287. perm, branches, err := getBranchesForRepo(ctx.User, rootRepo)
  288. if err != nil {
  289. ctx.ServerError("GetBranchesForRepo", err)
  290. return nil, nil, nil, nil, "", ""
  291. }
  292. if perm {
  293. ctx.Data["RootRepo"] = rootRepo
  294. ctx.Data["RootRepoBranches"] = branches
  295. }
  296. }
  297. // If we have a ownForkRepo and it's different from:
  298. // 1. The computed base
  299. // 2. The computed hea
  300. // 3. The rootRepo (if we have one)
  301. // then get the branches from it.
  302. if ownForkRepo != nil &&
  303. ownForkRepo.ID != headRepo.ID &&
  304. ownForkRepo.ID != baseRepo.ID &&
  305. (rootRepo == nil || ownForkRepo.ID != rootRepo.ID) {
  306. perm, branches, err := getBranchesForRepo(ctx.User, ownForkRepo)
  307. if err != nil {
  308. ctx.ServerError("GetBranchesForRepo", err)
  309. return nil, nil, nil, nil, "", ""
  310. }
  311. if perm {
  312. ctx.Data["OwnForkRepo"] = ownForkRepo
  313. ctx.Data["OwnForkRepoBranches"] = branches
  314. }
  315. }
  316. // Check if head branch is valid.
  317. headIsCommit := headGitRepo.IsCommitExist(headBranch)
  318. headIsBranch := headGitRepo.IsBranchExist(headBranch)
  319. headIsTag := headGitRepo.IsTagExist(headBranch)
  320. if !headIsCommit && !headIsBranch && !headIsTag {
  321. // Check if headBranch is short sha commit hash
  322. if headCommit, _ := headGitRepo.GetCommit(headBranch); headCommit != nil {
  323. headBranch = headCommit.ID.String()
  324. ctx.Data["HeadBranch"] = headBranch
  325. headIsCommit = true
  326. } else {
  327. ctx.NotFound("IsRefExist", nil)
  328. return nil, nil, nil, nil, "", ""
  329. }
  330. }
  331. ctx.Data["HeadIsCommit"] = headIsCommit
  332. ctx.Data["HeadIsBranch"] = headIsBranch
  333. ctx.Data["HeadIsTag"] = headIsTag
  334. // Treat as pull request if both references are branches
  335. if ctx.Data["PageIsComparePull"] == nil {
  336. ctx.Data["PageIsComparePull"] = headIsBranch && baseIsBranch
  337. }
  338. if ctx.Data["PageIsComparePull"] == true && !permBase.CanReadIssuesOrPulls(true) {
  339. if log.IsTrace() {
  340. log.Trace("Permission Denied: User: %-v cannot create/read pull requests in Repo: %-v\nUser in baseRepo has Permissions: %-+v",
  341. ctx.User,
  342. baseRepo,
  343. permBase)
  344. }
  345. ctx.NotFound("ParseCompareInfo", nil)
  346. return nil, nil, nil, nil, "", ""
  347. }
  348. baseBranchRef := baseBranch
  349. if baseIsBranch {
  350. baseBranchRef = git.BranchPrefix + baseBranch
  351. } else if baseIsTag {
  352. baseBranchRef = git.TagPrefix + baseBranch
  353. }
  354. headBranchRef := headBranch
  355. if headIsBranch {
  356. headBranchRef = git.BranchPrefix + headBranch
  357. } else if headIsTag {
  358. headBranchRef = git.TagPrefix + headBranch
  359. }
  360. compareInfo, err := headGitRepo.GetCompareInfo(baseRepo.RepoPath(), baseBranchRef, headBranchRef)
  361. if err != nil {
  362. ctx.ServerError("GetCompareInfo", err)
  363. return nil, nil, nil, nil, "", ""
  364. }
  365. ctx.Data["BeforeCommitID"] = compareInfo.MergeBase
  366. return headUser, headRepo, headGitRepo, compareInfo, baseBranch, headBranch
  367. }
  368. // PrepareCompareDiff renders compare diff page
  369. func PrepareCompareDiff(
  370. ctx *context.Context,
  371. headUser *models.User,
  372. headRepo *models.Repository,
  373. headGitRepo *git.Repository,
  374. compareInfo *git.CompareInfo,
  375. baseBranch, headBranch string) bool {
  376. var (
  377. repo = ctx.Repo.Repository
  378. err error
  379. title string
  380. )
  381. // Get diff information.
  382. ctx.Data["CommitRepoLink"] = headRepo.Link()
  383. headCommitID := headBranch
  384. if ctx.Data["HeadIsCommit"] == false {
  385. if ctx.Data["HeadIsTag"] == true {
  386. headCommitID, err = headGitRepo.GetTagCommitID(headBranch)
  387. } else {
  388. headCommitID, err = headGitRepo.GetBranchCommitID(headBranch)
  389. }
  390. if err != nil {
  391. ctx.ServerError("GetRefCommitID", err)
  392. return false
  393. }
  394. }
  395. ctx.Data["AfterCommitID"] = headCommitID
  396. if headCommitID == compareInfo.MergeBase {
  397. ctx.Data["IsNothingToCompare"] = true
  398. return true
  399. }
  400. diff, err := gitdiff.GetDiffRange(models.RepoPath(headUser.Name, headRepo.Name),
  401. compareInfo.MergeBase, headCommitID, setting.Git.MaxGitDiffLines,
  402. setting.Git.MaxGitDiffLineCharacters, setting.Git.MaxGitDiffFiles)
  403. if err != nil {
  404. ctx.ServerError("GetDiffRange", err)
  405. return false
  406. }
  407. ctx.Data["Diff"] = diff
  408. ctx.Data["DiffNotAvailable"] = diff.NumFiles == 0
  409. headCommit, err := headGitRepo.GetCommit(headCommitID)
  410. if err != nil {
  411. ctx.ServerError("GetCommit", err)
  412. return false
  413. }
  414. baseGitRepo := ctx.Repo.GitRepo
  415. baseCommitID := baseBranch
  416. if ctx.Data["BaseIsCommit"] == false {
  417. if ctx.Data["BaseIsTag"] == true {
  418. baseCommitID, err = baseGitRepo.GetTagCommitID(baseBranch)
  419. } else {
  420. baseCommitID, err = baseGitRepo.GetBranchCommitID(baseBranch)
  421. }
  422. if err != nil {
  423. ctx.ServerError("GetRefCommitID", err)
  424. return false
  425. }
  426. }
  427. baseCommit, err := baseGitRepo.GetCommit(baseCommitID)
  428. if err != nil {
  429. ctx.ServerError("GetCommit", err)
  430. return false
  431. }
  432. compareInfo.Commits = models.ValidateCommitsWithEmails(compareInfo.Commits)
  433. compareInfo.Commits = models.ParseCommitsWithSignature(compareInfo.Commits, headRepo)
  434. compareInfo.Commits = models.ParseCommitsWithStatus(compareInfo.Commits, headRepo)
  435. ctx.Data["Commits"] = compareInfo.Commits
  436. ctx.Data["CommitCount"] = compareInfo.Commits.Len()
  437. if compareInfo.Commits.Len() == 1 {
  438. c := compareInfo.Commits.Front().Value.(models.SignCommitWithStatuses)
  439. title = strings.TrimSpace(c.UserCommit.Summary())
  440. body := strings.Split(strings.TrimSpace(c.UserCommit.Message()), "\n")
  441. if len(body) > 1 {
  442. ctx.Data["content"] = strings.Join(body[1:], "\n")
  443. }
  444. } else {
  445. title = headBranch
  446. }
  447. ctx.Data["title"] = title
  448. ctx.Data["Username"] = headUser.Name
  449. ctx.Data["Reponame"] = headRepo.Name
  450. setImageCompareContext(ctx, baseCommit, headCommit)
  451. headTarget := path.Join(headUser.Name, repo.Name)
  452. setPathsCompareContext(ctx, baseCommit, headCommit, headTarget)
  453. return false
  454. }
  455. func getBranchesForRepo(user *models.User, repo *models.Repository) (bool, []string, error) {
  456. perm, err := models.GetUserRepoPermission(repo, user)
  457. if err != nil {
  458. return false, nil, err
  459. }
  460. if !perm.CanRead(models.UnitTypeCode) {
  461. return false, nil, nil
  462. }
  463. gitRepo, err := git.OpenRepository(repo.RepoPath())
  464. if err != nil {
  465. return false, nil, err
  466. }
  467. defer gitRepo.Close()
  468. branches, err := gitRepo.GetBranches()
  469. if err != nil {
  470. return false, nil, err
  471. }
  472. return true, branches, nil
  473. }
  474. // CompareDiff show different from one commit to another commit
  475. func CompareDiff(ctx *context.Context) {
  476. headUser, headRepo, headGitRepo, compareInfo, baseBranch, headBranch := ParseCompareInfo(ctx)
  477. if ctx.Written() {
  478. return
  479. }
  480. defer headGitRepo.Close()
  481. nothingToCompare := PrepareCompareDiff(ctx, headUser, headRepo, headGitRepo, compareInfo, baseBranch, headBranch)
  482. if ctx.Written() {
  483. return
  484. }
  485. if ctx.Data["PageIsComparePull"] == true {
  486. headBranches, err := headGitRepo.GetBranches()
  487. if err != nil {
  488. ctx.ServerError("GetBranches", err)
  489. return
  490. }
  491. ctx.Data["HeadBranches"] = headBranches
  492. pr, err := models.GetUnmergedPullRequest(headRepo.ID, ctx.Repo.Repository.ID, headBranch, baseBranch)
  493. if err != nil {
  494. if !models.IsErrPullRequestNotExist(err) {
  495. ctx.ServerError("GetUnmergedPullRequest", err)
  496. return
  497. }
  498. } else {
  499. ctx.Data["HasPullRequest"] = true
  500. ctx.Data["PullRequest"] = pr
  501. ctx.HTML(200, tplCompareDiff)
  502. return
  503. }
  504. if !nothingToCompare {
  505. // Setup information for new form.
  506. RetrieveRepoMetas(ctx, ctx.Repo.Repository, true)
  507. if ctx.Written() {
  508. return
  509. }
  510. }
  511. }
  512. beforeCommitID := ctx.Data["BeforeCommitID"].(string)
  513. afterCommitID := ctx.Data["AfterCommitID"].(string)
  514. ctx.Data["Title"] = "Comparing " + base.ShortSha(beforeCommitID) + "..." + base.ShortSha(afterCommitID)
  515. ctx.Data["IsRepoToolbarCommits"] = true
  516. ctx.Data["IsDiffCompare"] = true
  517. ctx.Data["RequireTribute"] = true
  518. ctx.Data["RequireSimpleMDE"] = true
  519. ctx.Data["PullRequestWorkInProgressPrefixes"] = setting.Repository.PullRequest.WorkInProgressPrefixes
  520. setTemplateIfExists(ctx, pullRequestTemplateKey, pullRequestTemplateCandidates)
  521. renderAttachmentSettings(ctx)
  522. ctx.Data["HasIssuesOrPullsWritePermission"] = ctx.Repo.CanWrite(models.UnitTypePullRequests)
  523. ctx.HTML(200, tplCompare)
  524. }
  525. // ExcerptBlob render blob excerpt contents
  526. func ExcerptBlob(ctx *context.Context) {
  527. commitID := ctx.Params("sha")
  528. lastLeft := ctx.QueryInt("last_left")
  529. lastRight := ctx.QueryInt("last_right")
  530. idxLeft := ctx.QueryInt("left")
  531. idxRight := ctx.QueryInt("right")
  532. leftHunkSize := ctx.QueryInt("left_hunk_size")
  533. rightHunkSize := ctx.QueryInt("right_hunk_size")
  534. anchor := ctx.Query("anchor")
  535. direction := ctx.Query("direction")
  536. filePath := ctx.Query("path")
  537. gitRepo := ctx.Repo.GitRepo
  538. chunkSize := gitdiff.BlobExceprtChunkSize
  539. commit, err := gitRepo.GetCommit(commitID)
  540. if err != nil {
  541. ctx.Error(500, "GetCommit")
  542. return
  543. }
  544. section := &gitdiff.DiffSection{
  545. Name: filePath,
  546. }
  547. if direction == "up" && (idxLeft-lastLeft) > chunkSize {
  548. idxLeft -= chunkSize
  549. idxRight -= chunkSize
  550. leftHunkSize += chunkSize
  551. rightHunkSize += chunkSize
  552. section.Lines, err = getExcerptLines(commit, filePath, idxLeft-1, idxRight-1, chunkSize)
  553. } else if direction == "down" && (idxLeft-lastLeft) > chunkSize {
  554. section.Lines, err = getExcerptLines(commit, filePath, lastLeft, lastRight, chunkSize)
  555. lastLeft += chunkSize
  556. lastRight += chunkSize
  557. } else {
  558. section.Lines, err = getExcerptLines(commit, filePath, lastLeft, lastRight, idxRight-lastRight-1)
  559. leftHunkSize = 0
  560. rightHunkSize = 0
  561. idxLeft = lastLeft
  562. idxRight = lastRight
  563. }
  564. if err != nil {
  565. ctx.Error(500, "getExcerptLines")
  566. return
  567. }
  568. if idxRight > lastRight {
  569. lineText := " "
  570. if rightHunkSize > 0 || leftHunkSize > 0 {
  571. lineText = fmt.Sprintf("@@ -%d,%d +%d,%d @@\n", idxLeft, leftHunkSize, idxRight, rightHunkSize)
  572. }
  573. lineText = html.EscapeString(lineText)
  574. lineSection := &gitdiff.DiffLine{
  575. Type: gitdiff.DiffLineSection,
  576. Content: lineText,
  577. SectionInfo: &gitdiff.DiffLineSectionInfo{
  578. Path: filePath,
  579. LastLeftIdx: lastLeft,
  580. LastRightIdx: lastRight,
  581. LeftIdx: idxLeft,
  582. RightIdx: idxRight,
  583. LeftHunkSize: leftHunkSize,
  584. RightHunkSize: rightHunkSize,
  585. }}
  586. if direction == "up" {
  587. section.Lines = append([]*gitdiff.DiffLine{lineSection}, section.Lines...)
  588. } else if direction == "down" {
  589. section.Lines = append(section.Lines, lineSection)
  590. }
  591. }
  592. ctx.Data["section"] = section
  593. ctx.Data["fileName"] = filePath
  594. ctx.Data["AfterCommitID"] = commitID
  595. ctx.Data["Anchor"] = anchor
  596. ctx.HTML(200, tplBlobExcerpt)
  597. }
  598. func getExcerptLines(commit *git.Commit, filePath string, idxLeft int, idxRight int, chunkSize int) ([]*gitdiff.DiffLine, error) {
  599. blob, err := commit.Tree.GetBlobByPath(filePath)
  600. if err != nil {
  601. return nil, err
  602. }
  603. reader, err := blob.DataAsync()
  604. if err != nil {
  605. return nil, err
  606. }
  607. defer reader.Close()
  608. scanner := bufio.NewScanner(reader)
  609. var diffLines []*gitdiff.DiffLine
  610. for line := 0; line < idxRight+chunkSize; line++ {
  611. if ok := scanner.Scan(); !ok {
  612. break
  613. }
  614. if line < idxRight {
  615. continue
  616. }
  617. lineText := scanner.Text()
  618. diffLine := &gitdiff.DiffLine{
  619. LeftIdx: idxLeft + (line - idxRight) + 1,
  620. RightIdx: line + 1,
  621. Type: gitdiff.DiffLinePlain,
  622. Content: " " + lineText,
  623. }
  624. diffLines = append(diffLines, diffLine)
  625. }
  626. return diffLines, nil
  627. }