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.

view.go 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  1. // Copyright 2017 The Gitea Authors. All rights reserved.
  2. // Copyright 2014 The Gogs Authors. All rights reserved.
  3. // Use of this source code is governed by a MIT-style
  4. // license that can be found in the LICENSE file.
  5. package repo
  6. import (
  7. "bytes"
  8. "encoding/base64"
  9. "fmt"
  10. gotemplate "html/template"
  11. "io/ioutil"
  12. "path"
  13. "strings"
  14. "code.gitea.io/git"
  15. "code.gitea.io/gitea/models"
  16. "code.gitea.io/gitea/modules/base"
  17. "code.gitea.io/gitea/modules/context"
  18. "code.gitea.io/gitea/modules/highlight"
  19. "code.gitea.io/gitea/modules/lfs"
  20. "code.gitea.io/gitea/modules/log"
  21. "code.gitea.io/gitea/modules/markup"
  22. "code.gitea.io/gitea/modules/setting"
  23. "code.gitea.io/gitea/modules/templates"
  24. "github.com/Unknwon/paginater"
  25. )
  26. const (
  27. tplRepoEMPTY base.TplName = "repo/empty"
  28. tplRepoHome base.TplName = "repo/home"
  29. tplWatchers base.TplName = "repo/watchers"
  30. tplForks base.TplName = "repo/forks"
  31. )
  32. func renderDirectory(ctx *context.Context, treeLink string) {
  33. tree, err := ctx.Repo.Commit.SubTree(ctx.Repo.TreePath)
  34. if err != nil {
  35. ctx.NotFoundOrServerError("Repo.Commit.SubTree", git.IsErrNotExist, err)
  36. return
  37. }
  38. entries, err := tree.ListEntries()
  39. if err != nil {
  40. ctx.ServerError("ListEntries", err)
  41. return
  42. }
  43. entries.CustomSort(base.NaturalSortLess)
  44. ctx.Data["Files"], err = entries.GetCommitsInfo(ctx.Repo.Commit, ctx.Repo.TreePath)
  45. if err != nil {
  46. ctx.ServerError("GetCommitsInfo", err)
  47. return
  48. }
  49. // 3 for the extensions in exts[] in order
  50. // the last one is for a readme that doesn't
  51. // strictly match an extension
  52. var readmeFiles [4]*git.Blob
  53. var exts = []string{".md", ".txt", ""} // sorted by priority
  54. for _, entry := range entries {
  55. if entry.IsDir() {
  56. continue
  57. }
  58. for i, ext := range exts {
  59. if markup.IsReadmeFile(entry.Name(), ext) {
  60. readmeFiles[i] = entry.Blob()
  61. }
  62. }
  63. if markup.IsReadmeFile(entry.Name()) {
  64. readmeFiles[3] = entry.Blob()
  65. }
  66. }
  67. var readmeFile *git.Blob
  68. for _, f := range readmeFiles {
  69. if f != nil {
  70. readmeFile = f
  71. break
  72. }
  73. }
  74. if readmeFile != nil {
  75. ctx.Data["RawFileLink"] = ""
  76. ctx.Data["ReadmeInList"] = true
  77. ctx.Data["ReadmeExist"] = true
  78. dataRc, err := readmeFile.DataAsync()
  79. if err != nil {
  80. ctx.ServerError("Data", err)
  81. return
  82. }
  83. defer dataRc.Close()
  84. buf := make([]byte, 1024)
  85. n, _ := dataRc.Read(buf)
  86. buf = buf[:n]
  87. isTextFile := base.IsTextFile(buf)
  88. ctx.Data["FileIsText"] = isTextFile
  89. ctx.Data["FileName"] = readmeFile.Name()
  90. // FIXME: what happens when README file is an image?
  91. if isTextFile {
  92. if readmeFile.Size() >= setting.UI.MaxDisplayFileSize {
  93. // Pretend that this is a normal text file to display 'This file is too large to be shown'
  94. ctx.Data["IsFileTooLarge"] = true
  95. ctx.Data["IsTextFile"] = true
  96. ctx.Data["FileSize"] = readmeFile.Size()
  97. } else {
  98. d, _ := ioutil.ReadAll(dataRc)
  99. buf = templates.ToUTF8WithFallback(append(buf, d...))
  100. if markup.Type(readmeFile.Name()) != "" {
  101. ctx.Data["IsMarkup"] = true
  102. ctx.Data["FileContent"] = string(markup.Render(readmeFile.Name(), buf, treeLink, ctx.Repo.Repository.ComposeMetas()))
  103. } else {
  104. ctx.Data["IsRenderedHTML"] = true
  105. ctx.Data["FileContent"] = strings.Replace(
  106. gotemplate.HTMLEscapeString(string(buf)), "\n", `<br>`, -1,
  107. )
  108. }
  109. }
  110. }
  111. }
  112. // Show latest commit info of repository in table header,
  113. // or of directory if not in root directory.
  114. latestCommit := ctx.Repo.Commit
  115. if len(ctx.Repo.TreePath) > 0 {
  116. latestCommit, err = ctx.Repo.Commit.GetCommitByPath(ctx.Repo.TreePath)
  117. if err != nil {
  118. ctx.ServerError("GetCommitByPath", err)
  119. return
  120. }
  121. }
  122. ctx.Data["LatestCommit"] = latestCommit
  123. ctx.Data["LatestCommitVerification"] = models.ParseCommitWithSignature(latestCommit)
  124. ctx.Data["LatestCommitUser"] = models.ValidateCommitWithEmail(latestCommit)
  125. statuses, err := models.GetLatestCommitStatus(ctx.Repo.Repository, ctx.Repo.Commit.ID.String(), 0)
  126. if err != nil {
  127. log.Error(3, "GetLatestCommitStatus: %v", err)
  128. }
  129. ctx.Data["LatestCommitStatus"] = models.CalcCommitStatus(statuses)
  130. // Check permission to add or upload new file.
  131. if ctx.Repo.CanWrite(models.UnitTypeCode) && ctx.Repo.IsViewBranch {
  132. ctx.Data["CanAddFile"] = !ctx.Repo.Repository.IsArchived
  133. ctx.Data["CanUploadFile"] = setting.Repository.Upload.Enabled && !ctx.Repo.Repository.IsArchived
  134. }
  135. }
  136. func renderFile(ctx *context.Context, entry *git.TreeEntry, treeLink, rawLink string) {
  137. ctx.Data["IsViewFile"] = true
  138. blob := entry.Blob()
  139. dataRc, err := blob.DataAsync()
  140. if err != nil {
  141. ctx.ServerError("DataAsync", err)
  142. return
  143. }
  144. defer dataRc.Close()
  145. ctx.Data["Title"] = ctx.Data["Title"].(string) + " - " + ctx.Repo.TreePath + " at " + ctx.Repo.BranchName
  146. ctx.Data["FileSize"] = blob.Size()
  147. ctx.Data["FileName"] = blob.Name()
  148. ctx.Data["HighlightClass"] = highlight.FileNameToHighlightClass(blob.Name())
  149. ctx.Data["RawFileLink"] = rawLink + "/" + ctx.Repo.TreePath
  150. buf := make([]byte, 1024)
  151. n, _ := dataRc.Read(buf)
  152. buf = buf[:n]
  153. isTextFile := base.IsTextFile(buf)
  154. isLFSFile := false
  155. ctx.Data["IsTextFile"] = isTextFile
  156. //Check for LFS meta file
  157. if isTextFile {
  158. if meta := lfs.IsPointerFile(&buf); meta != nil {
  159. if meta, _ = ctx.Repo.Repository.GetLFSMetaObjectByOid(meta.Oid); meta != nil {
  160. ctx.Data["IsLFSFile"] = true
  161. isLFSFile = true
  162. // OK read the lfs object
  163. dataRc, err := lfs.ReadMetaObject(meta)
  164. if err != nil {
  165. ctx.ServerError("ReadMetaObject", err)
  166. return
  167. }
  168. defer dataRc.Close()
  169. buf = make([]byte, 1024)
  170. n, _ = dataRc.Read(buf)
  171. buf = buf[:n]
  172. isTextFile = base.IsTextFile(buf)
  173. ctx.Data["IsTextFile"] = isTextFile
  174. ctx.Data["FileSize"] = meta.Size
  175. filenameBase64 := base64.RawURLEncoding.EncodeToString([]byte(blob.Name()))
  176. ctx.Data["RawFileLink"] = fmt.Sprintf("%s%s.git/info/lfs/objects/%s/%s", setting.AppURL, ctx.Repo.Repository.FullName(), meta.Oid, filenameBase64)
  177. }
  178. }
  179. }
  180. // Assume file is not editable first.
  181. if isLFSFile {
  182. ctx.Data["EditFileTooltip"] = ctx.Tr("repo.editor.cannot_edit_lfs_files")
  183. } else if !isTextFile {
  184. ctx.Data["EditFileTooltip"] = ctx.Tr("repo.editor.cannot_edit_non_text_files")
  185. }
  186. switch {
  187. case isTextFile:
  188. if blob.Size() >= setting.UI.MaxDisplayFileSize {
  189. ctx.Data["IsFileTooLarge"] = true
  190. break
  191. }
  192. d, _ := ioutil.ReadAll(dataRc)
  193. buf = templates.ToUTF8WithFallback(append(buf, d...))
  194. readmeExist := markup.IsReadmeFile(blob.Name())
  195. ctx.Data["ReadmeExist"] = readmeExist
  196. if markup.Type(blob.Name()) != "" {
  197. ctx.Data["IsMarkup"] = true
  198. ctx.Data["FileContent"] = string(markup.Render(blob.Name(), buf, path.Dir(treeLink), ctx.Repo.Repository.ComposeMetas()))
  199. } else if readmeExist {
  200. ctx.Data["IsRenderedHTML"] = true
  201. ctx.Data["FileContent"] = strings.Replace(
  202. gotemplate.HTMLEscapeString(string(buf)), "\n", `<br>`, -1,
  203. )
  204. } else {
  205. // Building code view blocks with line number on server side.
  206. var fileContent string
  207. if content, err := templates.ToUTF8WithErr(buf); err != nil {
  208. if err != nil {
  209. log.Error(4, "ToUTF8WithErr: %v", err)
  210. }
  211. fileContent = string(buf)
  212. } else {
  213. fileContent = content
  214. }
  215. var output bytes.Buffer
  216. lines := strings.Split(fileContent, "\n")
  217. //Remove blank line at the end of file
  218. if len(lines) > 0 && lines[len(lines)-1] == "" {
  219. lines = lines[:len(lines)-1]
  220. }
  221. for index, line := range lines {
  222. line = gotemplate.HTMLEscapeString(line)
  223. if index != len(lines)-1 {
  224. line += "\n"
  225. }
  226. output.WriteString(fmt.Sprintf(`<li class="L%d" rel="L%d">%s</li>`, index+1, index+1, line))
  227. }
  228. ctx.Data["FileContent"] = gotemplate.HTML(output.String())
  229. output.Reset()
  230. for i := 0; i < len(lines); i++ {
  231. output.WriteString(fmt.Sprintf(`<span id="L%d">%d</span>`, i+1, i+1))
  232. }
  233. ctx.Data["LineNums"] = gotemplate.HTML(output.String())
  234. }
  235. if !isLFSFile {
  236. if ctx.Repo.CanEnableEditor() {
  237. ctx.Data["CanEditFile"] = true
  238. ctx.Data["EditFileTooltip"] = ctx.Tr("repo.editor.edit_this_file")
  239. } else if !ctx.Repo.IsViewBranch {
  240. ctx.Data["EditFileTooltip"] = ctx.Tr("repo.editor.must_be_on_a_branch")
  241. } else if !ctx.Repo.CanWrite(models.UnitTypeCode) {
  242. ctx.Data["EditFileTooltip"] = ctx.Tr("repo.editor.fork_before_edit")
  243. }
  244. }
  245. case base.IsPDFFile(buf):
  246. ctx.Data["IsPDFFile"] = true
  247. case base.IsVideoFile(buf):
  248. ctx.Data["IsVideoFile"] = true
  249. case base.IsAudioFile(buf):
  250. ctx.Data["IsAudioFile"] = true
  251. case base.IsImageFile(buf):
  252. ctx.Data["IsImageFile"] = true
  253. }
  254. if ctx.Repo.CanEnableEditor() {
  255. ctx.Data["CanDeleteFile"] = true
  256. ctx.Data["DeleteFileTooltip"] = ctx.Tr("repo.editor.delete_this_file")
  257. } else if !ctx.Repo.IsViewBranch {
  258. ctx.Data["DeleteFileTooltip"] = ctx.Tr("repo.editor.must_be_on_a_branch")
  259. } else if !ctx.Repo.CanWrite(models.UnitTypeCode) {
  260. ctx.Data["DeleteFileTooltip"] = ctx.Tr("repo.editor.must_have_write_access")
  261. }
  262. }
  263. // Home render repository home page
  264. func Home(ctx *context.Context) {
  265. if len(ctx.Repo.Units) > 0 {
  266. var firstUnit *models.Unit
  267. for _, repoUnit := range ctx.Repo.Units {
  268. if repoUnit.Type == models.UnitTypeCode {
  269. renderCode(ctx)
  270. return
  271. }
  272. unit, ok := models.Units[repoUnit.Type]
  273. if ok && (firstUnit == nil || !firstUnit.IsLessThan(unit)) {
  274. firstUnit = &unit
  275. }
  276. }
  277. if firstUnit != nil {
  278. ctx.Redirect(fmt.Sprintf("%s/%s%s", setting.AppSubURL, ctx.Repo.Repository.FullName(), firstUnit.URI))
  279. return
  280. }
  281. }
  282. ctx.NotFound("Home", fmt.Errorf(ctx.Tr("units.error.no_unit_allowed_repo")))
  283. }
  284. func renderCode(ctx *context.Context) {
  285. ctx.Data["PageIsViewCode"] = true
  286. if ctx.Repo.Repository.IsEmpty {
  287. ctx.HTML(200, tplRepoEMPTY)
  288. return
  289. }
  290. title := ctx.Repo.Repository.Owner.Name + "/" + ctx.Repo.Repository.Name
  291. if len(ctx.Repo.Repository.Description) > 0 {
  292. title += ": " + ctx.Repo.Repository.Description
  293. }
  294. ctx.Data["Title"] = title
  295. ctx.Data["RequireHighlightJS"] = true
  296. branchLink := ctx.Repo.RepoLink + "/src/" + ctx.Repo.BranchNameSubURL()
  297. treeLink := branchLink
  298. rawLink := ctx.Repo.RepoLink + "/raw/" + ctx.Repo.BranchNameSubURL()
  299. if len(ctx.Repo.TreePath) > 0 {
  300. treeLink += "/" + ctx.Repo.TreePath
  301. }
  302. // Get Topics of this repo
  303. topics, err := models.FindTopics(&models.FindTopicOptions{
  304. RepoID: ctx.Repo.Repository.ID,
  305. })
  306. if err != nil {
  307. ctx.ServerError("models.FindTopics", err)
  308. return
  309. }
  310. ctx.Data["Topics"] = topics
  311. // Get current entry user currently looking at.
  312. entry, err := ctx.Repo.Commit.GetTreeEntryByPath(ctx.Repo.TreePath)
  313. if err != nil {
  314. ctx.NotFoundOrServerError("Repo.Commit.GetTreeEntryByPath", git.IsErrNotExist, err)
  315. return
  316. }
  317. if entry.IsDir() {
  318. renderDirectory(ctx, treeLink)
  319. } else {
  320. renderFile(ctx, entry, treeLink, rawLink)
  321. }
  322. if ctx.Written() {
  323. return
  324. }
  325. var treeNames []string
  326. paths := make([]string, 0, 5)
  327. if len(ctx.Repo.TreePath) > 0 {
  328. treeNames = strings.Split(ctx.Repo.TreePath, "/")
  329. for i := range treeNames {
  330. paths = append(paths, strings.Join(treeNames[:i+1], "/"))
  331. }
  332. ctx.Data["HasParentPath"] = true
  333. if len(paths)-2 >= 0 {
  334. ctx.Data["ParentPath"] = "/" + paths[len(paths)-2]
  335. }
  336. }
  337. ctx.Data["Paths"] = paths
  338. ctx.Data["TreeLink"] = treeLink
  339. ctx.Data["TreeNames"] = treeNames
  340. ctx.Data["BranchLink"] = branchLink
  341. ctx.HTML(200, tplRepoHome)
  342. }
  343. // RenderUserCards render a page show users according the input templaet
  344. func RenderUserCards(ctx *context.Context, total int, getter func(page int) ([]*models.User, error), tpl base.TplName) {
  345. page := ctx.QueryInt("page")
  346. if page <= 0 {
  347. page = 1
  348. }
  349. pager := paginater.New(total, models.ItemsPerPage, page, 5)
  350. ctx.Data["Page"] = pager
  351. items, err := getter(pager.Current())
  352. if err != nil {
  353. ctx.ServerError("getter", err)
  354. return
  355. }
  356. ctx.Data["Cards"] = items
  357. ctx.HTML(200, tpl)
  358. }
  359. // Watchers render repository's watch users
  360. func Watchers(ctx *context.Context) {
  361. ctx.Data["Title"] = ctx.Tr("repo.watchers")
  362. ctx.Data["CardsTitle"] = ctx.Tr("repo.watchers")
  363. ctx.Data["PageIsWatchers"] = true
  364. RenderUserCards(ctx, ctx.Repo.Repository.NumWatches, ctx.Repo.Repository.GetWatchers, tplWatchers)
  365. }
  366. // Stars render repository's starred users
  367. func Stars(ctx *context.Context) {
  368. ctx.Data["Title"] = ctx.Tr("repo.stargazers")
  369. ctx.Data["CardsTitle"] = ctx.Tr("repo.stargazers")
  370. ctx.Data["PageIsStargazers"] = true
  371. RenderUserCards(ctx, ctx.Repo.Repository.NumStars, ctx.Repo.Repository.GetStargazers, tplWatchers)
  372. }
  373. // Forks render repository's forked users
  374. func Forks(ctx *context.Context) {
  375. ctx.Data["Title"] = ctx.Tr("repos.forks")
  376. forks, err := ctx.Repo.Repository.GetForks()
  377. if err != nil {
  378. ctx.ServerError("GetForks", err)
  379. return
  380. }
  381. for _, fork := range forks {
  382. if err = fork.GetOwner(); err != nil {
  383. ctx.ServerError("GetOwner", err)
  384. return
  385. }
  386. }
  387. ctx.Data["Forks"] = forks
  388. ctx.HTML(200, tplForks)
  389. }