view.go 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  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. "github.com/Unknwon/paginater"
  13. "github.com/gogits/git-module"
  14. "github.com/gogits/gogs/models"
  15. "github.com/gogits/gogs/modules/base"
  16. "github.com/gogits/gogs/modules/context"
  17. "github.com/gogits/gogs/modules/log"
  18. "github.com/gogits/gogs/modules/markdown"
  19. "github.com/gogits/gogs/modules/setting"
  20. "github.com/gogits/gogs/modules/template"
  21. "github.com/gogits/gogs/modules/template/highlight"
  22. )
  23. const (
  24. HOME base.TplName = "repo/home"
  25. WATCHERS base.TplName = "repo/watchers"
  26. FORKS 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["IsTextFile"] = isTextFile
  68. ctx.Data["FileName"] = readmeFile.Name()
  69. if isTextFile {
  70. d, _ := ioutil.ReadAll(dataRc)
  71. buf = append(buf, d...)
  72. switch {
  73. case markdown.IsMarkdownFile(readmeFile.Name()):
  74. ctx.Data["IsMarkdown"] = true
  75. buf = markdown.Render(buf, treeLink, ctx.Repo.Repository.ComposeMetas())
  76. default:
  77. buf = bytes.Replace(buf, []byte("\n"), []byte(`<br>`), -1)
  78. }
  79. ctx.Data["FileContent"] = string(buf)
  80. }
  81. }
  82. // Show latest commit info of repository in table header,
  83. // or of directory if not in root directory.
  84. latestCommit := ctx.Repo.Commit
  85. if len(ctx.Repo.TreePath) > 0 {
  86. latestCommit, err = ctx.Repo.Commit.GetCommitByPath(ctx.Repo.TreePath)
  87. if err != nil {
  88. ctx.Handle(500, "GetCommitByPath", err)
  89. return
  90. }
  91. }
  92. ctx.Data["LatestCommit"] = latestCommit
  93. ctx.Data["LatestCommitUser"] = models.ValidateCommitWithEmail(latestCommit)
  94. // Check permission to add or upload new file.
  95. if ctx.Repo.IsWriter() && ctx.Repo.IsViewBranch {
  96. ctx.Data["CanAddFile"] = true
  97. ctx.Data["CanUploadFile"] = setting.Repository.Upload.Enabled
  98. }
  99. }
  100. func renderFile(ctx *context.Context, entry *git.TreeEntry, treeLink, rawLink string) {
  101. ctx.Data["IsViewFile"] = true
  102. blob := entry.Blob()
  103. dataRc, err := blob.Data()
  104. if err != nil {
  105. ctx.Handle(500, "Data", err)
  106. return
  107. }
  108. ctx.Data["FileSize"] = blob.Size()
  109. ctx.Data["FileName"] = blob.Name()
  110. ctx.Data["HighlightClass"] = highlight.FileNameToHighlightClass(blob.Name())
  111. ctx.Data["RawFileLink"] = rawLink + "/" + ctx.Repo.TreePath
  112. buf := make([]byte, 1024)
  113. n, _ := dataRc.Read(buf)
  114. buf = buf[:n]
  115. isTextFile := base.IsTextFile(buf)
  116. ctx.Data["IsTextFile"] = isTextFile
  117. // Assume file is not editable first.
  118. if !isTextFile {
  119. ctx.Data["EditFileTooltip"] = ctx.Tr("repo.editor.cannot_edit_non_text_files")
  120. }
  121. switch {
  122. case isTextFile:
  123. if blob.Size() >= setting.UI.MaxDisplayFileSize {
  124. ctx.Data["IsFileTooLarge"] = true
  125. break
  126. }
  127. d, _ := ioutil.ReadAll(dataRc)
  128. buf = append(buf, d...)
  129. isMarkdown := markdown.IsMarkdownFile(blob.Name())
  130. ctx.Data["IsMarkdown"] = isMarkdown
  131. ctx.Data["ReadmeExist"] = isMarkdown && markdown.IsReadmeFile(blob.Name())
  132. if isMarkdown {
  133. ctx.Data["FileContent"] = string(markdown.Render(buf, path.Dir(treeLink), ctx.Repo.Repository.ComposeMetas()))
  134. } else {
  135. // Building code view blocks with line number on server side.
  136. var fileContent string
  137. if err, content := template.ToUTF8WithErr(buf); err != nil {
  138. if err != nil {
  139. log.Error(4, "ToUTF8WithErr: %s", err)
  140. }
  141. fileContent = string(buf)
  142. } else {
  143. fileContent = content
  144. }
  145. var output bytes.Buffer
  146. lines := strings.Split(fileContent, "\n")
  147. for index, line := range lines {
  148. output.WriteString(fmt.Sprintf(`<li class="L%d" rel="L%d">%s</li>`, index+1, index+1, gotemplate.HTMLEscapeString(line)) + "\n")
  149. }
  150. ctx.Data["FileContent"] = gotemplate.HTML(output.String())
  151. output.Reset()
  152. for i := 0; i < len(lines); i++ {
  153. output.WriteString(fmt.Sprintf(`<span id="L%d">%d</span>`, i+1, i+1))
  154. }
  155. ctx.Data["LineNums"] = gotemplate.HTML(output.String())
  156. }
  157. if ctx.Repo.CanEnableEditor() {
  158. ctx.Data["CanEditFile"] = true
  159. ctx.Data["EditFileTooltip"] = ctx.Tr("repo.editor.edit_this_file")
  160. } else if !ctx.Repo.IsViewBranch {
  161. ctx.Data["EditFileTooltip"] = ctx.Tr("repo.editor.must_be_on_a_branch")
  162. } else if !ctx.Repo.IsWriter() {
  163. ctx.Data["EditFileTooltip"] = ctx.Tr("repo.editor.fork_before_edit")
  164. }
  165. case base.IsPDFFile(buf):
  166. ctx.Data["IsPDFFile"] = true
  167. case base.IsVideoFile(buf):
  168. ctx.Data["IsVideoFile"] = true
  169. case base.IsImageFile(buf):
  170. ctx.Data["IsImageFile"] = true
  171. }
  172. if ctx.Repo.CanEnableEditor() {
  173. ctx.Data["CanDeleteFile"] = true
  174. ctx.Data["DeleteFileTooltip"] = ctx.Tr("repo.editor.delete_this_file")
  175. } else if !ctx.Repo.IsViewBranch {
  176. ctx.Data["DeleteFileTooltip"] = ctx.Tr("repo.editor.must_be_on_a_branch")
  177. } else if !ctx.Repo.IsWriter() {
  178. ctx.Data["DeleteFileTooltip"] = ctx.Tr("repo.editor.must_have_write_access")
  179. }
  180. }
  181. func Home(ctx *context.Context) {
  182. title := ctx.Repo.Repository.Owner.Name + "/" + ctx.Repo.Repository.Name
  183. if len(ctx.Repo.Repository.Description) > 0 {
  184. title += ": " + ctx.Repo.Repository.Description
  185. }
  186. ctx.Data["Title"] = title
  187. ctx.Data["PageIsViewCode"] = true
  188. ctx.Data["RequireHighlightJS"] = true
  189. branchLink := ctx.Repo.RepoLink + "/src/" + ctx.Repo.BranchName
  190. treeLink := branchLink
  191. rawLink := ctx.Repo.RepoLink + "/raw/" + ctx.Repo.BranchName
  192. if len(ctx.Repo.TreePath) > 0 {
  193. treeLink += "/" + ctx.Repo.TreePath
  194. }
  195. // Get current entry user currently looking at.
  196. entry, err := ctx.Repo.Commit.GetTreeEntryByPath(ctx.Repo.TreePath)
  197. if err != nil {
  198. ctx.NotFoundOrServerError("Repo.Commit.GetTreeEntryByPath", git.IsErrNotExist, err)
  199. return
  200. }
  201. if entry.IsDir() {
  202. renderDirectory(ctx, treeLink)
  203. } else {
  204. renderFile(ctx, entry, treeLink, rawLink)
  205. }
  206. if ctx.Written() {
  207. return
  208. }
  209. setEditorconfigIfExists(ctx)
  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, HOME)
  230. }
  231. func RenderUserCards(ctx *context.Context, total int, getter func(page int) ([]*models.User, error), tpl base.TplName) {
  232. page := ctx.QueryInt("page")
  233. if page <= 0 {
  234. page = 1
  235. }
  236. pager := paginater.New(total, models.ItemsPerPage, page, 5)
  237. ctx.Data["Page"] = pager
  238. items, err := getter(pager.Current())
  239. if err != nil {
  240. ctx.Handle(500, "getter", err)
  241. return
  242. }
  243. ctx.Data["Cards"] = items
  244. ctx.HTML(200, tpl)
  245. }
  246. func Watchers(ctx *context.Context) {
  247. ctx.Data["Title"] = ctx.Tr("repo.watchers")
  248. ctx.Data["CardsTitle"] = ctx.Tr("repo.watchers")
  249. ctx.Data["PageIsWatchers"] = true
  250. RenderUserCards(ctx, ctx.Repo.Repository.NumWatches, ctx.Repo.Repository.GetWatchers, WATCHERS)
  251. }
  252. func Stars(ctx *context.Context) {
  253. ctx.Data["Title"] = ctx.Tr("repo.stargazers")
  254. ctx.Data["CardsTitle"] = ctx.Tr("repo.stargazers")
  255. ctx.Data["PageIsStargazers"] = true
  256. RenderUserCards(ctx, ctx.Repo.Repository.NumStars, ctx.Repo.Repository.GetStargazers, WATCHERS)
  257. }
  258. func Forks(ctx *context.Context) {
  259. ctx.Data["Title"] = ctx.Tr("repos.forks")
  260. forks, err := ctx.Repo.Repository.GetForks()
  261. if err != nil {
  262. ctx.Handle(500, "GetForks", err)
  263. return
  264. }
  265. for _, fork := range forks {
  266. if err = fork.GetOwner(); err != nil {
  267. ctx.Handle(500, "GetOwner", err)
  268. return
  269. }
  270. }
  271. ctx.Data["Forks"] = forks
  272. ctx.HTML(200, FORKS)
  273. }