view.go 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  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. for index, line := range lines {
  160. output.WriteString(fmt.Sprintf(`<li class="L%d" rel="L%d">%s</li>`, index+1, index+1, gotemplate.HTMLEscapeString(strings.TrimRight(line, "\r"))) + "\n")
  161. }
  162. c.Data["FileContent"] = gotemplate.HTML(output.String())
  163. output.Reset()
  164. for i := 0; i < len(lines); i++ {
  165. output.WriteString(fmt.Sprintf(`<span id="L%d">%d</span>`, i+1, i+1))
  166. }
  167. c.Data["LineNums"] = gotemplate.HTML(output.String())
  168. }
  169. if canEnableEditor {
  170. c.Data["CanEditFile"] = true
  171. c.Data["EditFileTooltip"] = c.Tr("repo.editor.edit_this_file")
  172. } else if !c.Repo.IsViewBranch {
  173. c.Data["EditFileTooltip"] = c.Tr("repo.editor.must_be_on_a_branch")
  174. } else if !c.Repo.IsWriter() {
  175. c.Data["EditFileTooltip"] = c.Tr("repo.editor.fork_before_edit")
  176. }
  177. case tool.IsPDFFile(buf):
  178. c.Data["IsPDFFile"] = true
  179. case tool.IsVideoFile(buf):
  180. c.Data["IsVideoFile"] = true
  181. case tool.IsImageFile(buf):
  182. c.Data["IsImageFile"] = true
  183. }
  184. if canEnableEditor {
  185. c.Data["CanDeleteFile"] = true
  186. c.Data["DeleteFileTooltip"] = c.Tr("repo.editor.delete_this_file")
  187. } else if !c.Repo.IsViewBranch {
  188. c.Data["DeleteFileTooltip"] = c.Tr("repo.editor.must_be_on_a_branch")
  189. } else if !c.Repo.IsWriter() {
  190. c.Data["DeleteFileTooltip"] = c.Tr("repo.editor.must_have_write_access")
  191. }
  192. }
  193. func setEditorconfigIfExists(c *context.Context) {
  194. ec, err := c.Repo.GetEditorconfig()
  195. if err != nil && !git.IsErrNotExist(err) {
  196. log.Trace("setEditorconfigIfExists.GetEditorconfig [%d]: %v", c.Repo.Repository.ID, err)
  197. return
  198. }
  199. c.Data["Editorconfig"] = ec
  200. }
  201. func Home(c *context.Context) {
  202. c.Data["PageIsViewFiles"] = true
  203. if c.Repo.Repository.IsBare {
  204. c.HTML(200, BARE)
  205. return
  206. }
  207. title := c.Repo.Repository.Owner.Name + "/" + c.Repo.Repository.Name
  208. if len(c.Repo.Repository.Description) > 0 {
  209. title += ": " + c.Repo.Repository.Description
  210. }
  211. c.Data["Title"] = title
  212. if c.Repo.BranchName != c.Repo.Repository.DefaultBranch {
  213. c.Data["Title"] = title + " @ " + c.Repo.BranchName
  214. }
  215. c.Data["RequireHighlightJS"] = true
  216. branchLink := c.Repo.RepoLink + "/src/" + c.Repo.BranchName
  217. treeLink := branchLink
  218. rawLink := c.Repo.RepoLink + "/raw/" + c.Repo.BranchName
  219. isRootDir := false
  220. if len(c.Repo.TreePath) > 0 {
  221. treeLink += "/" + c.Repo.TreePath
  222. } else {
  223. isRootDir = true
  224. // Only show Git stats panel when view root directory
  225. var err error
  226. c.Repo.CommitsCount, err = c.Repo.Commit.CommitsCount()
  227. if err != nil {
  228. c.Handle(500, "CommitsCount", err)
  229. return
  230. }
  231. c.Data["CommitsCount"] = c.Repo.CommitsCount
  232. }
  233. c.Data["PageIsRepoHome"] = isRootDir
  234. // Get current entry user currently looking at.
  235. entry, err := c.Repo.Commit.GetTreeEntryByPath(c.Repo.TreePath)
  236. if err != nil {
  237. c.NotFoundOrServerError("Repo.Commit.GetTreeEntryByPath", git.IsErrNotExist, err)
  238. return
  239. }
  240. if entry.IsDir() {
  241. renderDirectory(c, treeLink)
  242. } else {
  243. renderFile(c, entry, treeLink, rawLink)
  244. }
  245. if c.Written() {
  246. return
  247. }
  248. setEditorconfigIfExists(c)
  249. if c.Written() {
  250. return
  251. }
  252. var treeNames []string
  253. paths := make([]string, 0, 5)
  254. if len(c.Repo.TreePath) > 0 {
  255. treeNames = strings.Split(c.Repo.TreePath, "/")
  256. for i := range treeNames {
  257. paths = append(paths, strings.Join(treeNames[:i+1], "/"))
  258. }
  259. c.Data["HasParentPath"] = true
  260. if len(paths)-2 >= 0 {
  261. c.Data["ParentPath"] = "/" + paths[len(paths)-2]
  262. }
  263. }
  264. c.Data["Paths"] = paths
  265. c.Data["TreeLink"] = treeLink
  266. c.Data["TreeNames"] = treeNames
  267. c.Data["BranchLink"] = branchLink
  268. c.HTML(200, HOME)
  269. }
  270. func RenderUserCards(c *context.Context, total int, getter func(page int) ([]*models.User, error), tpl string) {
  271. page := c.QueryInt("page")
  272. if page <= 0 {
  273. page = 1
  274. }
  275. pager := paginater.New(total, models.ItemsPerPage, page, 5)
  276. c.Data["Page"] = pager
  277. items, err := getter(pager.Current())
  278. if err != nil {
  279. c.Handle(500, "getter", err)
  280. return
  281. }
  282. c.Data["Cards"] = items
  283. c.HTML(200, tpl)
  284. }
  285. func Watchers(c *context.Context) {
  286. c.Data["Title"] = c.Tr("repo.watchers")
  287. c.Data["CardsTitle"] = c.Tr("repo.watchers")
  288. c.Data["PageIsWatchers"] = true
  289. RenderUserCards(c, c.Repo.Repository.NumWatches, c.Repo.Repository.GetWatchers, WATCHERS)
  290. }
  291. func Stars(c *context.Context) {
  292. c.Data["Title"] = c.Tr("repo.stargazers")
  293. c.Data["CardsTitle"] = c.Tr("repo.stargazers")
  294. c.Data["PageIsStargazers"] = true
  295. RenderUserCards(c, c.Repo.Repository.NumStars, c.Repo.Repository.GetStargazers, WATCHERS)
  296. }
  297. func Forks(c *context.Context) {
  298. c.Data["Title"] = c.Tr("repos.forks")
  299. forks, err := c.Repo.Repository.GetForks()
  300. if err != nil {
  301. c.Handle(500, "GetForks", err)
  302. return
  303. }
  304. for _, fork := range forks {
  305. if err = fork.GetOwner(); err != nil {
  306. c.Handle(500, "GetOwner", err)
  307. return
  308. }
  309. }
  310. c.Data["Forks"] = forks
  311. c.HTML(200, FORKS)
  312. }