view.go 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  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/unknwon/paginater"
  14. log "unknwon.dev/clog/v2"
  15. "gogs.io/gogs/internal/conf"
  16. "gogs.io/gogs/internal/context"
  17. "gogs.io/gogs/internal/database"
  18. "gogs.io/gogs/internal/gitutil"
  19. "gogs.io/gogs/internal/markup"
  20. "gogs.io/gogs/internal/template"
  21. "gogs.io/gogs/internal/template/highlight"
  22. "gogs.io/gogs/internal/tool"
  23. )
  24. const (
  25. BARE = "repo/bare"
  26. HOME = "repo/home"
  27. WATCHERS = "repo/watchers"
  28. FORKS = "repo/forks"
  29. )
  30. func renderDirectory(c *context.Context, treeLink string) {
  31. tree, err := c.Repo.Commit.Subtree(c.Repo.TreePath)
  32. if err != nil {
  33. c.NotFoundOrError(gitutil.NewError(err), "get subtree")
  34. return
  35. }
  36. entries, err := tree.Entries()
  37. if err != nil {
  38. c.Error(err, "list entries")
  39. return
  40. }
  41. entries.Sort()
  42. c.Data["Files"], err = entries.CommitsInfo(c.Repo.Commit, git.CommitsInfoOptions{
  43. Path: c.Repo.TreePath,
  44. MaxConcurrency: conf.Repository.CommitsFetchConcurrency,
  45. Timeout: 5 * time.Minute,
  46. })
  47. if err != nil {
  48. c.Error(err, "get commits info")
  49. return
  50. }
  51. var readmeFile *git.Blob
  52. for _, entry := range entries {
  53. if entry.IsTree() || !markup.IsReadmeFile(entry.Name()) {
  54. continue
  55. }
  56. // TODO(unknwon): collect all possible README files and show with priority.
  57. readmeFile = entry.Blob()
  58. break
  59. }
  60. if readmeFile != nil {
  61. c.Data["RawFileLink"] = ""
  62. c.Data["ReadmeInList"] = true
  63. c.Data["ReadmeExist"] = true
  64. p, err := readmeFile.Bytes()
  65. if err != nil {
  66. c.Error(err, "read file")
  67. return
  68. }
  69. isTextFile := tool.IsTextFile(p)
  70. c.Data["IsTextFile"] = isTextFile
  71. c.Data["FileName"] = readmeFile.Name()
  72. if isTextFile {
  73. switch markup.Detect(readmeFile.Name()) {
  74. case markup.TypeMarkdown:
  75. c.Data["IsMarkdown"] = true
  76. p = markup.Markdown(p, treeLink, c.Repo.Repository.ComposeMetas())
  77. case markup.TypeOrgMode:
  78. c.Data["IsMarkdown"] = true
  79. p = markup.OrgMode(p, treeLink, c.Repo.Repository.ComposeMetas())
  80. case markup.TypeIPythonNotebook:
  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. p = bytes.ReplaceAll(p, []byte("\n"), []byte(`<br>`))
  85. }
  86. c.Data["FileContent"] = string(p)
  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.CommitByPath(git.CommitByRevisionOptions{Path: c.Repo.TreePath})
  94. if err != nil {
  95. c.Error(err, "get commit by path")
  96. return
  97. }
  98. }
  99. c.Data["LatestCommit"] = latestCommit
  100. c.Data["LatestCommitUser"] = tryGetUserByEmail(c.Req.Context(), latestCommit.Author.Email)
  101. if c.Repo.CanEnableEditor() {
  102. c.Data["CanAddFile"] = true
  103. c.Data["CanUploadFile"] = conf.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. p, err := blob.Bytes()
  110. if err != nil {
  111. c.Error(err, "read blob")
  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. isTextFile := tool.IsTextFile(p)
  119. c.Data["IsTextFile"] = isTextFile
  120. // Assume file is not editable first.
  121. if !isTextFile {
  122. c.Data["EditFileTooltip"] = c.Tr("repo.editor.cannot_edit_non_text_files")
  123. }
  124. canEnableEditor := c.Repo.CanEnableEditor()
  125. switch {
  126. case isTextFile:
  127. if blob.Size() >= conf.UI.MaxDisplayFileSize {
  128. c.Data["IsFileTooLarge"] = true
  129. break
  130. }
  131. c.Data["ReadmeExist"] = markup.IsReadmeFile(blob.Name())
  132. switch markup.Detect(blob.Name()) {
  133. case markup.TypeMarkdown:
  134. c.Data["IsMarkdown"] = true
  135. c.Data["FileContent"] = string(markup.Markdown(p, path.Dir(treeLink), c.Repo.Repository.ComposeMetas()))
  136. case markup.TypeOrgMode:
  137. c.Data["IsMarkdown"] = true
  138. c.Data["FileContent"] = string(markup.OrgMode(p, path.Dir(treeLink), c.Repo.Repository.ComposeMetas()))
  139. case markup.TypeIPythonNotebook:
  140. c.Data["IsIPythonNotebook"] = true
  141. default:
  142. // Building code view blocks with line number on server side.
  143. var fileContent string
  144. if err, content := template.ToUTF8WithErr(p); err != nil {
  145. if err != nil {
  146. log.Error("ToUTF8WithErr: %s", err)
  147. }
  148. fileContent = string(p)
  149. } else {
  150. fileContent = content
  151. }
  152. var output bytes.Buffer
  153. lines := strings.Split(fileContent, "\n")
  154. // Remove blank line at the end of file
  155. if len(lines) > 0 && lines[len(lines)-1] == "" {
  156. lines = lines[:len(lines)-1]
  157. }
  158. for index, line := range lines {
  159. output.WriteString(fmt.Sprintf(`<li class="L%d" rel="L%d">%s</li>`, index+1, index+1, gotemplate.HTMLEscapeString(strings.TrimRight(line, "\r"))) + "\n")
  160. }
  161. c.Data["FileContent"] = gotemplate.HTML(output.String())
  162. output.Reset()
  163. for i := 0; i < len(lines); i++ {
  164. output.WriteString(fmt.Sprintf(`<span id="L%d">%d</span>`, i+1, i+1))
  165. }
  166. c.Data["LineNums"] = gotemplate.HTML(output.String())
  167. }
  168. if canEnableEditor {
  169. c.Data["CanEditFile"] = true
  170. c.Data["EditFileTooltip"] = c.Tr("repo.editor.edit_this_file")
  171. } else if !c.Repo.IsViewBranch {
  172. c.Data["EditFileTooltip"] = c.Tr("repo.editor.must_be_on_a_branch")
  173. } else if !c.Repo.IsWriter() {
  174. c.Data["EditFileTooltip"] = c.Tr("repo.editor.fork_before_edit")
  175. }
  176. case tool.IsPDFFile(p):
  177. c.Data["IsPDFFile"] = true
  178. case tool.IsVideoFile(p):
  179. c.Data["IsVideoFile"] = true
  180. case tool.IsImageFile(p):
  181. c.Data["IsImageFile"] = true
  182. }
  183. if canEnableEditor {
  184. c.Data["CanDeleteFile"] = true
  185. c.Data["DeleteFileTooltip"] = c.Tr("repo.editor.delete_this_file")
  186. } else if !c.Repo.IsViewBranch {
  187. c.Data["DeleteFileTooltip"] = c.Tr("repo.editor.must_be_on_a_branch")
  188. } else if !c.Repo.IsWriter() {
  189. c.Data["DeleteFileTooltip"] = c.Tr("repo.editor.must_have_write_access")
  190. }
  191. }
  192. func setEditorconfigIfExists(c *context.Context) {
  193. ec, err := c.Repo.Editorconfig()
  194. if err != nil && !gitutil.IsErrRevisionNotExist(err) {
  195. log.Warn("setEditorconfigIfExists.Editorconfig [repo_id: %d]: %v", c.Repo.Repository.ID, err)
  196. return
  197. }
  198. c.Data["Editorconfig"] = ec
  199. }
  200. func Home(c *context.Context) {
  201. c.Data["PageIsViewFiles"] = true
  202. if c.Repo.Repository.IsBare {
  203. c.Success(BARE)
  204. return
  205. }
  206. title := c.Repo.Repository.Owner.Name + "/" + c.Repo.Repository.Name
  207. if len(c.Repo.Repository.Description) > 0 {
  208. title += ": " + c.Repo.Repository.Description
  209. }
  210. c.Data["Title"] = title
  211. if c.Repo.BranchName != c.Repo.Repository.DefaultBranch {
  212. c.Data["Title"] = title + " @ " + c.Repo.BranchName
  213. }
  214. c.Data["RequireHighlightJS"] = true
  215. branchLink := c.Repo.RepoLink + "/src/" + c.Repo.BranchName
  216. treeLink := branchLink
  217. rawLink := c.Repo.RepoLink + "/raw/" + c.Repo.BranchName
  218. isRootDir := false
  219. if len(c.Repo.TreePath) > 0 {
  220. treeLink += "/" + c.Repo.TreePath
  221. } else {
  222. isRootDir = true
  223. // Only show Git stats panel when view root directory
  224. var err error
  225. c.Repo.CommitsCount, err = c.Repo.Commit.CommitsCount()
  226. if err != nil {
  227. c.Error(err, "count commits")
  228. return
  229. }
  230. c.Data["CommitsCount"] = c.Repo.CommitsCount
  231. }
  232. c.Data["PageIsRepoHome"] = isRootDir
  233. // Get current entry user currently looking at.
  234. entry, err := c.Repo.Commit.TreeEntry(c.Repo.TreePath)
  235. if err != nil {
  236. c.NotFoundOrError(gitutil.NewError(err), "get tree entry")
  237. return
  238. }
  239. if entry.IsTree() {
  240. renderDirectory(c, treeLink)
  241. } else {
  242. renderFile(c, entry, treeLink, rawLink)
  243. }
  244. if c.Written() {
  245. return
  246. }
  247. setEditorconfigIfExists(c)
  248. if c.Written() {
  249. return
  250. }
  251. var treeNames []string
  252. paths := make([]string, 0, 5)
  253. if len(c.Repo.TreePath) > 0 {
  254. treeNames = strings.Split(c.Repo.TreePath, "/")
  255. for i := range treeNames {
  256. paths = append(paths, strings.Join(treeNames[:i+1], "/"))
  257. }
  258. c.Data["HasParentPath"] = true
  259. if len(paths)-2 >= 0 {
  260. c.Data["ParentPath"] = "/" + paths[len(paths)-2]
  261. }
  262. }
  263. c.Data["Paths"] = paths
  264. c.Data["TreeLink"] = treeLink
  265. c.Data["TreeNames"] = treeNames
  266. c.Data["BranchLink"] = branchLink
  267. c.Success(HOME)
  268. }
  269. func RenderUserCards(c *context.Context, total int, getter func(page int) ([]*database.User, error), tpl string) {
  270. page := c.QueryInt("page")
  271. if page <= 0 {
  272. page = 1
  273. }
  274. pager := paginater.New(total, database.ItemsPerPage, page, 5)
  275. c.Data["Page"] = pager
  276. items, err := getter(pager.Current())
  277. if err != nil {
  278. c.Error(err, "getter")
  279. return
  280. }
  281. c.Data["Cards"] = items
  282. c.Success(tpl)
  283. }
  284. func Watchers(c *context.Context) {
  285. c.Data["Title"] = c.Tr("repo.watchers")
  286. c.Data["CardsTitle"] = c.Tr("repo.watchers")
  287. c.Data["PageIsWatchers"] = true
  288. RenderUserCards(c, c.Repo.Repository.NumWatches, c.Repo.Repository.GetWatchers, WATCHERS)
  289. }
  290. func Stars(c *context.Context) {
  291. c.Data["Title"] = c.Tr("repo.stargazers")
  292. c.Data["CardsTitle"] = c.Tr("repo.stargazers")
  293. c.Data["PageIsStargazers"] = true
  294. RenderUserCards(c, c.Repo.Repository.NumStars, c.Repo.Repository.GetStargazers, WATCHERS)
  295. }
  296. func Forks(c *context.Context) {
  297. c.Data["Title"] = c.Tr("repos.forks")
  298. forks, err := c.Repo.Repository.GetForks()
  299. if err != nil {
  300. c.Error(err, "get forks")
  301. return
  302. }
  303. for _, fork := range forks {
  304. if err = fork.GetOwner(); err != nil {
  305. c.Error(err, "get owner")
  306. return
  307. }
  308. }
  309. c.Data["Forks"] = forks
  310. c.Success(FORKS)
  311. }