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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981
  1. // Copyright 2019 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package repo
  4. import (
  5. "bufio"
  6. gocontext "context"
  7. "encoding/csv"
  8. "errors"
  9. "fmt"
  10. "html"
  11. "io"
  12. "net/http"
  13. "net/url"
  14. "path/filepath"
  15. "strings"
  16. "code.gitea.io/gitea/models/db"
  17. git_model "code.gitea.io/gitea/models/git"
  18. issues_model "code.gitea.io/gitea/models/issues"
  19. access_model "code.gitea.io/gitea/models/perm/access"
  20. repo_model "code.gitea.io/gitea/models/repo"
  21. "code.gitea.io/gitea/models/unit"
  22. user_model "code.gitea.io/gitea/models/user"
  23. "code.gitea.io/gitea/modules/base"
  24. "code.gitea.io/gitea/modules/charset"
  25. "code.gitea.io/gitea/modules/context"
  26. csv_module "code.gitea.io/gitea/modules/csv"
  27. "code.gitea.io/gitea/modules/git"
  28. "code.gitea.io/gitea/modules/log"
  29. "code.gitea.io/gitea/modules/markup"
  30. "code.gitea.io/gitea/modules/setting"
  31. api "code.gitea.io/gitea/modules/structs"
  32. "code.gitea.io/gitea/modules/typesniffer"
  33. "code.gitea.io/gitea/modules/upload"
  34. "code.gitea.io/gitea/modules/util"
  35. "code.gitea.io/gitea/services/gitdiff"
  36. )
  37. const (
  38. tplCompare base.TplName = "repo/diff/compare"
  39. tplBlobExcerpt base.TplName = "repo/diff/blob_excerpt"
  40. tplDiffBox base.TplName = "repo/diff/box"
  41. )
  42. // setCompareContext sets context data.
  43. func setCompareContext(ctx *context.Context, before, head *git.Commit, headOwner, headName string) {
  44. ctx.Data["BeforeCommit"] = before
  45. ctx.Data["HeadCommit"] = head
  46. ctx.Data["GetBlobByPathForCommit"] = func(commit *git.Commit, path string) *git.Blob {
  47. if commit == nil {
  48. return nil
  49. }
  50. blob, err := commit.GetBlobByPath(path)
  51. if err != nil {
  52. return nil
  53. }
  54. return blob
  55. }
  56. ctx.Data["GetSniffedTypeForBlob"] = func(blob *git.Blob) typesniffer.SniffedType {
  57. st := typesniffer.SniffedType{}
  58. if blob == nil {
  59. return st
  60. }
  61. st, err := blob.GuessContentType()
  62. if err != nil {
  63. log.Error("GuessContentType failed: %v", err)
  64. return st
  65. }
  66. return st
  67. }
  68. setPathsCompareContext(ctx, before, head, headOwner, headName)
  69. setImageCompareContext(ctx)
  70. setCsvCompareContext(ctx)
  71. }
  72. // SourceCommitURL creates a relative URL for a commit in the given repository
  73. func SourceCommitURL(owner, name string, commit *git.Commit) string {
  74. return setting.AppSubURL + "/" + url.PathEscape(owner) + "/" + url.PathEscape(name) + "/src/commit/" + url.PathEscape(commit.ID.String())
  75. }
  76. // RawCommitURL creates a relative URL for the raw commit in the given repository
  77. func RawCommitURL(owner, name string, commit *git.Commit) string {
  78. return setting.AppSubURL + "/" + url.PathEscape(owner) + "/" + url.PathEscape(name) + "/raw/commit/" + url.PathEscape(commit.ID.String())
  79. }
  80. // setPathsCompareContext sets context data for source and raw paths
  81. func setPathsCompareContext(ctx *context.Context, base, head *git.Commit, headOwner, headName string) {
  82. ctx.Data["SourcePath"] = SourceCommitURL(headOwner, headName, head)
  83. ctx.Data["RawPath"] = RawCommitURL(headOwner, headName, head)
  84. if base != nil {
  85. ctx.Data["BeforeSourcePath"] = SourceCommitURL(headOwner, headName, base)
  86. ctx.Data["BeforeRawPath"] = RawCommitURL(headOwner, headName, base)
  87. }
  88. }
  89. // setImageCompareContext sets context data that is required by image compare template
  90. func setImageCompareContext(ctx *context.Context) {
  91. ctx.Data["IsSniffedTypeAnImage"] = func(st typesniffer.SniffedType) bool {
  92. return st.IsImage() && (setting.UI.SVG.Enabled || !st.IsSvgImage())
  93. }
  94. }
  95. // setCsvCompareContext sets context data that is required by the CSV compare template
  96. func setCsvCompareContext(ctx *context.Context) {
  97. ctx.Data["IsCsvFile"] = func(diffFile *gitdiff.DiffFile) bool {
  98. extension := strings.ToLower(filepath.Ext(diffFile.Name))
  99. return extension == ".csv" || extension == ".tsv"
  100. }
  101. type CsvDiffResult struct {
  102. Sections []*gitdiff.TableDiffSection
  103. Error string
  104. }
  105. ctx.Data["CreateCsvDiff"] = func(diffFile *gitdiff.DiffFile, baseBlob, headBlob *git.Blob) CsvDiffResult {
  106. if diffFile == nil {
  107. return CsvDiffResult{nil, ""}
  108. }
  109. errTooLarge := errors.New(ctx.Locale.Tr("repo.error.csv.too_large"))
  110. csvReaderFromCommit := func(ctx *markup.RenderContext, blob *git.Blob) (*csv.Reader, io.Closer, error) {
  111. if blob == nil {
  112. // It's ok for blob to be nil (file added or deleted)
  113. return nil, nil, nil
  114. }
  115. if setting.UI.CSV.MaxFileSize != 0 && setting.UI.CSV.MaxFileSize < blob.Size() {
  116. return nil, nil, errTooLarge
  117. }
  118. reader, err := blob.DataAsync()
  119. if err != nil {
  120. return nil, nil, err
  121. }
  122. csvReader, err := csv_module.CreateReaderAndDetermineDelimiter(ctx, charset.ToUTF8WithFallbackReader(reader, charset.ConvertOpts{}))
  123. return csvReader, reader, err
  124. }
  125. baseReader, baseBlobCloser, err := csvReaderFromCommit(&markup.RenderContext{Ctx: ctx, RelativePath: diffFile.OldName}, baseBlob)
  126. if baseBlobCloser != nil {
  127. defer baseBlobCloser.Close()
  128. }
  129. if err != nil {
  130. if err == errTooLarge {
  131. return CsvDiffResult{nil, err.Error()}
  132. }
  133. log.Error("error whilst creating csv.Reader from file %s in base commit %s in %s: %v", diffFile.Name, baseBlob.ID.String(), ctx.Repo.Repository.Name, err)
  134. return CsvDiffResult{nil, "unable to load file"}
  135. }
  136. headReader, headBlobCloser, err := csvReaderFromCommit(&markup.RenderContext{Ctx: ctx, RelativePath: diffFile.Name}, headBlob)
  137. if headBlobCloser != nil {
  138. defer headBlobCloser.Close()
  139. }
  140. if err != nil {
  141. if err == errTooLarge {
  142. return CsvDiffResult{nil, err.Error()}
  143. }
  144. log.Error("error whilst creating csv.Reader from file %s in head commit %s in %s: %v", diffFile.Name, headBlob.ID.String(), ctx.Repo.Repository.Name, err)
  145. return CsvDiffResult{nil, "unable to load file"}
  146. }
  147. sections, err := gitdiff.CreateCsvDiff(diffFile, baseReader, headReader)
  148. if err != nil {
  149. errMessage, err := csv_module.FormatError(err, ctx.Locale)
  150. if err != nil {
  151. log.Error("CreateCsvDiff FormatError failed: %v", err)
  152. return CsvDiffResult{nil, "unknown csv diff error"}
  153. }
  154. return CsvDiffResult{nil, errMessage}
  155. }
  156. return CsvDiffResult{sections, ""}
  157. }
  158. }
  159. // CompareInfo represents the collected results from ParseCompareInfo
  160. type CompareInfo struct {
  161. HeadUser *user_model.User
  162. HeadRepo *repo_model.Repository
  163. HeadGitRepo *git.Repository
  164. CompareInfo *git.CompareInfo
  165. BaseBranch string
  166. HeadBranch string
  167. DirectComparison bool
  168. }
  169. // ParseCompareInfo parse compare info between two commit for preparing comparing references
  170. func ParseCompareInfo(ctx *context.Context) *CompareInfo {
  171. baseRepo := ctx.Repo.Repository
  172. ci := &CompareInfo{}
  173. fileOnly := ctx.FormBool("file-only")
  174. // Get compared branches information
  175. // A full compare url is of the form:
  176. //
  177. // 1. /{:baseOwner}/{:baseRepoName}/compare/{:baseBranch}...{:headBranch}
  178. // 2. /{:baseOwner}/{:baseRepoName}/compare/{:baseBranch}...{:headOwner}:{:headBranch}
  179. // 3. /{:baseOwner}/{:baseRepoName}/compare/{:baseBranch}...{:headOwner}/{:headRepoName}:{:headBranch}
  180. // 4. /{:baseOwner}/{:baseRepoName}/compare/{:headBranch}
  181. // 5. /{:baseOwner}/{:baseRepoName}/compare/{:headOwner}:{:headBranch}
  182. // 6. /{:baseOwner}/{:baseRepoName}/compare/{:headOwner}/{:headRepoName}:{:headBranch}
  183. //
  184. // Here we obtain the infoPath "{:baseBranch}...[{:headOwner}/{:headRepoName}:]{:headBranch}" as ctx.Params("*")
  185. // with the :baseRepo in ctx.Repo.
  186. //
  187. // Note: Generally :headRepoName is not provided here - we are only passed :headOwner.
  188. //
  189. // How do we determine the :headRepo?
  190. //
  191. // 1. If :headOwner is not set then the :headRepo = :baseRepo
  192. // 2. If :headOwner is set - then look for the fork of :baseRepo owned by :headOwner
  193. // 3. But... :baseRepo could be a fork of :headOwner's repo - so check that
  194. // 4. Now, :baseRepo and :headRepos could be forks of the same repo - so check that
  195. //
  196. // format: <base branch>...[<head repo>:]<head branch>
  197. // base<-head: master...head:feature
  198. // same repo: master...feature
  199. var (
  200. isSameRepo bool
  201. infoPath string
  202. err error
  203. )
  204. infoPath = ctx.Params("*")
  205. var infos []string
  206. if infoPath == "" {
  207. infos = []string{baseRepo.DefaultBranch, baseRepo.DefaultBranch}
  208. } else {
  209. infos = strings.SplitN(infoPath, "...", 2)
  210. if len(infos) != 2 {
  211. if infos = strings.SplitN(infoPath, "..", 2); len(infos) == 2 {
  212. ci.DirectComparison = true
  213. ctx.Data["PageIsComparePull"] = false
  214. } else {
  215. infos = []string{baseRepo.DefaultBranch, infoPath}
  216. }
  217. }
  218. }
  219. ctx.Data["BaseName"] = baseRepo.OwnerName
  220. ci.BaseBranch = infos[0]
  221. ctx.Data["BaseBranch"] = ci.BaseBranch
  222. // If there is no head repository, it means compare between same repository.
  223. headInfos := strings.Split(infos[1], ":")
  224. if len(headInfos) == 1 {
  225. isSameRepo = true
  226. ci.HeadUser = ctx.Repo.Owner
  227. ci.HeadBranch = headInfos[0]
  228. } else if len(headInfos) == 2 {
  229. headInfosSplit := strings.Split(headInfos[0], "/")
  230. if len(headInfosSplit) == 1 {
  231. ci.HeadUser, err = user_model.GetUserByName(ctx, headInfos[0])
  232. if err != nil {
  233. if user_model.IsErrUserNotExist(err) {
  234. ctx.NotFound("GetUserByName", nil)
  235. } else {
  236. ctx.ServerError("GetUserByName", err)
  237. }
  238. return nil
  239. }
  240. ci.HeadBranch = headInfos[1]
  241. isSameRepo = ci.HeadUser.ID == ctx.Repo.Owner.ID
  242. if isSameRepo {
  243. ci.HeadRepo = baseRepo
  244. }
  245. } else {
  246. ci.HeadRepo, err = repo_model.GetRepositoryByOwnerAndName(ctx, headInfosSplit[0], headInfosSplit[1])
  247. if err != nil {
  248. if repo_model.IsErrRepoNotExist(err) {
  249. ctx.NotFound("GetRepositoryByOwnerAndName", nil)
  250. } else {
  251. ctx.ServerError("GetRepositoryByOwnerAndName", err)
  252. }
  253. return nil
  254. }
  255. if err := ci.HeadRepo.LoadOwner(ctx); err != nil {
  256. if user_model.IsErrUserNotExist(err) {
  257. ctx.NotFound("GetUserByName", nil)
  258. } else {
  259. ctx.ServerError("GetUserByName", err)
  260. }
  261. return nil
  262. }
  263. ci.HeadBranch = headInfos[1]
  264. ci.HeadUser = ci.HeadRepo.Owner
  265. isSameRepo = ci.HeadRepo.ID == ctx.Repo.Repository.ID
  266. }
  267. } else {
  268. ctx.NotFound("CompareAndPullRequest", nil)
  269. return nil
  270. }
  271. ctx.Data["HeadUser"] = ci.HeadUser
  272. ctx.Data["HeadBranch"] = ci.HeadBranch
  273. ctx.Repo.PullRequest.SameRepo = isSameRepo
  274. // Check if base branch is valid.
  275. baseIsCommit := ctx.Repo.GitRepo.IsCommitExist(ci.BaseBranch)
  276. baseIsBranch := ctx.Repo.GitRepo.IsBranchExist(ci.BaseBranch)
  277. baseIsTag := ctx.Repo.GitRepo.IsTagExist(ci.BaseBranch)
  278. if !baseIsCommit && !baseIsBranch && !baseIsTag {
  279. // Check if baseBranch is short sha commit hash
  280. if baseCommit, _ := ctx.Repo.GitRepo.GetCommit(ci.BaseBranch); baseCommit != nil {
  281. ci.BaseBranch = baseCommit.ID.String()
  282. ctx.Data["BaseBranch"] = ci.BaseBranch
  283. baseIsCommit = true
  284. } else if ci.BaseBranch == git.EmptySHA {
  285. if isSameRepo {
  286. ctx.Redirect(ctx.Repo.RepoLink + "/compare/" + util.PathEscapeSegments(ci.HeadBranch))
  287. } else {
  288. ctx.Redirect(ctx.Repo.RepoLink + "/compare/" + util.PathEscapeSegments(ci.HeadRepo.FullName()) + ":" + util.PathEscapeSegments(ci.HeadBranch))
  289. }
  290. return nil
  291. } else {
  292. ctx.NotFound("IsRefExist", nil)
  293. return nil
  294. }
  295. }
  296. ctx.Data["BaseIsCommit"] = baseIsCommit
  297. ctx.Data["BaseIsBranch"] = baseIsBranch
  298. ctx.Data["BaseIsTag"] = baseIsTag
  299. ctx.Data["IsPull"] = true
  300. // Now we have the repository that represents the base
  301. // The current base and head repositories and branches may not
  302. // actually be the intended branches that the user wants to
  303. // create a pull-request from - but also determining the head
  304. // repo is difficult.
  305. // We will want therefore to offer a few repositories to set as
  306. // our base and head
  307. // 1. First if the baseRepo is a fork get the "RootRepo" it was
  308. // forked from
  309. var rootRepo *repo_model.Repository
  310. if baseRepo.IsFork {
  311. err = baseRepo.GetBaseRepo(ctx)
  312. if err != nil {
  313. if !repo_model.IsErrRepoNotExist(err) {
  314. ctx.ServerError("Unable to find root repo", err)
  315. return nil
  316. }
  317. } else {
  318. rootRepo = baseRepo.BaseRepo
  319. }
  320. }
  321. // 2. Now if the current user is not the owner of the baseRepo,
  322. // check if they have a fork of the base repo and offer that as
  323. // "OwnForkRepo"
  324. var ownForkRepo *repo_model.Repository
  325. if ctx.Doer != nil && baseRepo.OwnerID != ctx.Doer.ID {
  326. repo := repo_model.GetForkedRepo(ctx, ctx.Doer.ID, baseRepo.ID)
  327. if repo != nil {
  328. ownForkRepo = repo
  329. ctx.Data["OwnForkRepo"] = ownForkRepo
  330. }
  331. }
  332. has := ci.HeadRepo != nil
  333. // 3. If the base is a forked from "RootRepo" and the owner of
  334. // the "RootRepo" is the :headUser - set headRepo to that
  335. if !has && rootRepo != nil && rootRepo.OwnerID == ci.HeadUser.ID {
  336. ci.HeadRepo = rootRepo
  337. has = true
  338. }
  339. // 4. If the ctx.Doer has their own fork of the baseRepo and the headUser is the ctx.Doer
  340. // set the headRepo to the ownFork
  341. if !has && ownForkRepo != nil && ownForkRepo.OwnerID == ci.HeadUser.ID {
  342. ci.HeadRepo = ownForkRepo
  343. has = true
  344. }
  345. // 5. If the headOwner has a fork of the baseRepo - use that
  346. if !has {
  347. ci.HeadRepo = repo_model.GetForkedRepo(ctx, ci.HeadUser.ID, baseRepo.ID)
  348. has = ci.HeadRepo != nil
  349. }
  350. // 6. If the baseRepo is a fork and the headUser has a fork of that use that
  351. if !has && baseRepo.IsFork {
  352. ci.HeadRepo = repo_model.GetForkedRepo(ctx, ci.HeadUser.ID, baseRepo.ForkID)
  353. has = ci.HeadRepo != nil
  354. }
  355. // 7. Otherwise if we're not the same repo and haven't found a repo give up
  356. if !isSameRepo && !has {
  357. ctx.Data["PageIsComparePull"] = false
  358. }
  359. // 8. Finally open the git repo
  360. if isSameRepo {
  361. ci.HeadRepo = ctx.Repo.Repository
  362. ci.HeadGitRepo = ctx.Repo.GitRepo
  363. } else if has {
  364. ci.HeadGitRepo, err = git.OpenRepository(ctx, ci.HeadRepo.RepoPath())
  365. if err != nil {
  366. ctx.ServerError("OpenRepository", err)
  367. return nil
  368. }
  369. defer ci.HeadGitRepo.Close()
  370. } else {
  371. ctx.NotFound("ParseCompareInfo", nil)
  372. return nil
  373. }
  374. ctx.Data["HeadRepo"] = ci.HeadRepo
  375. ctx.Data["BaseCompareRepo"] = ctx.Repo.Repository
  376. // Now we need to assert that the ctx.Doer has permission to read
  377. // the baseRepo's code and pulls
  378. // (NOT headRepo's)
  379. permBase, err := access_model.GetUserRepoPermission(ctx, baseRepo, ctx.Doer)
  380. if err != nil {
  381. ctx.ServerError("GetUserRepoPermission", err)
  382. return nil
  383. }
  384. if !permBase.CanRead(unit.TypeCode) {
  385. if log.IsTrace() {
  386. log.Trace("Permission Denied: User: %-v cannot read code in Repo: %-v\nUser in baseRepo has Permissions: %-+v",
  387. ctx.Doer,
  388. baseRepo,
  389. permBase)
  390. }
  391. ctx.NotFound("ParseCompareInfo", nil)
  392. return nil
  393. }
  394. // If we're not merging from the same repo:
  395. if !isSameRepo {
  396. // Assert ctx.Doer has permission to read headRepo's codes
  397. permHead, err := access_model.GetUserRepoPermission(ctx, ci.HeadRepo, ctx.Doer)
  398. if err != nil {
  399. ctx.ServerError("GetUserRepoPermission", err)
  400. return nil
  401. }
  402. if !permHead.CanRead(unit.TypeCode) {
  403. if log.IsTrace() {
  404. log.Trace("Permission Denied: User: %-v cannot read code in Repo: %-v\nUser in headRepo has Permissions: %-+v",
  405. ctx.Doer,
  406. ci.HeadRepo,
  407. permHead)
  408. }
  409. ctx.NotFound("ParseCompareInfo", nil)
  410. return nil
  411. }
  412. ctx.Data["CanWriteToHeadRepo"] = permHead.CanWrite(unit.TypeCode)
  413. }
  414. // If we have a rootRepo and it's different from:
  415. // 1. the computed base
  416. // 2. the computed head
  417. // then get the branches of it
  418. if rootRepo != nil &&
  419. rootRepo.ID != ci.HeadRepo.ID &&
  420. rootRepo.ID != baseRepo.ID {
  421. canRead := access_model.CheckRepoUnitUser(ctx, rootRepo, ctx.Doer, unit.TypeCode)
  422. if canRead {
  423. ctx.Data["RootRepo"] = rootRepo
  424. if !fileOnly {
  425. branches, tags, err := getBranchesAndTagsForRepo(ctx, rootRepo)
  426. if err != nil {
  427. ctx.ServerError("GetBranchesForRepo", err)
  428. return nil
  429. }
  430. ctx.Data["RootRepoBranches"] = branches
  431. ctx.Data["RootRepoTags"] = tags
  432. }
  433. }
  434. }
  435. // If we have a ownForkRepo and it's different from:
  436. // 1. The computed base
  437. // 2. The computed head
  438. // 3. The rootRepo (if we have one)
  439. // then get the branches from it.
  440. if ownForkRepo != nil &&
  441. ownForkRepo.ID != ci.HeadRepo.ID &&
  442. ownForkRepo.ID != baseRepo.ID &&
  443. (rootRepo == nil || ownForkRepo.ID != rootRepo.ID) {
  444. canRead := access_model.CheckRepoUnitUser(ctx, ownForkRepo, ctx.Doer, unit.TypeCode)
  445. if canRead {
  446. ctx.Data["OwnForkRepo"] = ownForkRepo
  447. if !fileOnly {
  448. branches, tags, err := getBranchesAndTagsForRepo(ctx, ownForkRepo)
  449. if err != nil {
  450. ctx.ServerError("GetBranchesForRepo", err)
  451. return nil
  452. }
  453. ctx.Data["OwnForkRepoBranches"] = branches
  454. ctx.Data["OwnForkRepoTags"] = tags
  455. }
  456. }
  457. }
  458. // Check if head branch is valid.
  459. headIsCommit := ci.HeadGitRepo.IsCommitExist(ci.HeadBranch)
  460. headIsBranch := ci.HeadGitRepo.IsBranchExist(ci.HeadBranch)
  461. headIsTag := ci.HeadGitRepo.IsTagExist(ci.HeadBranch)
  462. if !headIsCommit && !headIsBranch && !headIsTag {
  463. // Check if headBranch is short sha commit hash
  464. if headCommit, _ := ci.HeadGitRepo.GetCommit(ci.HeadBranch); headCommit != nil {
  465. ci.HeadBranch = headCommit.ID.String()
  466. ctx.Data["HeadBranch"] = ci.HeadBranch
  467. headIsCommit = true
  468. } else {
  469. ctx.NotFound("IsRefExist", nil)
  470. return nil
  471. }
  472. }
  473. ctx.Data["HeadIsCommit"] = headIsCommit
  474. ctx.Data["HeadIsBranch"] = headIsBranch
  475. ctx.Data["HeadIsTag"] = headIsTag
  476. // Treat as pull request if both references are branches
  477. if ctx.Data["PageIsComparePull"] == nil {
  478. ctx.Data["PageIsComparePull"] = headIsBranch && baseIsBranch
  479. }
  480. if ctx.Data["PageIsComparePull"] == true && !permBase.CanReadIssuesOrPulls(true) {
  481. if log.IsTrace() {
  482. log.Trace("Permission Denied: User: %-v cannot create/read pull requests in Repo: %-v\nUser in baseRepo has Permissions: %-+v",
  483. ctx.Doer,
  484. baseRepo,
  485. permBase)
  486. }
  487. ctx.NotFound("ParseCompareInfo", nil)
  488. return nil
  489. }
  490. baseBranchRef := ci.BaseBranch
  491. if baseIsBranch {
  492. baseBranchRef = git.BranchPrefix + ci.BaseBranch
  493. } else if baseIsTag {
  494. baseBranchRef = git.TagPrefix + ci.BaseBranch
  495. }
  496. headBranchRef := ci.HeadBranch
  497. if headIsBranch {
  498. headBranchRef = git.BranchPrefix + ci.HeadBranch
  499. } else if headIsTag {
  500. headBranchRef = git.TagPrefix + ci.HeadBranch
  501. }
  502. ci.CompareInfo, err = ci.HeadGitRepo.GetCompareInfo(baseRepo.RepoPath(), baseBranchRef, headBranchRef, ci.DirectComparison, fileOnly)
  503. if err != nil {
  504. ctx.ServerError("GetCompareInfo", err)
  505. return nil
  506. }
  507. if ci.DirectComparison {
  508. ctx.Data["BeforeCommitID"] = ci.CompareInfo.BaseCommitID
  509. } else {
  510. ctx.Data["BeforeCommitID"] = ci.CompareInfo.MergeBase
  511. }
  512. return ci
  513. }
  514. // PrepareCompareDiff renders compare diff page
  515. func PrepareCompareDiff(
  516. ctx *context.Context,
  517. ci *CompareInfo,
  518. whitespaceBehavior git.TrustedCmdArgs,
  519. ) bool {
  520. var (
  521. repo = ctx.Repo.Repository
  522. err error
  523. title string
  524. )
  525. // Get diff information.
  526. ctx.Data["CommitRepoLink"] = ci.HeadRepo.Link()
  527. headCommitID := ci.CompareInfo.HeadCommitID
  528. ctx.Data["AfterCommitID"] = headCommitID
  529. if (headCommitID == ci.CompareInfo.MergeBase && !ci.DirectComparison) ||
  530. headCommitID == ci.CompareInfo.BaseCommitID {
  531. ctx.Data["IsNothingToCompare"] = true
  532. if unit, err := repo.GetUnit(ctx, unit.TypePullRequests); err == nil {
  533. config := unit.PullRequestsConfig()
  534. if !config.AutodetectManualMerge {
  535. allowEmptyPr := !(ci.BaseBranch == ci.HeadBranch && ctx.Repo.Repository.Name == ci.HeadRepo.Name)
  536. ctx.Data["AllowEmptyPr"] = allowEmptyPr
  537. return !allowEmptyPr
  538. }
  539. ctx.Data["AllowEmptyPr"] = false
  540. }
  541. return true
  542. }
  543. beforeCommitID := ci.CompareInfo.MergeBase
  544. if ci.DirectComparison {
  545. beforeCommitID = ci.CompareInfo.BaseCommitID
  546. }
  547. maxLines, maxFiles := setting.Git.MaxGitDiffLines, setting.Git.MaxGitDiffFiles
  548. files := ctx.FormStrings("files")
  549. if len(files) == 2 || len(files) == 1 {
  550. maxLines, maxFiles = -1, -1
  551. }
  552. diff, err := gitdiff.GetDiff(ci.HeadGitRepo,
  553. &gitdiff.DiffOptions{
  554. BeforeCommitID: beforeCommitID,
  555. AfterCommitID: headCommitID,
  556. SkipTo: ctx.FormString("skip-to"),
  557. MaxLines: maxLines,
  558. MaxLineCharacters: setting.Git.MaxGitDiffLineCharacters,
  559. MaxFiles: maxFiles,
  560. WhitespaceBehavior: whitespaceBehavior,
  561. DirectComparison: ci.DirectComparison,
  562. }, ctx.FormStrings("files")...)
  563. if err != nil {
  564. ctx.ServerError("GetDiffRangeWithWhitespaceBehavior", err)
  565. return false
  566. }
  567. ctx.Data["Diff"] = diff
  568. ctx.Data["DiffNotAvailable"] = diff.NumFiles == 0
  569. headCommit, err := ci.HeadGitRepo.GetCommit(headCommitID)
  570. if err != nil {
  571. ctx.ServerError("GetCommit", err)
  572. return false
  573. }
  574. baseGitRepo := ctx.Repo.GitRepo
  575. beforeCommit, err := baseGitRepo.GetCommit(beforeCommitID)
  576. if err != nil {
  577. ctx.ServerError("GetCommit", err)
  578. return false
  579. }
  580. commits := git_model.ConvertFromGitCommit(ctx, ci.CompareInfo.Commits, ci.HeadRepo)
  581. ctx.Data["Commits"] = commits
  582. ctx.Data["CommitCount"] = len(commits)
  583. if len(commits) == 1 {
  584. c := commits[0]
  585. title = strings.TrimSpace(c.UserCommit.Summary())
  586. body := strings.Split(strings.TrimSpace(c.UserCommit.Message()), "\n")
  587. if len(body) > 1 {
  588. ctx.Data["content"] = strings.Join(body[1:], "\n")
  589. }
  590. } else {
  591. title = ci.HeadBranch
  592. }
  593. if len(title) > 255 {
  594. var trailer string
  595. title, trailer = util.SplitStringAtByteN(title, 255)
  596. if len(trailer) > 0 {
  597. if ctx.Data["content"] != nil {
  598. ctx.Data["content"] = fmt.Sprintf("%s\n\n%s", trailer, ctx.Data["content"])
  599. } else {
  600. ctx.Data["content"] = trailer + "\n"
  601. }
  602. }
  603. }
  604. ctx.Data["title"] = title
  605. ctx.Data["Username"] = ci.HeadUser.Name
  606. ctx.Data["Reponame"] = ci.HeadRepo.Name
  607. setCompareContext(ctx, beforeCommit, headCommit, ci.HeadUser.Name, repo.Name)
  608. return false
  609. }
  610. func getBranchesAndTagsForRepo(ctx gocontext.Context, repo *repo_model.Repository) (branches, tags []string, err error) {
  611. gitRepo, err := git.OpenRepository(ctx, repo.RepoPath())
  612. if err != nil {
  613. return nil, nil, err
  614. }
  615. defer gitRepo.Close()
  616. branches, err = git_model.FindBranchNames(ctx, git_model.FindBranchOptions{
  617. RepoID: repo.ID,
  618. ListOptions: db.ListOptions{
  619. ListAll: true,
  620. },
  621. IsDeletedBranch: util.OptionalBoolFalse,
  622. })
  623. if err != nil {
  624. return nil, nil, err
  625. }
  626. tags, err = gitRepo.GetTags(0, 0)
  627. if err != nil {
  628. return nil, nil, err
  629. }
  630. return branches, tags, nil
  631. }
  632. // CompareDiff show different from one commit to another commit
  633. func CompareDiff(ctx *context.Context) {
  634. ci := ParseCompareInfo(ctx)
  635. defer func() {
  636. if ci != nil && ci.HeadGitRepo != nil {
  637. ci.HeadGitRepo.Close()
  638. }
  639. }()
  640. if ctx.Written() {
  641. return
  642. }
  643. ctx.Data["PullRequestWorkInProgressPrefixes"] = setting.Repository.PullRequest.WorkInProgressPrefixes
  644. ctx.Data["DirectComparison"] = ci.DirectComparison
  645. ctx.Data["OtherCompareSeparator"] = ".."
  646. ctx.Data["CompareSeparator"] = "..."
  647. if ci.DirectComparison {
  648. ctx.Data["CompareSeparator"] = ".."
  649. ctx.Data["OtherCompareSeparator"] = "..."
  650. }
  651. nothingToCompare := PrepareCompareDiff(ctx, ci,
  652. gitdiff.GetWhitespaceFlag(ctx.Data["WhitespaceBehavior"].(string)))
  653. if ctx.Written() {
  654. return
  655. }
  656. baseTags, err := repo_model.GetTagNamesByRepoID(ctx, ctx.Repo.Repository.ID)
  657. if err != nil {
  658. ctx.ServerError("GetTagNamesByRepoID", err)
  659. return
  660. }
  661. ctx.Data["Tags"] = baseTags
  662. fileOnly := ctx.FormBool("file-only")
  663. if fileOnly {
  664. ctx.HTML(http.StatusOK, tplDiffBox)
  665. return
  666. }
  667. headBranches, err := git_model.FindBranchNames(ctx, git_model.FindBranchOptions{
  668. RepoID: ci.HeadRepo.ID,
  669. ListOptions: db.ListOptions{
  670. ListAll: true,
  671. },
  672. IsDeletedBranch: util.OptionalBoolFalse,
  673. })
  674. if err != nil {
  675. ctx.ServerError("GetBranches", err)
  676. return
  677. }
  678. ctx.Data["HeadBranches"] = headBranches
  679. // For compare repo branches
  680. PrepareBranchList(ctx)
  681. if ctx.Written() {
  682. return
  683. }
  684. headTags, err := repo_model.GetTagNamesByRepoID(ctx, ci.HeadRepo.ID)
  685. if err != nil {
  686. ctx.ServerError("GetTagNamesByRepoID", err)
  687. return
  688. }
  689. ctx.Data["HeadTags"] = headTags
  690. if ctx.Data["PageIsComparePull"] == true {
  691. pr, err := issues_model.GetUnmergedPullRequest(ctx, ci.HeadRepo.ID, ctx.Repo.Repository.ID, ci.HeadBranch, ci.BaseBranch, issues_model.PullRequestFlowGithub)
  692. if err != nil {
  693. if !issues_model.IsErrPullRequestNotExist(err) {
  694. ctx.ServerError("GetUnmergedPullRequest", err)
  695. return
  696. }
  697. } else {
  698. ctx.Data["HasPullRequest"] = true
  699. if err := pr.LoadIssue(ctx); err != nil {
  700. ctx.ServerError("LoadIssue", err)
  701. return
  702. }
  703. ctx.Data["PullRequest"] = pr
  704. ctx.HTML(http.StatusOK, tplCompareDiff)
  705. return
  706. }
  707. if !nothingToCompare {
  708. // Setup information for new form.
  709. RetrieveRepoMetas(ctx, ctx.Repo.Repository, true)
  710. if ctx.Written() {
  711. return
  712. }
  713. }
  714. }
  715. beforeCommitID := ctx.Data["BeforeCommitID"].(string)
  716. afterCommitID := ctx.Data["AfterCommitID"].(string)
  717. separator := "..."
  718. if ci.DirectComparison {
  719. separator = ".."
  720. }
  721. ctx.Data["Title"] = "Comparing " + base.ShortSha(beforeCommitID) + separator + base.ShortSha(afterCommitID)
  722. ctx.Data["IsRepoToolbarCommits"] = true
  723. ctx.Data["IsDiffCompare"] = true
  724. _, templateErrs := setTemplateIfExists(ctx, pullRequestTemplateKey, pullRequestTemplateCandidates)
  725. if len(templateErrs) > 0 {
  726. ctx.Flash.Warning(renderErrorOfTemplates(ctx, templateErrs), true)
  727. }
  728. if content, ok := ctx.Data["content"].(string); ok && content != "" {
  729. // If a template content is set, prepend the "content". In this case that's only
  730. // applicable if you have one commit to compare and that commit has a message.
  731. // In that case the commit message will be prepend to the template body.
  732. if templateContent, ok := ctx.Data[pullRequestTemplateKey].(string); ok && templateContent != "" {
  733. // Re-use the same key as that's priortized over the "content" key.
  734. // Add two new lines between the content to ensure there's always at least
  735. // one empty line between them.
  736. ctx.Data[pullRequestTemplateKey] = content + "\n\n" + templateContent
  737. }
  738. // When using form fields, also add content to field with id "body".
  739. if fields, ok := ctx.Data["Fields"].([]*api.IssueFormField); ok {
  740. for _, field := range fields {
  741. if field.ID == "body" {
  742. if fieldValue, ok := field.Attributes["value"].(string); ok && fieldValue != "" {
  743. field.Attributes["value"] = content + "\n\n" + fieldValue
  744. } else {
  745. field.Attributes["value"] = content
  746. }
  747. }
  748. }
  749. }
  750. }
  751. ctx.Data["IsProjectsEnabled"] = ctx.Repo.CanWrite(unit.TypeProjects)
  752. ctx.Data["IsAttachmentEnabled"] = setting.Attachment.Enabled
  753. upload.AddUploadContext(ctx, "comment")
  754. ctx.Data["HasIssuesOrPullsWritePermission"] = ctx.Repo.CanWrite(unit.TypePullRequests)
  755. if unit, err := ctx.Repo.Repository.GetUnit(ctx, unit.TypePullRequests); err == nil {
  756. config := unit.PullRequestsConfig()
  757. ctx.Data["AllowMaintainerEdit"] = config.DefaultAllowMaintainerEdit
  758. } else {
  759. ctx.Data["AllowMaintainerEdit"] = false
  760. }
  761. ctx.HTML(http.StatusOK, tplCompare)
  762. }
  763. // ExcerptBlob render blob excerpt contents
  764. func ExcerptBlob(ctx *context.Context) {
  765. commitID := ctx.Params("sha")
  766. lastLeft := ctx.FormInt("last_left")
  767. lastRight := ctx.FormInt("last_right")
  768. idxLeft := ctx.FormInt("left")
  769. idxRight := ctx.FormInt("right")
  770. leftHunkSize := ctx.FormInt("left_hunk_size")
  771. rightHunkSize := ctx.FormInt("right_hunk_size")
  772. anchor := ctx.FormString("anchor")
  773. direction := ctx.FormString("direction")
  774. filePath := ctx.FormString("path")
  775. gitRepo := ctx.Repo.GitRepo
  776. if ctx.FormBool("wiki") {
  777. var err error
  778. gitRepo, err = git.OpenRepository(ctx, ctx.Repo.Repository.WikiPath())
  779. if err != nil {
  780. ctx.ServerError("OpenRepository", err)
  781. return
  782. }
  783. defer gitRepo.Close()
  784. }
  785. chunkSize := gitdiff.BlobExcerptChunkSize
  786. commit, err := gitRepo.GetCommit(commitID)
  787. if err != nil {
  788. ctx.Error(http.StatusInternalServerError, "GetCommit")
  789. return
  790. }
  791. section := &gitdiff.DiffSection{
  792. FileName: filePath,
  793. Name: filePath,
  794. }
  795. if direction == "up" && (idxLeft-lastLeft) > chunkSize {
  796. idxLeft -= chunkSize
  797. idxRight -= chunkSize
  798. leftHunkSize += chunkSize
  799. rightHunkSize += chunkSize
  800. section.Lines, err = getExcerptLines(commit, filePath, idxLeft-1, idxRight-1, chunkSize)
  801. } else if direction == "down" && (idxLeft-lastLeft) > chunkSize {
  802. section.Lines, err = getExcerptLines(commit, filePath, lastLeft, lastRight, chunkSize)
  803. lastLeft += chunkSize
  804. lastRight += chunkSize
  805. } else {
  806. offset := -1
  807. if direction == "down" {
  808. offset = 0
  809. }
  810. section.Lines, err = getExcerptLines(commit, filePath, lastLeft, lastRight, idxRight-lastRight+offset)
  811. leftHunkSize = 0
  812. rightHunkSize = 0
  813. idxLeft = lastLeft
  814. idxRight = lastRight
  815. }
  816. if err != nil {
  817. ctx.Error(http.StatusInternalServerError, "getExcerptLines")
  818. return
  819. }
  820. if idxRight > lastRight {
  821. lineText := " "
  822. if rightHunkSize > 0 || leftHunkSize > 0 {
  823. lineText = fmt.Sprintf("@@ -%d,%d +%d,%d @@\n", idxLeft, leftHunkSize, idxRight, rightHunkSize)
  824. }
  825. lineText = html.EscapeString(lineText)
  826. lineSection := &gitdiff.DiffLine{
  827. Type: gitdiff.DiffLineSection,
  828. Content: lineText,
  829. SectionInfo: &gitdiff.DiffLineSectionInfo{
  830. Path: filePath,
  831. LastLeftIdx: lastLeft,
  832. LastRightIdx: lastRight,
  833. LeftIdx: idxLeft,
  834. RightIdx: idxRight,
  835. LeftHunkSize: leftHunkSize,
  836. RightHunkSize: rightHunkSize,
  837. },
  838. }
  839. if direction == "up" {
  840. section.Lines = append([]*gitdiff.DiffLine{lineSection}, section.Lines...)
  841. } else if direction == "down" {
  842. section.Lines = append(section.Lines, lineSection)
  843. }
  844. }
  845. ctx.Data["section"] = section
  846. ctx.Data["FileNameHash"] = base.EncodeSha1(filePath)
  847. ctx.Data["AfterCommitID"] = commitID
  848. ctx.Data["Anchor"] = anchor
  849. ctx.HTML(http.StatusOK, tplBlobExcerpt)
  850. }
  851. func getExcerptLines(commit *git.Commit, filePath string, idxLeft, idxRight, chunkSize int) ([]*gitdiff.DiffLine, error) {
  852. blob, err := commit.Tree.GetBlobByPath(filePath)
  853. if err != nil {
  854. return nil, err
  855. }
  856. reader, err := blob.DataAsync()
  857. if err != nil {
  858. return nil, err
  859. }
  860. defer reader.Close()
  861. scanner := bufio.NewScanner(reader)
  862. var diffLines []*gitdiff.DiffLine
  863. for line := 0; line < idxRight+chunkSize; line++ {
  864. if ok := scanner.Scan(); !ok {
  865. break
  866. }
  867. if line < idxRight {
  868. continue
  869. }
  870. lineText := scanner.Text()
  871. diffLine := &gitdiff.DiffLine{
  872. LeftIdx: idxLeft + (line - idxRight) + 1,
  873. RightIdx: line + 1,
  874. Type: gitdiff.DiffLinePlain,
  875. Content: " " + lineText,
  876. }
  877. diffLines = append(diffLines, diffLine)
  878. }
  879. return diffLines, nil
  880. }