view.go 10 KB

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