view.go 9.7 KB

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