view.go 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  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. log "gopkg.in/clog.v1"
  14. "github.com/gogits/git-module"
  15. "github.com/gogits/gogs/models"
  16. "github.com/gogits/gogs/modules/base"
  17. "github.com/gogits/gogs/modules/context"
  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.GetCommitsInfoWithCustomConcurrency(ctx.Repo.Commit, ctx.Repo.TreePath, setting.Repository.CommitsFetchConcurrency)
  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. if ctx.Repo.CanEnableEditor() {
  95. ctx.Data["CanAddFile"] = true
  96. ctx.Data["CanUploadFile"] = setting.Repository.Upload.Enabled
  97. }
  98. }
  99. func renderFile(ctx *context.Context, entry *git.TreeEntry, treeLink, rawLink string) {
  100. ctx.Data["IsViewFile"] = true
  101. blob := entry.Blob()
  102. dataRc, err := blob.Data()
  103. if err != nil {
  104. ctx.Handle(500, "Data", err)
  105. return
  106. }
  107. ctx.Data["FileSize"] = blob.Size()
  108. ctx.Data["FileName"] = blob.Name()
  109. ctx.Data["HighlightClass"] = highlight.FileNameToHighlightClass(blob.Name())
  110. ctx.Data["RawFileLink"] = rawLink + "/" + ctx.Repo.TreePath
  111. buf := make([]byte, 1024)
  112. n, _ := dataRc.Read(buf)
  113. buf = buf[:n]
  114. isTextFile := base.IsTextFile(buf)
  115. ctx.Data["IsTextFile"] = isTextFile
  116. // Assume file is not editable first.
  117. if !isTextFile {
  118. ctx.Data["EditFileTooltip"] = ctx.Tr("repo.editor.cannot_edit_non_text_files")
  119. }
  120. canEnableEditor := ctx.Repo.CanEnableEditor()
  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. ctx.Data["IsIPythonNotebook"] = strings.HasSuffix(blob.Name(), ".ipynb")
  133. if isMarkdown {
  134. ctx.Data["FileContent"] = string(markdown.Render(buf, path.Dir(treeLink), ctx.Repo.Repository.ComposeMetas()))
  135. } else {
  136. // Building code view blocks with line number on server side.
  137. var fileContent string
  138. if err, content := template.ToUTF8WithErr(buf); err != nil {
  139. if err != nil {
  140. log.Error(4, "ToUTF8WithErr: %s", err)
  141. }
  142. fileContent = string(buf)
  143. } else {
  144. fileContent = content
  145. }
  146. var output bytes.Buffer
  147. lines := strings.Split(fileContent, "\n")
  148. for index, line := range lines {
  149. output.WriteString(fmt.Sprintf(`<li class="L%d" rel="L%d">%s</li>`, index+1, index+1, gotemplate.HTMLEscapeString(line)) + "\n")
  150. }
  151. ctx.Data["FileContent"] = gotemplate.HTML(output.String())
  152. output.Reset()
  153. for i := 0; i < len(lines); i++ {
  154. output.WriteString(fmt.Sprintf(`<span id="L%d">%d</span>`, i+1, i+1))
  155. }
  156. ctx.Data["LineNums"] = gotemplate.HTML(output.String())
  157. }
  158. if canEnableEditor {
  159. ctx.Data["CanEditFile"] = true
  160. ctx.Data["EditFileTooltip"] = ctx.Tr("repo.editor.edit_this_file")
  161. } else if !ctx.Repo.IsViewBranch {
  162. ctx.Data["EditFileTooltip"] = ctx.Tr("repo.editor.must_be_on_a_branch")
  163. } else if !ctx.Repo.IsWriter() {
  164. ctx.Data["EditFileTooltip"] = ctx.Tr("repo.editor.fork_before_edit")
  165. }
  166. case base.IsPDFFile(buf):
  167. ctx.Data["IsPDFFile"] = true
  168. case base.IsVideoFile(buf):
  169. ctx.Data["IsVideoFile"] = true
  170. case base.IsImageFile(buf):
  171. ctx.Data["IsImageFile"] = true
  172. }
  173. if 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 setEditorconfigIfExists(ctx *context.Context) {
  183. ec, err := ctx.Repo.GetEditorconfig()
  184. if err != nil && !git.IsErrNotExist(err) {
  185. log.Trace("setEditorconfigIfExists.GetEditorconfig [%d]: %v", ctx.Repo.Repository.ID, err)
  186. return
  187. }
  188. ctx.Data["Editorconfig"] = ec
  189. }
  190. func Home(ctx *context.Context) {
  191. title := ctx.Repo.Repository.Owner.Name + "/" + ctx.Repo.Repository.Name
  192. if len(ctx.Repo.Repository.Description) > 0 {
  193. title += ": " + ctx.Repo.Repository.Description
  194. }
  195. ctx.Data["Title"] = title
  196. if ctx.Repo.BranchName != ctx.Repo.Repository.DefaultBranch {
  197. ctx.Data["Title"] = title + " @ " + ctx.Repo.BranchName
  198. }
  199. ctx.Data["PageIsViewCode"] = true
  200. ctx.Data["RequireHighlightJS"] = true
  201. branchLink := ctx.Repo.RepoLink + "/src/" + ctx.Repo.BranchName
  202. treeLink := branchLink
  203. rawLink := ctx.Repo.RepoLink + "/raw/" + ctx.Repo.BranchName
  204. if len(ctx.Repo.TreePath) > 0 {
  205. treeLink += "/" + ctx.Repo.TreePath
  206. }
  207. // Get current entry user currently looking at.
  208. entry, err := ctx.Repo.Commit.GetTreeEntryByPath(ctx.Repo.TreePath)
  209. if err != nil {
  210. ctx.NotFoundOrServerError("Repo.Commit.GetTreeEntryByPath", git.IsErrNotExist, err)
  211. return
  212. }
  213. if entry.IsDir() {
  214. renderDirectory(ctx, treeLink)
  215. } else {
  216. renderFile(ctx, entry, treeLink, rawLink)
  217. }
  218. if ctx.Written() {
  219. return
  220. }
  221. setEditorconfigIfExists(ctx)
  222. if ctx.Written() {
  223. return
  224. }
  225. var treeNames []string
  226. paths := make([]string, 0, 5)
  227. if len(ctx.Repo.TreePath) > 0 {
  228. treeNames = strings.Split(ctx.Repo.TreePath, "/")
  229. for i := range treeNames {
  230. paths = append(paths, strings.Join(treeNames[:i+1], "/"))
  231. }
  232. ctx.Data["HasParentPath"] = true
  233. if len(paths)-2 >= 0 {
  234. ctx.Data["ParentPath"] = "/" + paths[len(paths)-2]
  235. }
  236. }
  237. ctx.Data["Paths"] = paths
  238. ctx.Data["TreeLink"] = treeLink
  239. ctx.Data["TreeNames"] = treeNames
  240. ctx.Data["BranchLink"] = branchLink
  241. ctx.HTML(200, HOME)
  242. }
  243. func RenderUserCards(ctx *context.Context, total int, getter func(page int) ([]*models.User, error), tpl base.TplName) {
  244. page := ctx.QueryInt("page")
  245. if page <= 0 {
  246. page = 1
  247. }
  248. pager := paginater.New(total, models.ItemsPerPage, page, 5)
  249. ctx.Data["Page"] = pager
  250. items, err := getter(pager.Current())
  251. if err != nil {
  252. ctx.Handle(500, "getter", err)
  253. return
  254. }
  255. ctx.Data["Cards"] = items
  256. ctx.HTML(200, tpl)
  257. }
  258. func Watchers(ctx *context.Context) {
  259. ctx.Data["Title"] = ctx.Tr("repo.watchers")
  260. ctx.Data["CardsTitle"] = ctx.Tr("repo.watchers")
  261. ctx.Data["PageIsWatchers"] = true
  262. RenderUserCards(ctx, ctx.Repo.Repository.NumWatches, ctx.Repo.Repository.GetWatchers, WATCHERS)
  263. }
  264. func Stars(ctx *context.Context) {
  265. ctx.Data["Title"] = ctx.Tr("repo.stargazers")
  266. ctx.Data["CardsTitle"] = ctx.Tr("repo.stargazers")
  267. ctx.Data["PageIsStargazers"] = true
  268. RenderUserCards(ctx, ctx.Repo.Repository.NumStars, ctx.Repo.Repository.GetStargazers, WATCHERS)
  269. }
  270. func Forks(ctx *context.Context) {
  271. ctx.Data["Title"] = ctx.Tr("repos.forks")
  272. forks, err := ctx.Repo.Repository.GetForks()
  273. if err != nil {
  274. ctx.Handle(500, "GetForks", err)
  275. return
  276. }
  277. for _, fork := range forks {
  278. if err = fork.GetOwner(); err != nil {
  279. ctx.Handle(500, "GetOwner", err)
  280. return
  281. }
  282. }
  283. ctx.Data["Forks"] = forks
  284. ctx.HTML(200, FORKS)
  285. }