view.go 8.7 KB

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. "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["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. buf = bytes.Replace(buf, []byte("\n"), []byte(`<br>`), -1)
  79. }
  80. ctx.Data["FileContent"] = string(buf)
  81. }
  82. }
  83. // Show latest commit info of repository in table header,
  84. // or of directory if not in root directory.
  85. latestCommit := ctx.Repo.Commit
  86. if len(ctx.Repo.TreePath) > 0 {
  87. latestCommit, err = ctx.Repo.Commit.GetCommitByPath(ctx.Repo.TreePath)
  88. if err != nil {
  89. ctx.Handle(500, "GetCommitByPath", err)
  90. return
  91. }
  92. }
  93. ctx.Data["LatestCommit"] = latestCommit
  94. ctx.Data["LatestCommitUser"] = models.ValidateCommitWithEmail(latestCommit)
  95. // Check permission to add or upload new file.
  96. if ctx.Repo.IsWriter() && ctx.Repo.IsViewBranch {
  97. ctx.Data["CanAddFile"] = true
  98. ctx.Data["CanUploadFile"] = setting.Repository.Upload.Enabled
  99. }
  100. }
  101. func renderFile(ctx *context.Context, entry *git.TreeEntry, treeLink, rawLink string) {
  102. ctx.Data["IsViewFile"] = true
  103. blob := entry.Blob()
  104. dataRc, err := blob.Data()
  105. if err != nil {
  106. ctx.Handle(500, "Data", err)
  107. return
  108. }
  109. ctx.Data["FileSize"] = blob.Size()
  110. ctx.Data["FileName"] = blob.Name()
  111. ctx.Data["HighlightClass"] = highlight.FileNameToHighlightClass(blob.Name())
  112. ctx.Data["RawFileLink"] = rawLink + "/" + ctx.Repo.TreePath
  113. buf := make([]byte, 1024)
  114. n, _ := dataRc.Read(buf)
  115. buf = buf[:n]
  116. isTextFile := base.IsTextFile(buf)
  117. ctx.Data["IsTextFile"] = isTextFile
  118. // Assume file is not editable first.
  119. if !isTextFile {
  120. ctx.Data["EditFileTooltip"] = ctx.Tr("repo.editor.cannot_edit_non_text_files")
  121. }
  122. switch {
  123. case isTextFile:
  124. if blob.Size() >= setting.UI.MaxDisplayFileSize {
  125. ctx.Data["IsFileTooLarge"] = true
  126. break
  127. }
  128. d, _ := ioutil.ReadAll(dataRc)
  129. buf = append(buf, d...)
  130. isMarkdown := markdown.IsMarkdownFile(blob.Name())
  131. ctx.Data["IsMarkdown"] = isMarkdown
  132. readmeExist := isMarkdown || markdown.IsReadmeFile(blob.Name())
  133. ctx.Data["ReadmeExist"] = readmeExist
  134. if readmeExist {
  135. // TODO: don't need to render if it's a README but not Markdown file.
  136. ctx.Data["FileContent"] = string(markdown.Render(buf, path.Dir(treeLink), ctx.Repo.Repository.ComposeMetas()))
  137. } else {
  138. // Building code view blocks with line number on server side.
  139. var fileContent string
  140. if err, content := template.ToUTF8WithErr(buf); err != nil {
  141. if err != nil {
  142. log.Error(4, "ToUTF8WithErr: %s", err)
  143. }
  144. fileContent = string(buf)
  145. } else {
  146. fileContent = content
  147. }
  148. var output bytes.Buffer
  149. lines := strings.Split(fileContent, "\n")
  150. for index, line := range lines {
  151. output.WriteString(fmt.Sprintf(`<li class="L%d" rel="L%d">%s</li>`, index+1, index+1, gotemplate.HTMLEscapeString(line)) + "\n")
  152. }
  153. ctx.Data["FileContent"] = gotemplate.HTML(output.String())
  154. output.Reset()
  155. for i := 0; i < len(lines); i++ {
  156. output.WriteString(fmt.Sprintf(`<span id="L%d">%d</span>`, i+1, i+1))
  157. }
  158. ctx.Data["LineNums"] = gotemplate.HTML(output.String())
  159. }
  160. if ctx.Repo.CanEnableEditor() {
  161. ctx.Data["CanEditFile"] = true
  162. ctx.Data["EditFileTooltip"] = ctx.Tr("repo.editor.edit_this_file")
  163. } else if !ctx.Repo.IsViewBranch {
  164. ctx.Data["EditFileTooltip"] = ctx.Tr("repo.editor.must_be_on_a_branch")
  165. } else if !ctx.Repo.IsWriter() {
  166. ctx.Data["EditFileTooltip"] = ctx.Tr("repo.editor.fork_before_edit")
  167. }
  168. case base.IsPDFFile(buf):
  169. ctx.Data["IsPDFFile"] = true
  170. case base.IsImageFile(buf):
  171. ctx.Data["IsImageFile"] = true
  172. }
  173. if ctx.Repo.CanEnableEditor() {
  174. ctx.Data["CanDeleteFile"] = true
  175. ctx.Data["DeleteFileTooltip"] = ctx.Tr("repo.editor.delete_this_file")
  176. } else if !ctx.Repo.IsViewBranch {
  177. ctx.Data["DeleteFileTooltip"] = ctx.Tr("repo.editor.must_be_on_a_branch")
  178. } else if !ctx.Repo.IsWriter() {
  179. ctx.Data["DeleteFileTooltip"] = ctx.Tr("repo.editor.must_have_write_access")
  180. }
  181. }
  182. func Home(ctx *context.Context) {
  183. title := ctx.Repo.Repository.Owner.Name + "/" + ctx.Repo.Repository.Name
  184. if len(ctx.Repo.Repository.Description) > 0 {
  185. title += ": " + ctx.Repo.Repository.Description
  186. }
  187. ctx.Data["Title"] = title
  188. ctx.Data["PageIsViewCode"] = true
  189. ctx.Data["RequireHighlightJS"] = true
  190. branchLink := ctx.Repo.RepoLink + "/src/" + ctx.Repo.BranchName
  191. treeLink := branchLink
  192. rawLink := ctx.Repo.RepoLink + "/raw/" + ctx.Repo.BranchName
  193. if len(ctx.Repo.TreePath) > 0 {
  194. treeLink += "/" + ctx.Repo.TreePath
  195. }
  196. // Get current entry user currently looking at.
  197. entry, err := ctx.Repo.Commit.GetTreeEntryByPath(ctx.Repo.TreePath)
  198. if err != nil {
  199. ctx.NotFoundOrServerError("Repo.Commit.GetTreeEntryByPath", git.IsErrNotExist, err)
  200. return
  201. }
  202. if entry.IsDir() {
  203. renderDirectory(ctx, treeLink)
  204. } else {
  205. renderFile(ctx, entry, treeLink, rawLink)
  206. }
  207. if ctx.Written() {
  208. return
  209. }
  210. ec, err := ctx.Repo.GetEditorconfig()
  211. if err != nil && !git.IsErrNotExist(err) {
  212. ctx.Handle(500, "Repo.GetEditorconfig", err)
  213. return
  214. }
  215. ctx.Data["Editorconfig"] = ec
  216. var treeNames []string
  217. paths := make([]string, 0, 5)
  218. if len(ctx.Repo.TreePath) > 0 {
  219. treeNames = strings.Split(ctx.Repo.TreePath, "/")
  220. for i := range treeNames {
  221. paths = append(paths, strings.Join(treeNames[:i+1], "/"))
  222. }
  223. ctx.Data["HasParentPath"] = true
  224. if len(paths)-2 >= 0 {
  225. ctx.Data["ParentPath"] = "/" + paths[len(paths)-2]
  226. }
  227. }
  228. ctx.Data["Paths"] = paths
  229. ctx.Data["TreeLink"] = treeLink
  230. ctx.Data["TreeNames"] = treeNames
  231. ctx.Data["BranchLink"] = branchLink
  232. ctx.HTML(200, HOME)
  233. }
  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. func Watchers(ctx *context.Context) {
  250. ctx.Data["Title"] = ctx.Tr("repo.watchers")
  251. ctx.Data["CardsTitle"] = ctx.Tr("repo.watchers")
  252. ctx.Data["PageIsWatchers"] = true
  253. RenderUserCards(ctx, ctx.Repo.Repository.NumWatches, ctx.Repo.Repository.GetWatchers, WATCHERS)
  254. }
  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, WATCHERS)
  260. }
  261. func Forks(ctx *context.Context) {
  262. ctx.Data["Title"] = ctx.Tr("repos.forks")
  263. forks, err := ctx.Repo.Repository.GetForks()
  264. if err != nil {
  265. ctx.Handle(500, "GetForks", err)
  266. return
  267. }
  268. for _, fork := range forks {
  269. if err = fork.GetOwner(); err != nil {
  270. ctx.Handle(500, "GetOwner", err)
  271. return
  272. }
  273. }
  274. ctx.Data["Forks"] = forks
  275. ctx.HTML(200, FORKS)
  276. }