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.

324 lines
8.9 KiB

10 years ago
9 years ago
9 years ago
9 years ago
  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.IsImageFile(buf):
  173. ctx.Data["IsImageFile"] = true
  174. }
  175. if ctx.Repo.CanEnableEditor() {
  176. ctx.Data["CanDeleteFile"] = true
  177. ctx.Data["DeleteFileTooltip"] = ctx.Tr("repo.editor.delete_this_file")
  178. } else if !ctx.Repo.IsViewBranch {
  179. ctx.Data["DeleteFileTooltip"] = ctx.Tr("repo.editor.must_be_on_a_branch")
  180. } else if !ctx.Repo.IsWriter() {
  181. ctx.Data["DeleteFileTooltip"] = ctx.Tr("repo.editor.must_have_write_access")
  182. }
  183. }
  184. // Home render repository home page
  185. func Home(ctx *context.Context) {
  186. title := ctx.Repo.Repository.Owner.Name + "/" + ctx.Repo.Repository.Name
  187. if len(ctx.Repo.Repository.Description) > 0 {
  188. title += ": " + ctx.Repo.Repository.Description
  189. }
  190. ctx.Data["Title"] = title
  191. ctx.Data["PageIsViewCode"] = true
  192. ctx.Data["RequireHighlightJS"] = true
  193. branchLink := ctx.Repo.RepoLink + "/src/" + ctx.Repo.BranchName
  194. treeLink := branchLink
  195. rawLink := ctx.Repo.RepoLink + "/raw/" + ctx.Repo.BranchName
  196. if len(ctx.Repo.TreePath) > 0 {
  197. treeLink += "/" + ctx.Repo.TreePath
  198. }
  199. // Get current entry user currently looking at.
  200. entry, err := ctx.Repo.Commit.GetTreeEntryByPath(ctx.Repo.TreePath)
  201. if err != nil {
  202. ctx.NotFoundOrServerError("Repo.Commit.GetTreeEntryByPath", git.IsErrNotExist, err)
  203. return
  204. }
  205. if entry.IsDir() {
  206. renderDirectory(ctx, treeLink)
  207. } else {
  208. renderFile(ctx, entry, treeLink, rawLink)
  209. }
  210. if ctx.Written() {
  211. return
  212. }
  213. var treeNames []string
  214. paths := make([]string, 0, 5)
  215. if len(ctx.Repo.TreePath) > 0 {
  216. treeNames = strings.Split(ctx.Repo.TreePath, "/")
  217. for i := range treeNames {
  218. paths = append(paths, strings.Join(treeNames[:i+1], "/"))
  219. }
  220. ctx.Data["HasParentPath"] = true
  221. if len(paths)-2 >= 0 {
  222. ctx.Data["ParentPath"] = "/" + paths[len(paths)-2]
  223. }
  224. }
  225. ctx.Data["Paths"] = paths
  226. ctx.Data["TreeLink"] = treeLink
  227. ctx.Data["TreeNames"] = treeNames
  228. ctx.Data["BranchLink"] = branchLink
  229. ctx.HTML(200, tplRepoHome)
  230. }
  231. // RenderUserCards render a page show users accroding the input templaet
  232. func RenderUserCards(ctx *context.Context, total int, getter func(page int) ([]*models.User, error), tpl base.TplName) {
  233. page := ctx.QueryInt("page")
  234. if page <= 0 {
  235. page = 1
  236. }
  237. pager := paginater.New(total, models.ItemsPerPage, page, 5)
  238. ctx.Data["Page"] = pager
  239. items, err := getter(pager.Current())
  240. if err != nil {
  241. ctx.Handle(500, "getter", err)
  242. return
  243. }
  244. ctx.Data["Cards"] = items
  245. ctx.HTML(200, tpl)
  246. }
  247. // Watchers render repository's watch users
  248. func Watchers(ctx *context.Context) {
  249. ctx.Data["Title"] = ctx.Tr("repo.watchers")
  250. ctx.Data["CardsTitle"] = ctx.Tr("repo.watchers")
  251. ctx.Data["PageIsWatchers"] = true
  252. RenderUserCards(ctx, ctx.Repo.Repository.NumWatches, ctx.Repo.Repository.GetWatchers, tplWatchers)
  253. }
  254. // Stars render repository's starred users
  255. func Stars(ctx *context.Context) {
  256. ctx.Data["Title"] = ctx.Tr("repo.stargazers")
  257. ctx.Data["CardsTitle"] = ctx.Tr("repo.stargazers")
  258. ctx.Data["PageIsStargazers"] = true
  259. RenderUserCards(ctx, ctx.Repo.Repository.NumStars, ctx.Repo.Repository.GetStargazers, tplWatchers)
  260. }
  261. // Forks render repository's forked users
  262. func Forks(ctx *context.Context) {
  263. ctx.Data["Title"] = ctx.Tr("repos.forks")
  264. forks, err := ctx.Repo.Repository.GetForks()
  265. if err != nil {
  266. ctx.Handle(500, "GetForks", err)
  267. return
  268. }
  269. for _, fork := range forks {
  270. if err = fork.GetOwner(); err != nil {
  271. ctx.Handle(500, "GetOwner", err)
  272. return
  273. }
  274. }
  275. ctx.Data["Forks"] = forks
  276. ctx.HTML(200, tplForks)
  277. }