view.go 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  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/pkg/context"
  17. "github.com/gogits/gogs/pkg/markup"
  18. "github.com/gogits/gogs/pkg/setting"
  19. "github.com/gogits/gogs/pkg/template"
  20. "github.com/gogits/gogs/pkg/template/highlight"
  21. "github.com/gogits/gogs/pkg/tool"
  22. )
  23. const (
  24. BARE = "repo/bare"
  25. HOME = "repo/home"
  26. WATCHERS = "repo/watchers"
  27. FORKS = "repo/forks"
  28. )
  29. func renderDirectory(c *context.Context, treeLink string) {
  30. tree, err := c.Repo.Commit.SubTree(c.Repo.TreePath)
  31. if err != nil {
  32. c.NotFoundOrServerError("Repo.Commit.SubTree", git.IsErrNotExist, err)
  33. return
  34. }
  35. entries, err := tree.ListEntries()
  36. if err != nil {
  37. c.ServerError("ListEntries", err)
  38. return
  39. }
  40. entries.Sort()
  41. c.Data["Files"], err = entries.GetCommitsInfoWithCustomConcurrency(c.Repo.Commit, c.Repo.TreePath, setting.Repository.CommitsFetchConcurrency)
  42. if err != nil {
  43. c.ServerError("GetCommitsInfoWithCustomConcurrency", err)
  44. return
  45. }
  46. var readmeFile *git.Blob
  47. for _, entry := range entries {
  48. if entry.IsDir() || !markup.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. c.Data["RawFileLink"] = ""
  57. c.Data["ReadmeInList"] = true
  58. c.Data["ReadmeExist"] = true
  59. dataRc, err := readmeFile.Data()
  60. if err != nil {
  61. c.ServerError("readmeFile.Data", err)
  62. return
  63. }
  64. buf := make([]byte, 1024)
  65. n, _ := dataRc.Read(buf)
  66. buf = buf[:n]
  67. isTextFile := tool.IsTextFile(buf)
  68. c.Data["IsTextFile"] = isTextFile
  69. c.Data["FileName"] = readmeFile.Name()
  70. if isTextFile {
  71. d, _ := ioutil.ReadAll(dataRc)
  72. buf = append(buf, d...)
  73. switch {
  74. case markup.IsMarkdownFile(readmeFile.Name()):
  75. c.Data["IsMarkdown"] = true
  76. buf = markup.Markdown(buf, treeLink, c.Repo.Repository.ComposeMetas())
  77. case markup.IsIPythonNotebook(readmeFile.Name()):
  78. c.Data["IsIPythonNotebook"] = true
  79. c.Data["RawFileLink"] = c.Repo.RepoLink + "/raw/" + path.Join(c.Repo.BranchName, c.Repo.TreePath, readmeFile.Name())
  80. default:
  81. buf = bytes.Replace(buf, []byte("\n"), []byte(`<br>`), -1)
  82. }
  83. c.Data["FileContent"] = string(buf)
  84. }
  85. }
  86. // Show latest commit info of repository in table header,
  87. // or of directory if not in root directory.
  88. latestCommit := c.Repo.Commit
  89. if len(c.Repo.TreePath) > 0 {
  90. latestCommit, err = c.Repo.Commit.GetCommitByPath(c.Repo.TreePath)
  91. if err != nil {
  92. c.ServerError("GetCommitByPath", err)
  93. return
  94. }
  95. }
  96. c.Data["LatestCommit"] = latestCommit
  97. c.Data["LatestCommitUser"] = models.ValidateCommitWithEmail(latestCommit)
  98. if c.Repo.CanEnableEditor() {
  99. c.Data["CanAddFile"] = true
  100. c.Data["CanUploadFile"] = setting.Repository.Upload.Enabled
  101. }
  102. }
  103. func renderFile(ctx *context.Context, entry *git.TreeEntry, treeLink, rawLink string) {
  104. ctx.Data["IsViewFile"] = true
  105. blob := entry.Blob()
  106. dataRc, err := blob.Data()
  107. if err != nil {
  108. ctx.Handle(500, "Data", err)
  109. return
  110. }
  111. ctx.Data["FileSize"] = blob.Size()
  112. ctx.Data["FileName"] = blob.Name()
  113. ctx.Data["HighlightClass"] = highlight.FileNameToHighlightClass(blob.Name())
  114. ctx.Data["RawFileLink"] = rawLink + "/" + ctx.Repo.TreePath
  115. buf := make([]byte, 1024)
  116. n, _ := dataRc.Read(buf)
  117. buf = buf[:n]
  118. isTextFile := tool.IsTextFile(buf)
  119. ctx.Data["IsTextFile"] = isTextFile
  120. // Assume file is not editable first.
  121. if !isTextFile {
  122. ctx.Data["EditFileTooltip"] = ctx.Tr("repo.editor.cannot_edit_non_text_files")
  123. }
  124. canEnableEditor := ctx.Repo.CanEnableEditor()
  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 := markup.IsMarkdownFile(blob.Name())
  134. ctx.Data["IsMarkdown"] = isMarkdown
  135. ctx.Data["ReadmeExist"] = isMarkdown && markup.IsReadmeFile(blob.Name())
  136. ctx.Data["IsIPythonNotebook"] = markup.IsIPythonNotebook(blob.Name())
  137. if isMarkdown {
  138. ctx.Data["FileContent"] = string(markup.Markdown(buf, path.Dir(treeLink), ctx.Repo.Repository.ComposeMetas()))
  139. } else {
  140. // Building code view blocks with line number on server side.
  141. var fileContent string
  142. if err, content := template.ToUTF8WithErr(buf); err != nil {
  143. if err != nil {
  144. log.Error(4, "ToUTF8WithErr: %s", err)
  145. }
  146. fileContent = string(buf)
  147. } else {
  148. fileContent = content
  149. }
  150. var output bytes.Buffer
  151. lines := strings.Split(fileContent, "\n")
  152. for index, line := range lines {
  153. output.WriteString(fmt.Sprintf(`<li class="L%d" rel="L%d">%s</li>`, index+1, index+1, gotemplate.HTMLEscapeString(line)) + "\n")
  154. }
  155. ctx.Data["FileContent"] = gotemplate.HTML(output.String())
  156. output.Reset()
  157. for i := 0; i < len(lines); i++ {
  158. output.WriteString(fmt.Sprintf(`<span id="L%d">%d</span>`, i+1, i+1))
  159. }
  160. ctx.Data["LineNums"] = gotemplate.HTML(output.String())
  161. }
  162. if canEnableEditor {
  163. ctx.Data["CanEditFile"] = true
  164. ctx.Data["EditFileTooltip"] = ctx.Tr("repo.editor.edit_this_file")
  165. } else if !ctx.Repo.IsViewBranch {
  166. ctx.Data["EditFileTooltip"] = ctx.Tr("repo.editor.must_be_on_a_branch")
  167. } else if !ctx.Repo.IsWriter() {
  168. ctx.Data["EditFileTooltip"] = ctx.Tr("repo.editor.fork_before_edit")
  169. }
  170. case tool.IsPDFFile(buf):
  171. ctx.Data["IsPDFFile"] = true
  172. case tool.IsVideoFile(buf):
  173. ctx.Data["IsVideoFile"] = true
  174. case tool.IsImageFile(buf):
  175. ctx.Data["IsImageFile"] = true
  176. }
  177. if canEnableEditor {
  178. ctx.Data["CanDeleteFile"] = true
  179. ctx.Data["DeleteFileTooltip"] = ctx.Tr("repo.editor.delete_this_file")
  180. } else if !ctx.Repo.IsViewBranch {
  181. ctx.Data["DeleteFileTooltip"] = ctx.Tr("repo.editor.must_be_on_a_branch")
  182. } else if !ctx.Repo.IsWriter() {
  183. ctx.Data["DeleteFileTooltip"] = ctx.Tr("repo.editor.must_have_write_access")
  184. }
  185. }
  186. func setEditorconfigIfExists(ctx *context.Context) {
  187. ec, err := ctx.Repo.GetEditorconfig()
  188. if err != nil && !git.IsErrNotExist(err) {
  189. log.Trace("setEditorconfigIfExists.GetEditorconfig [%d]: %v", ctx.Repo.Repository.ID, err)
  190. return
  191. }
  192. ctx.Data["Editorconfig"] = ec
  193. }
  194. func Home(ctx *context.Context) {
  195. ctx.Data["PageIsViewFiles"] = true
  196. if ctx.Repo.Repository.IsBare {
  197. ctx.HTML(200, BARE)
  198. return
  199. }
  200. title := ctx.Repo.Repository.Owner.Name + "/" + ctx.Repo.Repository.Name
  201. if len(ctx.Repo.Repository.Description) > 0 {
  202. title += ": " + ctx.Repo.Repository.Description
  203. }
  204. ctx.Data["Title"] = title
  205. if ctx.Repo.BranchName != ctx.Repo.Repository.DefaultBranch {
  206. ctx.Data["Title"] = title + " @ " + ctx.Repo.BranchName
  207. }
  208. ctx.Data["RequireHighlightJS"] = true
  209. branchLink := ctx.Repo.RepoLink + "/src/" + ctx.Repo.BranchName
  210. treeLink := branchLink
  211. rawLink := ctx.Repo.RepoLink + "/raw/" + ctx.Repo.BranchName
  212. isRootDir := false
  213. if len(ctx.Repo.TreePath) > 0 {
  214. treeLink += "/" + ctx.Repo.TreePath
  215. } else {
  216. isRootDir = true
  217. // Only show Git stats panel when view root directory
  218. var err error
  219. ctx.Repo.CommitsCount, err = ctx.Repo.Commit.CommitsCount()
  220. if err != nil {
  221. ctx.Handle(500, "CommitsCount", err)
  222. return
  223. }
  224. ctx.Data["CommitsCount"] = ctx.Repo.CommitsCount
  225. }
  226. ctx.Data["PageIsRepoHome"] = isRootDir
  227. // Get current entry user currently looking at.
  228. entry, err := ctx.Repo.Commit.GetTreeEntryByPath(ctx.Repo.TreePath)
  229. if err != nil {
  230. ctx.NotFoundOrServerError("Repo.Commit.GetTreeEntryByPath", git.IsErrNotExist, err)
  231. return
  232. }
  233. if entry.IsDir() {
  234. renderDirectory(ctx, treeLink)
  235. } else {
  236. renderFile(ctx, entry, treeLink, rawLink)
  237. }
  238. if ctx.Written() {
  239. return
  240. }
  241. setEditorconfigIfExists(ctx)
  242. if ctx.Written() {
  243. return
  244. }
  245. var treeNames []string
  246. paths := make([]string, 0, 5)
  247. if len(ctx.Repo.TreePath) > 0 {
  248. treeNames = strings.Split(ctx.Repo.TreePath, "/")
  249. for i := range treeNames {
  250. paths = append(paths, strings.Join(treeNames[:i+1], "/"))
  251. }
  252. ctx.Data["HasParentPath"] = true
  253. if len(paths)-2 >= 0 {
  254. ctx.Data["ParentPath"] = "/" + paths[len(paths)-2]
  255. }
  256. }
  257. ctx.Data["Paths"] = paths
  258. ctx.Data["TreeLink"] = treeLink
  259. ctx.Data["TreeNames"] = treeNames
  260. ctx.Data["BranchLink"] = branchLink
  261. ctx.HTML(200, HOME)
  262. }
  263. func RenderUserCards(ctx *context.Context, total int, getter func(page int) ([]*models.User, error), tpl string) {
  264. page := ctx.QueryInt("page")
  265. if page <= 0 {
  266. page = 1
  267. }
  268. pager := paginater.New(total, models.ItemsPerPage, page, 5)
  269. ctx.Data["Page"] = pager
  270. items, err := getter(pager.Current())
  271. if err != nil {
  272. ctx.Handle(500, "getter", err)
  273. return
  274. }
  275. ctx.Data["Cards"] = items
  276. ctx.HTML(200, tpl)
  277. }
  278. func Watchers(ctx *context.Context) {
  279. ctx.Data["Title"] = ctx.Tr("repo.watchers")
  280. ctx.Data["CardsTitle"] = ctx.Tr("repo.watchers")
  281. ctx.Data["PageIsWatchers"] = true
  282. RenderUserCards(ctx, ctx.Repo.Repository.NumWatches, ctx.Repo.Repository.GetWatchers, WATCHERS)
  283. }
  284. func Stars(ctx *context.Context) {
  285. ctx.Data["Title"] = ctx.Tr("repo.stargazers")
  286. ctx.Data["CardsTitle"] = ctx.Tr("repo.stargazers")
  287. ctx.Data["PageIsStargazers"] = true
  288. RenderUserCards(ctx, ctx.Repo.Repository.NumStars, ctx.Repo.Repository.GetStargazers, WATCHERS)
  289. }
  290. func Forks(ctx *context.Context) {
  291. ctx.Data["Title"] = ctx.Tr("repos.forks")
  292. forks, err := ctx.Repo.Repository.GetForks()
  293. if err != nil {
  294. ctx.Handle(500, "GetForks", err)
  295. return
  296. }
  297. for _, fork := range forks {
  298. if err = fork.GetOwner(); err != nil {
  299. ctx.Handle(500, "GetOwner", err)
  300. return
  301. }
  302. }
  303. ctx.Data["Forks"] = forks
  304. ctx.HTML(200, FORKS)
  305. }