gitea源码

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