view.go 9.4 KB

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