view.go 9.8 KB

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