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.

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