view.go 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  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. BARE base.TplName = "repo/bare"
  25. HOME base.TplName = "repo/home"
  26. WATCHERS base.TplName = "repo/watchers"
  27. FORKS base.TplName = "repo/forks"
  28. )
  29. func renderDirectory(ctx *context.Context, treeLink string) {
  30. tree, err := ctx.Repo.Commit.SubTree(ctx.Repo.TreePath)
  31. if err != nil {
  32. ctx.NotFoundOrServerError("Repo.Commit.SubTree", git.IsErrNotExist, err)
  33. return
  34. }
  35. entries, err := tree.ListEntries()
  36. if err != nil {
  37. ctx.Handle(500, "ListEntries", err)
  38. return
  39. }
  40. entries.Sort()
  41. ctx.Data["Files"], err = entries.GetCommitsInfoWithCustomConcurrency(ctx.Repo.Commit, ctx.Repo.TreePath, setting.Repository.CommitsFetchConcurrency)
  42. if err != nil {
  43. ctx.Handle(500, "GetCommitsInfo", err)
  44. return
  45. }
  46. var readmeFile *git.Blob
  47. for _, entry := range entries {
  48. if entry.IsDir() || !markdown.IsReadmeFile(entry.Name()) {
  49. continue
  50. }
  51. // TODO: collect all possible README files and show with priority.
  52. readmeFile = entry.Blob()
  53. break
  54. }
  55. if readmeFile != nil {
  56. ctx.Data["RawFileLink"] = ""
  57. ctx.Data["ReadmeInList"] = true
  58. ctx.Data["ReadmeExist"] = true
  59. dataRc, err := readmeFile.Data()
  60. if err != nil {
  61. ctx.Handle(500, "Data", err)
  62. return
  63. }
  64. buf := make([]byte, 1024)
  65. n, _ := dataRc.Read(buf)
  66. buf = buf[:n]
  67. isTextFile := base.IsTextFile(buf)
  68. ctx.Data["IsTextFile"] = isTextFile
  69. ctx.Data["FileName"] = readmeFile.Name()
  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. if ctx.Repo.CanEnableEditor() {
  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. canEnableEditor := ctx.Repo.CanEnableEditor()
  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. ctx.Data["ReadmeExist"] = isMarkdown && markdown.IsReadmeFile(blob.Name())
  133. ctx.Data["IsIPythonNotebook"] = strings.HasSuffix(blob.Name(), ".ipynb")
  134. if isMarkdown {
  135. ctx.Data["FileContent"] = string(markdown.Render(buf, path.Dir(treeLink), ctx.Repo.Repository.ComposeMetas()))
  136. } else {
  137. // Building code view blocks with line number on server side.
  138. var fileContent string
  139. if err, content := template.ToUTF8WithErr(buf); err != nil {
  140. if err != nil {
  141. log.Error(4, "ToUTF8WithErr: %s", err)
  142. }
  143. fileContent = string(buf)
  144. } else {
  145. fileContent = content
  146. }
  147. var output bytes.Buffer
  148. lines := strings.Split(fileContent, "\n")
  149. for index, line := range lines {
  150. output.WriteString(fmt.Sprintf(`<li class="L%d" rel="L%d">%s</li>`, index+1, index+1, gotemplate.HTMLEscapeString(line)) + "\n")
  151. }
  152. ctx.Data["FileContent"] = gotemplate.HTML(output.String())
  153. output.Reset()
  154. for i := 0; i < len(lines); i++ {
  155. output.WriteString(fmt.Sprintf(`<span id="L%d">%d</span>`, i+1, i+1))
  156. }
  157. ctx.Data["LineNums"] = gotemplate.HTML(output.String())
  158. }
  159. if canEnableEditor {
  160. ctx.Data["CanEditFile"] = true
  161. ctx.Data["EditFileTooltip"] = ctx.Tr("repo.editor.edit_this_file")
  162. } else if !ctx.Repo.IsViewBranch {
  163. ctx.Data["EditFileTooltip"] = ctx.Tr("repo.editor.must_be_on_a_branch")
  164. } else if !ctx.Repo.IsWriter() {
  165. ctx.Data["EditFileTooltip"] = ctx.Tr("repo.editor.fork_before_edit")
  166. }
  167. case base.IsPDFFile(buf):
  168. ctx.Data["IsPDFFile"] = true
  169. case base.IsVideoFile(buf):
  170. ctx.Data["IsVideoFile"] = true
  171. case base.IsImageFile(buf):
  172. ctx.Data["IsImageFile"] = true
  173. }
  174. if canEnableEditor {
  175. ctx.Data["CanDeleteFile"] = true
  176. ctx.Data["DeleteFileTooltip"] = ctx.Tr("repo.editor.delete_this_file")
  177. } else if !ctx.Repo.IsViewBranch {
  178. ctx.Data["DeleteFileTooltip"] = ctx.Tr("repo.editor.must_be_on_a_branch")
  179. } else if !ctx.Repo.IsWriter() {
  180. ctx.Data["DeleteFileTooltip"] = ctx.Tr("repo.editor.must_have_write_access")
  181. }
  182. }
  183. func setEditorconfigIfExists(ctx *context.Context) {
  184. ec, err := ctx.Repo.GetEditorconfig()
  185. if err != nil && !git.IsErrNotExist(err) {
  186. log.Trace("setEditorconfigIfExists.GetEditorconfig [%d]: %v", ctx.Repo.Repository.ID, err)
  187. return
  188. }
  189. ctx.Data["Editorconfig"] = ec
  190. }
  191. func Home(ctx *context.Context) {
  192. ctx.Data["PageIsViewFiles"] = true
  193. if ctx.Repo.Repository.IsBare {
  194. ctx.HTML(200, BARE)
  195. return
  196. }
  197. title := ctx.Repo.Repository.Owner.Name + "/" + ctx.Repo.Repository.Name
  198. if len(ctx.Repo.Repository.Description) > 0 {
  199. title += ": " + ctx.Repo.Repository.Description
  200. }
  201. ctx.Data["Title"] = title
  202. if ctx.Repo.BranchName != ctx.Repo.Repository.DefaultBranch {
  203. ctx.Data["Title"] = title + " @ " + ctx.Repo.BranchName
  204. }
  205. ctx.Data["RequireHighlightJS"] = true
  206. branchLink := ctx.Repo.RepoLink + "/src/" + ctx.Repo.BranchName
  207. treeLink := branchLink
  208. rawLink := ctx.Repo.RepoLink + "/raw/" + ctx.Repo.BranchName
  209. isRootDir := false
  210. if len(ctx.Repo.TreePath) > 0 {
  211. treeLink += "/" + ctx.Repo.TreePath
  212. } else {
  213. isRootDir = true
  214. // Only show Git stats panel when view root directory
  215. var err error
  216. ctx.Repo.CommitsCount, err = ctx.Repo.Commit.CommitsCount()
  217. if err != nil {
  218. ctx.Handle(500, "CommitsCount", err)
  219. return
  220. }
  221. ctx.Data["CommitsCount"] = ctx.Repo.CommitsCount
  222. }
  223. ctx.Data["PageIsRepoHome"] = isRootDir
  224. // Get current entry user currently looking at.
  225. entry, err := ctx.Repo.Commit.GetTreeEntryByPath(ctx.Repo.TreePath)
  226. if err != nil {
  227. ctx.NotFoundOrServerError("Repo.Commit.GetTreeEntryByPath", git.IsErrNotExist, err)
  228. return
  229. }
  230. if entry.IsDir() {
  231. renderDirectory(ctx, treeLink)
  232. } else {
  233. renderFile(ctx, entry, treeLink, rawLink)
  234. }
  235. if ctx.Written() {
  236. return
  237. }
  238. setEditorconfigIfExists(ctx)
  239. if ctx.Written() {
  240. return
  241. }
  242. var treeNames []string
  243. paths := make([]string, 0, 5)
  244. if len(ctx.Repo.TreePath) > 0 {
  245. treeNames = strings.Split(ctx.Repo.TreePath, "/")
  246. for i := range treeNames {
  247. paths = append(paths, strings.Join(treeNames[:i+1], "/"))
  248. }
  249. ctx.Data["HasParentPath"] = true
  250. if len(paths)-2 >= 0 {
  251. ctx.Data["ParentPath"] = "/" + paths[len(paths)-2]
  252. }
  253. }
  254. ctx.Data["Paths"] = paths
  255. ctx.Data["TreeLink"] = treeLink
  256. ctx.Data["TreeNames"] = treeNames
  257. ctx.Data["BranchLink"] = branchLink
  258. ctx.HTML(200, HOME)
  259. }
  260. func RenderUserCards(ctx *context.Context, total int, getter func(page int) ([]*models.User, error), tpl base.TplName) {
  261. page := ctx.QueryInt("page")
  262. if page <= 0 {
  263. page = 1
  264. }
  265. pager := paginater.New(total, models.ItemsPerPage, page, 5)
  266. ctx.Data["Page"] = pager
  267. items, err := getter(pager.Current())
  268. if err != nil {
  269. ctx.Handle(500, "getter", err)
  270. return
  271. }
  272. ctx.Data["Cards"] = items
  273. ctx.HTML(200, tpl)
  274. }
  275. func Watchers(ctx *context.Context) {
  276. ctx.Data["Title"] = ctx.Tr("repo.watchers")
  277. ctx.Data["CardsTitle"] = ctx.Tr("repo.watchers")
  278. ctx.Data["PageIsWatchers"] = true
  279. RenderUserCards(ctx, ctx.Repo.Repository.NumWatches, ctx.Repo.Repository.GetWatchers, WATCHERS)
  280. }
  281. func Stars(ctx *context.Context) {
  282. ctx.Data["Title"] = ctx.Tr("repo.stargazers")
  283. ctx.Data["CardsTitle"] = ctx.Tr("repo.stargazers")
  284. ctx.Data["PageIsStargazers"] = true
  285. RenderUserCards(ctx, ctx.Repo.Repository.NumStars, ctx.Repo.Repository.GetStargazers, WATCHERS)
  286. }
  287. func Forks(ctx *context.Context) {
  288. ctx.Data["Title"] = ctx.Tr("repos.forks")
  289. forks, err := ctx.Repo.Repository.GetForks()
  290. if err != nil {
  291. ctx.Handle(500, "GetForks", err)
  292. return
  293. }
  294. for _, fork := range forks {
  295. if err = fork.GetOwner(); err != nil {
  296. ctx.Handle(500, "GetOwner", err)
  297. return
  298. }
  299. }
  300. ctx.Data["Forks"] = forks
  301. ctx.HTML(200, FORKS)
  302. }