view.go 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  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. "path"
  10. "strings"
  11. "time"
  12. "github.com/gogs/git-module"
  13. "github.com/pkg/errors"
  14. "github.com/unknwon/paginater"
  15. log "unknwon.dev/clog/v2"
  16. "gogs.io/gogs/internal/conf"
  17. "gogs.io/gogs/internal/context"
  18. "gogs.io/gogs/internal/db"
  19. "gogs.io/gogs/internal/gitutil"
  20. "gogs.io/gogs/internal/markup"
  21. "gogs.io/gogs/internal/template"
  22. "gogs.io/gogs/internal/template/highlight"
  23. "gogs.io/gogs/internal/tool"
  24. )
  25. const (
  26. BARE = "repo/bare"
  27. HOME = "repo/home"
  28. WATCHERS = "repo/watchers"
  29. FORKS = "repo/forks"
  30. )
  31. func renderDirectory(c *context.Context, treeLink string) {
  32. tree, err := c.Repo.Commit.Subtree(c.Repo.TreePath)
  33. if err != nil {
  34. c.NotFoundOrError(gitutil.NewError(err), "get subtree")
  35. return
  36. }
  37. entries, err := tree.Entries()
  38. if err != nil {
  39. c.Error(err, "list entries")
  40. return
  41. }
  42. entries.Sort()
  43. c.Data["Files"], err = entries.CommitsInfo(c.Repo.Commit, git.CommitsInfoOptions{
  44. Path: c.Repo.TreePath,
  45. MaxConcurrency: conf.Repository.CommitsFetchConcurrency,
  46. Timeout: 5 * time.Minute,
  47. })
  48. if err != nil {
  49. c.Error(err, "get commits info")
  50. return
  51. }
  52. var readmeFile *git.Blob
  53. for _, entry := range entries {
  54. if entry.IsTree() || !markup.IsReadmeFile(entry.Name()) {
  55. continue
  56. }
  57. // TODO(unknwon): collect all possible README files and show with priority.
  58. readmeFile = entry.Blob()
  59. break
  60. }
  61. if readmeFile != nil {
  62. c.Data["RawFileLink"] = ""
  63. c.Data["ReadmeInList"] = true
  64. c.Data["ReadmeExist"] = true
  65. p, err := readmeFile.Bytes()
  66. if err != nil {
  67. c.Error(err, "read file")
  68. return
  69. }
  70. isTextFile := tool.IsTextFile(p)
  71. c.Data["IsTextFile"] = isTextFile
  72. c.Data["FileName"] = readmeFile.Name()
  73. if isTextFile {
  74. switch markup.Detect(readmeFile.Name()) {
  75. case markup.MARKDOWN:
  76. c.Data["IsMarkdown"] = true
  77. p = markup.Markdown(p, treeLink, c.Repo.Repository.ComposeMetas())
  78. case markup.ORG_MODE:
  79. c.Data["IsMarkdown"] = true
  80. p = markup.OrgMode(p, treeLink, c.Repo.Repository.ComposeMetas())
  81. case markup.IPYTHON_NOTEBOOK:
  82. c.Data["IsIPythonNotebook"] = true
  83. c.Data["RawFileLink"] = c.Repo.RepoLink + "/raw/" + path.Join(c.Repo.BranchName, c.Repo.TreePath, readmeFile.Name())
  84. default:
  85. p = bytes.Replace(p, []byte("\n"), []byte(`<br>`), -1)
  86. }
  87. c.Data["FileContent"] = string(p)
  88. }
  89. }
  90. // Show latest commit info of repository in table header,
  91. // or of directory if not in root directory.
  92. latestCommit := c.Repo.Commit
  93. if len(c.Repo.TreePath) > 0 {
  94. latestCommit, err = c.Repo.Commit.CommitByPath(git.CommitByRevisionOptions{Path: c.Repo.TreePath})
  95. if err != nil {
  96. c.Error(err, "get commit by path")
  97. return
  98. }
  99. }
  100. c.Data["LatestCommit"] = latestCommit
  101. c.Data["LatestCommitUser"] = db.ValidateCommitWithEmail(latestCommit)
  102. if c.Repo.CanEnableEditor() {
  103. c.Data["CanAddFile"] = true
  104. c.Data["CanUploadFile"] = conf.Repository.Upload.Enabled
  105. }
  106. }
  107. func renderFile(c *context.Context, entry *git.TreeEntry, treeLink, rawLink string) {
  108. c.Data["IsViewFile"] = true
  109. blob := entry.Blob()
  110. p, err := blob.Bytes()
  111. if err != nil {
  112. c.Error(err, "read blob")
  113. return
  114. }
  115. c.Data["FileSize"] = blob.Size()
  116. c.Data["FileName"] = blob.Name()
  117. c.Data["HighlightClass"] = highlight.FileNameToHighlightClass(blob.Name())
  118. c.Data["RawFileLink"] = rawLink + "/" + c.Repo.TreePath
  119. isTextFile := tool.IsTextFile(p)
  120. c.Data["IsTextFile"] = isTextFile
  121. // Assume file is not editable first.
  122. if !isTextFile {
  123. c.Data["EditFileTooltip"] = c.Tr("repo.editor.cannot_edit_non_text_files")
  124. }
  125. canEnableEditor := c.Repo.CanEnableEditor()
  126. switch {
  127. case isTextFile:
  128. if blob.Size() >= conf.UI.MaxDisplayFileSize {
  129. c.Data["IsFileTooLarge"] = true
  130. break
  131. }
  132. c.Data["ReadmeExist"] = markup.IsReadmeFile(blob.Name())
  133. switch markup.Detect(blob.Name()) {
  134. case markup.MARKDOWN:
  135. c.Data["IsMarkdown"] = true
  136. c.Data["FileContent"] = string(markup.Markdown(p, path.Dir(treeLink), c.Repo.Repository.ComposeMetas()))
  137. case markup.ORG_MODE:
  138. c.Data["IsMarkdown"] = true
  139. c.Data["FileContent"] = string(markup.OrgMode(p, path.Dir(treeLink), c.Repo.Repository.ComposeMetas()))
  140. case markup.IPYTHON_NOTEBOOK:
  141. c.Data["IsIPythonNotebook"] = true
  142. default:
  143. // Building code view blocks with line number on server side.
  144. var fileContent string
  145. if err, content := template.ToUTF8WithErr(p); err != nil {
  146. if err != nil {
  147. log.Error("ToUTF8WithErr: %s", err)
  148. }
  149. fileContent = string(p)
  150. } else {
  151. fileContent = content
  152. }
  153. var output bytes.Buffer
  154. lines := strings.Split(fileContent, "\n")
  155. // Remove blank line at the end of file
  156. if len(lines) > 0 && len(lines[len(lines)-1]) == 0 {
  157. lines = lines[:len(lines)-1]
  158. }
  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(p):
  178. c.Data["IsPDFFile"] = true
  179. case tool.IsVideoFile(p):
  180. c.Data["IsVideoFile"] = true
  181. case tool.IsImageFile(p):
  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.Editorconfig()
  195. if err != nil && !gitutil.IsErrRevisionNotExist(errors.Cause(err)) {
  196. log.Warn("setEditorconfigIfExists.Editorconfig [repo_id: %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.Success(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.Error(err, "count commits")
  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.TreeEntry(c.Repo.TreePath)
  236. if err != nil {
  237. c.NotFoundOrError(gitutil.NewError(err), "get tree entry")
  238. return
  239. }
  240. if entry.IsTree() {
  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.Success(HOME)
  269. }
  270. func RenderUserCards(c *context.Context, total int, getter func(page int) ([]*db.User, error), tpl string) {
  271. page := c.QueryInt("page")
  272. if page <= 0 {
  273. page = 1
  274. }
  275. pager := paginater.New(total, db.ItemsPerPage, page, 5)
  276. c.Data["Page"] = pager
  277. items, err := getter(pager.Current())
  278. if err != nil {
  279. c.Error(err, "getter")
  280. return
  281. }
  282. c.Data["Cards"] = items
  283. c.Success(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.Error(err, "get forks")
  302. return
  303. }
  304. for _, fork := range forks {
  305. if err = fork.GetOwner(); err != nil {
  306. c.Error(err, "get owner")
  307. return
  308. }
  309. }
  310. c.Data["Forks"] = forks
  311. c.Success(FORKS)
  312. }