view.go 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  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["ReadmeInList"] = true
  56. ctx.Data["ReadmeExist"] = true
  57. dataRc, err := readmeFile.Data()
  58. if err != nil {
  59. ctx.Handle(500, "Data", err)
  60. return
  61. }
  62. buf := make([]byte, 1024)
  63. n, _ := dataRc.Read(buf)
  64. if n > 0 {
  65. buf = buf[:n]
  66. }
  67. isTextFile := base.IsTextFile(buf)
  68. ctx.Data["FileIsText"] = isTextFile
  69. ctx.Data["FileName"] = readmeFile.Name()
  70. // FIXME: what happens when README file is an image?
  71. if isTextFile {
  72. d, _ := ioutil.ReadAll(dataRc)
  73. buf = append(buf, d...)
  74. switch {
  75. case markdown.IsMarkdownFile(readmeFile.Name()):
  76. ctx.Data["IsMarkdown"] = true
  77. buf = markdown.Render(buf, treeLink, ctx.Repo.Repository.ComposeMetas())
  78. default:
  79. buf = bytes.Replace(buf, []byte("\n"), []byte(`<br>`), -1)
  80. }
  81. ctx.Data["FileContent"] = string(buf)
  82. }
  83. }
  84. // Show latest commit info of repository in table header,
  85. // or of directory if not in root directory.
  86. latestCommit := ctx.Repo.Commit
  87. if len(ctx.Repo.TreePath) > 0 {
  88. latestCommit, err = ctx.Repo.Commit.GetCommitByPath(ctx.Repo.TreePath)
  89. if err != nil {
  90. ctx.Handle(500, "GetCommitByPath", err)
  91. return
  92. }
  93. }
  94. ctx.Data["LatestCommit"] = latestCommit
  95. ctx.Data["LatestCommitUser"] = models.ValidateCommitWithEmail(latestCommit)
  96. // Check permission to add or upload new file.
  97. if ctx.Repo.IsWriter() && ctx.Repo.IsViewBranch {
  98. ctx.Data["CanAddFile"] = true
  99. ctx.Data["CanUploadFile"] = setting.Repository.Upload.Enabled
  100. }
  101. }
  102. func renderFile(ctx *context.Context, entry *git.TreeEntry, treeLink, rawLink string) {
  103. ctx.Data["IsViewFile"] = true
  104. blob := entry.Blob()
  105. dataRc, err := blob.Data()
  106. if err != nil {
  107. ctx.Handle(500, "Data", err)
  108. return
  109. }
  110. ctx.Data["FileSize"] = blob.Size()
  111. ctx.Data["FileName"] = blob.Name()
  112. ctx.Data["HighlightClass"] = highlight.FileNameToHighlightClass(blob.Name())
  113. ctx.Data["RawFileLink"] = rawLink + "/" + ctx.Repo.TreePath
  114. buf := make([]byte, 1024)
  115. n, _ := dataRc.Read(buf)
  116. if n > 0 {
  117. buf = buf[:n]
  118. }
  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 {
  138. // TODO: don't need to render if it's a README but not Markdown file.
  139. ctx.Data["FileContent"] = string(markdown.Render(buf, path.Dir(treeLink), ctx.Repo.Repository.ComposeMetas()))
  140. } else {
  141. // Building code view blocks with line number on server side.
  142. var fileContent string
  143. if err, content := template.ToUTF8WithErr(buf); err != nil {
  144. if err != nil {
  145. log.Error(4, "ToUTF8WithErr: %s", err)
  146. }
  147. fileContent = string(buf)
  148. } else {
  149. fileContent = content
  150. }
  151. var output bytes.Buffer
  152. lines := strings.Split(fileContent, "\n")
  153. for index, line := range lines {
  154. output.WriteString(fmt.Sprintf(`<li class="L%d" rel="L%d">%s</li>`, index+1, index+1, gotemplate.HTMLEscapeString(line)) + "\n")
  155. }
  156. ctx.Data["FileContent"] = gotemplate.HTML(output.String())
  157. output.Reset()
  158. for i := 0; i < len(lines); i++ {
  159. output.WriteString(fmt.Sprintf(`<span id="L%d">%d</span>`, i+1, i+1))
  160. }
  161. ctx.Data["LineNums"] = gotemplate.HTML(output.String())
  162. }
  163. if ctx.Repo.CanEnableEditor() {
  164. ctx.Data["CanEditFile"] = true
  165. ctx.Data["EditFileTooltip"] = ctx.Tr("repo.editor.edit_this_file")
  166. } else if !ctx.Repo.IsViewBranch {
  167. ctx.Data["EditFileTooltip"] = ctx.Tr("repo.editor.must_be_on_a_branch")
  168. } else if !ctx.Repo.IsWriter() {
  169. ctx.Data["EditFileTooltip"] = ctx.Tr("repo.editor.fork_before_edit")
  170. }
  171. case base.IsPDFFile(buf):
  172. ctx.Data["IsPDFFile"] = true
  173. case base.IsImageFile(buf):
  174. ctx.Data["IsImageFile"] = true
  175. }
  176. if ctx.Repo.CanEnableEditor() {
  177. ctx.Data["CanDeleteFile"] = true
  178. ctx.Data["DeleteFileTooltip"] = ctx.Tr("repo.editor.delete_this_file")
  179. } else if !ctx.Repo.IsViewBranch {
  180. ctx.Data["DeleteFileTooltip"] = ctx.Tr("repo.editor.must_be_on_a_branch")
  181. } else if !ctx.Repo.IsWriter() {
  182. ctx.Data["DeleteFileTooltip"] = ctx.Tr("repo.editor.must_have_write_access")
  183. }
  184. }
  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. ec, err := ctx.Repo.GetEditorconfig()
  214. if err != nil && !git.IsErrNotExist(err) {
  215. ctx.Handle(500, "Repo.GetEditorconfig", err)
  216. return
  217. }
  218. ctx.Data["Editorconfig"] = ec
  219. var treeNames []string
  220. paths := make([]string, 0, 5)
  221. if len(ctx.Repo.TreePath) > 0 {
  222. treeNames = strings.Split(ctx.Repo.TreePath, "/")
  223. for i := range treeNames {
  224. paths = append(paths, strings.Join(treeNames[:i+1], "/"))
  225. }
  226. ctx.Data["HasParentPath"] = true
  227. if len(paths)-2 >= 0 {
  228. ctx.Data["ParentPath"] = "/" + paths[len(paths)-2]
  229. }
  230. }
  231. ctx.Data["Paths"] = paths
  232. ctx.Data["TreeLink"] = treeLink
  233. ctx.Data["TreeNames"] = treeNames
  234. ctx.Data["BranchLink"] = branchLink
  235. ctx.HTML(200, HOME)
  236. }
  237. func RenderUserCards(ctx *context.Context, total int, getter func(page int) ([]*models.User, error), tpl base.TplName) {
  238. page := ctx.QueryInt("page")
  239. if page <= 0 {
  240. page = 1
  241. }
  242. pager := paginater.New(total, models.ItemsPerPage, page, 5)
  243. ctx.Data["Page"] = pager
  244. items, err := getter(pager.Current())
  245. if err != nil {
  246. ctx.Handle(500, "getter", err)
  247. return
  248. }
  249. ctx.Data["Cards"] = items
  250. ctx.HTML(200, tpl)
  251. }
  252. func Watchers(ctx *context.Context) {
  253. ctx.Data["Title"] = ctx.Tr("repo.watchers")
  254. ctx.Data["CardsTitle"] = ctx.Tr("repo.watchers")
  255. ctx.Data["PageIsWatchers"] = true
  256. RenderUserCards(ctx, ctx.Repo.Repository.NumWatches, ctx.Repo.Repository.GetWatchers, WATCHERS)
  257. }
  258. func Stars(ctx *context.Context) {
  259. ctx.Data["Title"] = ctx.Tr("repo.stargazers")
  260. ctx.Data["CardsTitle"] = ctx.Tr("repo.stargazers")
  261. ctx.Data["PageIsStargazers"] = true
  262. RenderUserCards(ctx, ctx.Repo.Repository.NumStars, ctx.Repo.Repository.GetStargazers, WATCHERS)
  263. }
  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, FORKS)
  279. }