1
0

view.go 9.3 KB

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