view.go 9.4 KB

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