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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  1. // Copyright 2014 The Gogs 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. "bytes"
  7. "fmt"
  8. gotemplate "html/template"
  9. "io/ioutil"
  10. "path"
  11. "strings"
  12. "code.gitea.io/git"
  13. "code.gitea.io/gitea/models"
  14. "code.gitea.io/gitea/modules/base"
  15. "code.gitea.io/gitea/modules/context"
  16. "code.gitea.io/gitea/modules/highlight"
  17. "code.gitea.io/gitea/modules/log"
  18. "code.gitea.io/gitea/modules/markdown"
  19. "code.gitea.io/gitea/modules/setting"
  20. "code.gitea.io/gitea/modules/templates"
  21. "github.com/Unknwon/paginater"
  22. )
  23. const (
  24. tplRepoHome base.TplName = "repo/home"
  25. tplWatchers base.TplName = "repo/watchers"
  26. tplForks base.TplName = "repo/forks"
  27. )
  28. func renderDirectory(ctx *context.Context, treeLink string) {
  29. tree, err := ctx.Repo.Commit.SubTree(ctx.Repo.TreePath)
  30. if err != nil {
  31. ctx.NotFoundOrServerError("Repo.Commit.SubTree", git.IsErrNotExist, err)
  32. return
  33. }
  34. entries, err := tree.ListEntries()
  35. if err != nil {
  36. ctx.Handle(500, "ListEntries", err)
  37. return
  38. }
  39. entries.Sort()
  40. ctx.Data["Files"], err = entries.GetCommitsInfo(ctx.Repo.Commit, ctx.Repo.TreePath)
  41. if err != nil {
  42. ctx.Handle(500, "GetCommitsInfo", err)
  43. return
  44. }
  45. var readmeFile *git.Blob
  46. for _, entry := range entries {
  47. if entry.IsDir() || !markdown.IsReadmeFile(entry.Name()) {
  48. continue
  49. }
  50. // TODO: collect all possible README files and show with priority.
  51. readmeFile = entry.Blob()
  52. break
  53. }
  54. if readmeFile != nil {
  55. ctx.Data["RawFileLink"] = ""
  56. ctx.Data["ReadmeInList"] = true
  57. ctx.Data["ReadmeExist"] = true
  58. dataRc, err := readmeFile.Data()
  59. if err != nil {
  60. ctx.Handle(500, "Data", err)
  61. return
  62. }
  63. buf := make([]byte, 1024)
  64. n, _ := dataRc.Read(buf)
  65. buf = buf[:n]
  66. isTextFile := base.IsTextFile(buf)
  67. ctx.Data["FileIsText"] = isTextFile
  68. ctx.Data["FileName"] = readmeFile.Name()
  69. // FIXME: what happens when README file is an image?
  70. if isTextFile {
  71. d, _ := ioutil.ReadAll(dataRc)
  72. buf = append(buf, d...)
  73. switch {
  74. case markdown.IsMarkdownFile(readmeFile.Name()):
  75. ctx.Data["IsMarkdown"] = true
  76. buf = markdown.Render(buf, treeLink, ctx.Repo.Repository.ComposeMetas())
  77. default:
  78. // FIXME This is the only way to show non-markdown files
  79. // instead of a broken "View Raw" link
  80. ctx.Data["IsMarkdown"] = true
  81. buf = bytes.Replace(buf, []byte("\n"), []byte(`<br>`), -1)
  82. }
  83. ctx.Data["FileContent"] = string(buf)
  84. }
  85. }
  86. // Show latest commit info of repository in table header,
  87. // or of directory if not in root directory.
  88. latestCommit := ctx.Repo.Commit
  89. if len(ctx.Repo.TreePath) > 0 {
  90. latestCommit, err = ctx.Repo.Commit.GetCommitByPath(ctx.Repo.TreePath)
  91. if err != nil {
  92. ctx.Handle(500, "GetCommitByPath", err)
  93. return
  94. }
  95. }
  96. ctx.Data["LatestCommit"] = latestCommit
  97. ctx.Data["LatestCommitUser"] = models.ValidateCommitWithEmail(latestCommit)
  98. // Check permission to add or upload new file.
  99. if ctx.Repo.IsWriter() && ctx.Repo.IsViewBranch {
  100. ctx.Data["CanAddFile"] = true
  101. ctx.Data["CanUploadFile"] = setting.Repository.Upload.Enabled
  102. }
  103. }
  104. func renderFile(ctx *context.Context, entry *git.TreeEntry, treeLink, rawLink string) {
  105. ctx.Data["IsViewFile"] = true
  106. blob := entry.Blob()
  107. dataRc, err := blob.Data()
  108. if err != nil {
  109. ctx.Handle(500, "Data", err)
  110. return
  111. }
  112. ctx.Data["FileSize"] = blob.Size()
  113. ctx.Data["FileName"] = blob.Name()
  114. ctx.Data["HighlightClass"] = highlight.FileNameToHighlightClass(blob.Name())
  115. ctx.Data["RawFileLink"] = rawLink + "/" + ctx.Repo.TreePath
  116. buf := make([]byte, 1024)
  117. n, _ := dataRc.Read(buf)
  118. buf = buf[:n]
  119. isTextFile := base.IsTextFile(buf)
  120. ctx.Data["IsTextFile"] = isTextFile
  121. // Assume file is not editable first.
  122. if !isTextFile {
  123. ctx.Data["EditFileTooltip"] = ctx.Tr("repo.editor.cannot_edit_non_text_files")
  124. }
  125. switch {
  126. case isTextFile:
  127. if blob.Size() >= setting.UI.MaxDisplayFileSize {
  128. ctx.Data["IsFileTooLarge"] = true
  129. break
  130. }
  131. d, _ := ioutil.ReadAll(dataRc)
  132. buf = append(buf, d...)
  133. isMarkdown := markdown.IsMarkdownFile(blob.Name())
  134. ctx.Data["IsMarkdown"] = isMarkdown
  135. readmeExist := isMarkdown || markdown.IsReadmeFile(blob.Name())
  136. ctx.Data["ReadmeExist"] = readmeExist
  137. if readmeExist && isMarkdown {
  138. ctx.Data["FileContent"] = string(markdown.Render(buf, path.Dir(treeLink), ctx.Repo.Repository.ComposeMetas()))
  139. } else {
  140. // Building code view blocks with line number on server side.
  141. var fileContent string
  142. if content, err := templates.ToUTF8WithErr(buf); err != nil {
  143. if err != nil {
  144. log.Error(4, "ToUTF8WithErr: %s", err)
  145. }
  146. fileContent = string(buf)
  147. } else {
  148. fileContent = content
  149. }
  150. var output bytes.Buffer
  151. lines := strings.Split(fileContent, "\n")
  152. for index, line := range lines {
  153. output.WriteString(fmt.Sprintf(`<li class="L%d" rel="L%d">%s</li>`, index+1, index+1, gotemplate.HTMLEscapeString(line)) + "\n")
  154. }
  155. ctx.Data["FileContent"] = gotemplate.HTML(output.String())
  156. output.Reset()
  157. for i := 0; i < len(lines); i++ {
  158. output.WriteString(fmt.Sprintf(`<span id="L%d">%d</span>`, i+1, i+1))
  159. }
  160. ctx.Data["LineNums"] = gotemplate.HTML(output.String())
  161. }
  162. if ctx.Repo.CanEnableEditor() {
  163. ctx.Data["CanEditFile"] = true
  164. ctx.Data["EditFileTooltip"] = ctx.Tr("repo.editor.edit_this_file")
  165. } else if !ctx.Repo.IsViewBranch {
  166. ctx.Data["EditFileTooltip"] = ctx.Tr("repo.editor.must_be_on_a_branch")
  167. } else if !ctx.Repo.IsWriter() {
  168. ctx.Data["EditFileTooltip"] = ctx.Tr("repo.editor.fork_before_edit")
  169. }
  170. case base.IsPDFFile(buf):
  171. ctx.Data["IsPDFFile"] = true
  172. case base.IsVideoFile(buf):
  173. ctx.Data["IsVideoFile"] = true
  174. case base.IsImageFile(buf):
  175. ctx.Data["IsImageFile"] = true
  176. }
  177. if ctx.Repo.CanEnableEditor() {
  178. ctx.Data["CanDeleteFile"] = true
  179. ctx.Data["DeleteFileTooltip"] = ctx.Tr("repo.editor.delete_this_file")
  180. } else if !ctx.Repo.IsViewBranch {
  181. ctx.Data["DeleteFileTooltip"] = ctx.Tr("repo.editor.must_be_on_a_branch")
  182. } else if !ctx.Repo.IsWriter() {
  183. ctx.Data["DeleteFileTooltip"] = ctx.Tr("repo.editor.must_have_write_access")
  184. }
  185. }
  186. // Home render repository home page
  187. func Home(ctx *context.Context) {
  188. title := ctx.Repo.Repository.Owner.Name + "/" + ctx.Repo.Repository.Name
  189. if len(ctx.Repo.Repository.Description) > 0 {
  190. title += ": " + ctx.Repo.Repository.Description
  191. }
  192. ctx.Data["Title"] = title
  193. ctx.Data["PageIsViewCode"] = true
  194. ctx.Data["RequireHighlightJS"] = true
  195. branchLink := ctx.Repo.RepoLink + "/src/" + ctx.Repo.BranchName
  196. treeLink := branchLink
  197. rawLink := ctx.Repo.RepoLink + "/raw/" + ctx.Repo.BranchName
  198. if len(ctx.Repo.TreePath) > 0 {
  199. treeLink += "/" + ctx.Repo.TreePath
  200. }
  201. // Get current entry user currently looking at.
  202. entry, err := ctx.Repo.Commit.GetTreeEntryByPath(ctx.Repo.TreePath)
  203. if err != nil {
  204. ctx.NotFoundOrServerError("Repo.Commit.GetTreeEntryByPath", git.IsErrNotExist, err)
  205. return
  206. }
  207. if entry.IsDir() {
  208. renderDirectory(ctx, treeLink)
  209. } else {
  210. renderFile(ctx, entry, treeLink, rawLink)
  211. }
  212. if ctx.Written() {
  213. return
  214. }
  215. var treeNames []string
  216. paths := make([]string, 0, 5)
  217. if len(ctx.Repo.TreePath) > 0 {
  218. treeNames = strings.Split(ctx.Repo.TreePath, "/")
  219. for i := range treeNames {
  220. paths = append(paths, strings.Join(treeNames[:i+1], "/"))
  221. }
  222. ctx.Data["HasParentPath"] = true
  223. if len(paths)-2 >= 0 {
  224. ctx.Data["ParentPath"] = "/" + paths[len(paths)-2]
  225. }
  226. }
  227. ctx.Data["Paths"] = paths
  228. ctx.Data["TreeLink"] = treeLink
  229. ctx.Data["TreeNames"] = treeNames
  230. ctx.Data["BranchLink"] = branchLink
  231. ctx.HTML(200, tplRepoHome)
  232. }
  233. // RenderUserCards render a page show users accroding the input templaet
  234. func RenderUserCards(ctx *context.Context, total int, getter func(page int) ([]*models.User, error), tpl base.TplName) {
  235. page := ctx.QueryInt("page")
  236. if page <= 0 {
  237. page = 1
  238. }
  239. pager := paginater.New(total, models.ItemsPerPage, page, 5)
  240. ctx.Data["Page"] = pager
  241. items, err := getter(pager.Current())
  242. if err != nil {
  243. ctx.Handle(500, "getter", err)
  244. return
  245. }
  246. ctx.Data["Cards"] = items
  247. ctx.HTML(200, tpl)
  248. }
  249. // Watchers render repository's watch users
  250. func Watchers(ctx *context.Context) {
  251. ctx.Data["Title"] = ctx.Tr("repo.watchers")
  252. ctx.Data["CardsTitle"] = ctx.Tr("repo.watchers")
  253. ctx.Data["PageIsWatchers"] = true
  254. RenderUserCards(ctx, ctx.Repo.Repository.NumWatches, ctx.Repo.Repository.GetWatchers, tplWatchers)
  255. }
  256. // Stars render repository's starred users
  257. func Stars(ctx *context.Context) {
  258. ctx.Data["Title"] = ctx.Tr("repo.stargazers")
  259. ctx.Data["CardsTitle"] = ctx.Tr("repo.stargazers")
  260. ctx.Data["PageIsStargazers"] = true
  261. RenderUserCards(ctx, ctx.Repo.Repository.NumStars, ctx.Repo.Repository.GetStargazers, tplWatchers)
  262. }
  263. // Forks render repository's forked users
  264. func Forks(ctx *context.Context) {
  265. ctx.Data["Title"] = ctx.Tr("repos.forks")
  266. forks, err := ctx.Repo.Repository.GetForks()
  267. if err != nil {
  268. ctx.Handle(500, "GetForks", err)
  269. return
  270. }
  271. for _, fork := range forks {
  272. if err = fork.GetOwner(); err != nil {
  273. ctx.Handle(500, "GetOwner", err)
  274. return
  275. }
  276. }
  277. ctx.Data["Forks"] = forks
  278. ctx.HTML(200, tplForks)
  279. }