You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

view.go 9.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  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. "io/ioutil"
  10. "path"
  11. "strings"
  12. "code.gitea.io/git"
  13. "code.gitea.io/gitea/models"
  14. "code.gitea.io/gitea/modules/base"
  15. "code.gitea.io/gitea/modules/context"
  16. "code.gitea.io/gitea/modules/highlight"
  17. "code.gitea.io/gitea/modules/lfs"
  18. "code.gitea.io/gitea/modules/log"
  19. "code.gitea.io/gitea/modules/markdown"
  20. "code.gitea.io/gitea/modules/setting"
  21. "code.gitea.io/gitea/modules/templates"
  22. "encoding/base64"
  23. "github.com/Unknwon/paginater"
  24. "strconv"
  25. )
  26. const (
  27. tplRepoHome base.TplName = "repo/home"
  28. tplWatchers base.TplName = "repo/watchers"
  29. tplForks base.TplName = "repo/forks"
  30. )
  31. func renderDirectory(ctx *context.Context, treeLink string) {
  32. tree, err := ctx.Repo.Commit.SubTree(ctx.Repo.TreePath)
  33. if err != nil {
  34. ctx.NotFoundOrServerError("Repo.Commit.SubTree", git.IsErrNotExist, err)
  35. return
  36. }
  37. entries, err := tree.ListEntries()
  38. if err != nil {
  39. ctx.Handle(500, "ListEntries", err)
  40. return
  41. }
  42. entries.Sort()
  43. ctx.Data["Files"], err = entries.GetCommitsInfo(ctx.Repo.Commit, ctx.Repo.TreePath)
  44. if err != nil {
  45. ctx.Handle(500, "GetCommitsInfo", err)
  46. return
  47. }
  48. var readmeFile *git.Blob
  49. for _, entry := range entries {
  50. if entry.IsDir() || !markdown.IsReadmeFile(entry.Name()) {
  51. continue
  52. }
  53. // TODO: collect all possible README files and show with priority.
  54. readmeFile = entry.Blob()
  55. break
  56. }
  57. if readmeFile != nil {
  58. ctx.Data["RawFileLink"] = ""
  59. ctx.Data["ReadmeInList"] = true
  60. ctx.Data["ReadmeExist"] = true
  61. dataRc, err := readmeFile.Data()
  62. if err != nil {
  63. ctx.Handle(500, "Data", err)
  64. return
  65. }
  66. buf := make([]byte, 1024)
  67. n, _ := dataRc.Read(buf)
  68. buf = buf[:n]
  69. isTextFile := base.IsTextFile(buf)
  70. ctx.Data["FileIsText"] = isTextFile
  71. ctx.Data["FileName"] = readmeFile.Name()
  72. // FIXME: what happens when README file is an image?
  73. if isTextFile {
  74. d, _ := ioutil.ReadAll(dataRc)
  75. buf = append(buf, d...)
  76. switch {
  77. case markdown.IsMarkdownFile(readmeFile.Name()):
  78. ctx.Data["IsMarkdown"] = true
  79. buf = markdown.Render(buf, treeLink, ctx.Repo.Repository.ComposeMetas())
  80. default:
  81. // FIXME This is the only way to show non-markdown files
  82. // instead of a broken "View Raw" link
  83. ctx.Data["IsMarkdown"] = true
  84. buf = bytes.Replace(buf, []byte("\n"), []byte(`<br>`), -1)
  85. }
  86. ctx.Data["FileContent"] = string(buf)
  87. }
  88. }
  89. // Show latest commit info of repository in table header,
  90. // or of directory if not in root directory.
  91. latestCommit := ctx.Repo.Commit
  92. if len(ctx.Repo.TreePath) > 0 {
  93. latestCommit, err = ctx.Repo.Commit.GetCommitByPath(ctx.Repo.TreePath)
  94. if err != nil {
  95. ctx.Handle(500, "GetCommitByPath", err)
  96. return
  97. }
  98. }
  99. ctx.Data["LatestCommit"] = latestCommit
  100. ctx.Data["LatestCommitUser"] = models.ValidateCommitWithEmail(latestCommit)
  101. // Check permission to add or upload new file.
  102. if ctx.Repo.IsWriter() && ctx.Repo.IsViewBranch {
  103. ctx.Data["CanAddFile"] = true
  104. ctx.Data["CanUploadFile"] = setting.Repository.Upload.Enabled
  105. }
  106. }
  107. func renderFile(ctx *context.Context, entry *git.TreeEntry, treeLink, rawLink string) {
  108. ctx.Data["IsViewFile"] = true
  109. blob := entry.Blob()
  110. dataRc, err := blob.Data()
  111. if err != nil {
  112. ctx.Handle(500, "Data", err)
  113. return
  114. }
  115. ctx.Data["FileSize"] = blob.Size()
  116. ctx.Data["FileName"] = blob.Name()
  117. ctx.Data["HighlightClass"] = highlight.FileNameToHighlightClass(blob.Name())
  118. ctx.Data["RawFileLink"] = rawLink + "/" + ctx.Repo.TreePath
  119. buf := make([]byte, 1024)
  120. n, _ := dataRc.Read(buf)
  121. buf = buf[:n]
  122. isTextFile := base.IsTextFile(buf)
  123. ctx.Data["IsTextFile"] = isTextFile
  124. //Check for LFS meta file
  125. if isTextFile && setting.LFS.StartServer {
  126. headString := string(buf)
  127. if strings.HasPrefix(headString, models.LFSMetaFileIdentifier) {
  128. splitLines := strings.Split(headString, "\n")
  129. if len(splitLines) >= 3 {
  130. oid := strings.TrimPrefix(splitLines[1], models.LFSMetaFileOidPrefix)
  131. size, err := strconv.ParseInt(strings.TrimPrefix(splitLines[2], "size "), 10, 64)
  132. if len(oid) == 64 && err == nil {
  133. contentStore := &lfs.ContentStore{BasePath: setting.LFS.ContentPath}
  134. meta := &models.LFSMetaObject{Oid: oid}
  135. if contentStore.Exists(meta) {
  136. ctx.Data["IsTextFile"] = false
  137. isTextFile = false
  138. ctx.Data["IsLFSFile"] = true
  139. ctx.Data["FileSize"] = size
  140. filenameBase64 := base64.RawURLEncoding.EncodeToString([]byte(blob.Name()))
  141. ctx.Data["RawFileLink"] = fmt.Sprintf("%s%s/info/lfs/objects/%s/%s", setting.AppURL, ctx.Repo.Repository.FullName(), oid, filenameBase64)
  142. }
  143. }
  144. }
  145. }
  146. }
  147. // Assume file is not editable first.
  148. if !isTextFile {
  149. ctx.Data["EditFileTooltip"] = ctx.Tr("repo.editor.cannot_edit_non_text_files")
  150. }
  151. switch {
  152. case isTextFile:
  153. if blob.Size() >= setting.UI.MaxDisplayFileSize {
  154. ctx.Data["IsFileTooLarge"] = true
  155. break
  156. }
  157. d, _ := ioutil.ReadAll(dataRc)
  158. buf = append(buf, d...)
  159. isMarkdown := markdown.IsMarkdownFile(blob.Name())
  160. ctx.Data["IsMarkdown"] = isMarkdown
  161. readmeExist := isMarkdown || markdown.IsReadmeFile(blob.Name())
  162. ctx.Data["ReadmeExist"] = readmeExist
  163. if readmeExist && isMarkdown {
  164. ctx.Data["FileContent"] = string(markdown.Render(buf, path.Dir(treeLink), ctx.Repo.Repository.ComposeMetas()))
  165. } else {
  166. // Building code view blocks with line number on server side.
  167. var fileContent string
  168. if content, err := templates.ToUTF8WithErr(buf); err != nil {
  169. if err != nil {
  170. log.Error(4, "ToUTF8WithErr: %s", err)
  171. }
  172. fileContent = string(buf)
  173. } else {
  174. fileContent = content
  175. }
  176. var output bytes.Buffer
  177. lines := strings.Split(fileContent, "\n")
  178. for index, line := range lines {
  179. output.WriteString(fmt.Sprintf(`<li class="L%d" rel="L%d">%s</li>`, index+1, index+1, gotemplate.HTMLEscapeString(line)) + "\n")
  180. }
  181. ctx.Data["FileContent"] = gotemplate.HTML(output.String())
  182. output.Reset()
  183. for i := 0; i < len(lines); i++ {
  184. output.WriteString(fmt.Sprintf(`<span id="L%d">%d</span>`, i+1, i+1))
  185. }
  186. ctx.Data["LineNums"] = gotemplate.HTML(output.String())
  187. }
  188. if ctx.Repo.CanEnableEditor() {
  189. ctx.Data["CanEditFile"] = true
  190. ctx.Data["EditFileTooltip"] = ctx.Tr("repo.editor.edit_this_file")
  191. } else if !ctx.Repo.IsViewBranch {
  192. ctx.Data["EditFileTooltip"] = ctx.Tr("repo.editor.must_be_on_a_branch")
  193. } else if !ctx.Repo.IsWriter() {
  194. ctx.Data["EditFileTooltip"] = ctx.Tr("repo.editor.fork_before_edit")
  195. }
  196. case base.IsPDFFile(buf):
  197. ctx.Data["IsPDFFile"] = true
  198. case base.IsVideoFile(buf):
  199. ctx.Data["IsVideoFile"] = true
  200. case base.IsImageFile(buf):
  201. ctx.Data["IsImageFile"] = true
  202. }
  203. if ctx.Repo.CanEnableEditor() {
  204. ctx.Data["CanDeleteFile"] = true
  205. ctx.Data["DeleteFileTooltip"] = ctx.Tr("repo.editor.delete_this_file")
  206. } else if !ctx.Repo.IsViewBranch {
  207. ctx.Data["DeleteFileTooltip"] = ctx.Tr("repo.editor.must_be_on_a_branch")
  208. } else if !ctx.Repo.IsWriter() {
  209. ctx.Data["DeleteFileTooltip"] = ctx.Tr("repo.editor.must_have_write_access")
  210. }
  211. }
  212. // Home render repository home page
  213. func Home(ctx *context.Context) {
  214. title := ctx.Repo.Repository.Owner.Name + "/" + ctx.Repo.Repository.Name
  215. if len(ctx.Repo.Repository.Description) > 0 {
  216. title += ": " + ctx.Repo.Repository.Description
  217. }
  218. ctx.Data["Title"] = title
  219. ctx.Data["PageIsViewCode"] = true
  220. ctx.Data["RequireHighlightJS"] = true
  221. branchLink := ctx.Repo.RepoLink + "/src/" + ctx.Repo.BranchName
  222. treeLink := branchLink
  223. rawLink := ctx.Repo.RepoLink + "/raw/" + ctx.Repo.BranchName
  224. if len(ctx.Repo.TreePath) > 0 {
  225. treeLink += "/" + ctx.Repo.TreePath
  226. }
  227. // Get current entry user currently looking at.
  228. entry, err := ctx.Repo.Commit.GetTreeEntryByPath(ctx.Repo.TreePath)
  229. if err != nil {
  230. ctx.NotFoundOrServerError("Repo.Commit.GetTreeEntryByPath", git.IsErrNotExist, err)
  231. return
  232. }
  233. if entry.IsDir() {
  234. renderDirectory(ctx, treeLink)
  235. } else {
  236. renderFile(ctx, entry, treeLink, rawLink)
  237. }
  238. if ctx.Written() {
  239. return
  240. }
  241. var treeNames []string
  242. paths := make([]string, 0, 5)
  243. if len(ctx.Repo.TreePath) > 0 {
  244. treeNames = strings.Split(ctx.Repo.TreePath, "/")
  245. for i := range treeNames {
  246. paths = append(paths, strings.Join(treeNames[:i+1], "/"))
  247. }
  248. ctx.Data["HasParentPath"] = true
  249. if len(paths)-2 >= 0 {
  250. ctx.Data["ParentPath"] = "/" + paths[len(paths)-2]
  251. }
  252. }
  253. ctx.Data["Paths"] = paths
  254. ctx.Data["TreeLink"] = treeLink
  255. ctx.Data["TreeNames"] = treeNames
  256. ctx.Data["BranchLink"] = branchLink
  257. ctx.HTML(200, tplRepoHome)
  258. }
  259. // RenderUserCards render a page show users accroding the input templaet
  260. func RenderUserCards(ctx *context.Context, total int, getter func(page int) ([]*models.User, error), tpl base.TplName) {
  261. page := ctx.QueryInt("page")
  262. if page <= 0 {
  263. page = 1
  264. }
  265. pager := paginater.New(total, models.ItemsPerPage, page, 5)
  266. ctx.Data["Page"] = pager
  267. items, err := getter(pager.Current())
  268. if err != nil {
  269. ctx.Handle(500, "getter", err)
  270. return
  271. }
  272. ctx.Data["Cards"] = items
  273. ctx.HTML(200, tpl)
  274. }
  275. // Watchers render repository's watch users
  276. func Watchers(ctx *context.Context) {
  277. ctx.Data["Title"] = ctx.Tr("repo.watchers")
  278. ctx.Data["CardsTitle"] = ctx.Tr("repo.watchers")
  279. ctx.Data["PageIsWatchers"] = true
  280. RenderUserCards(ctx, ctx.Repo.Repository.NumWatches, ctx.Repo.Repository.GetWatchers, tplWatchers)
  281. }
  282. // Stars render repository's starred users
  283. func Stars(ctx *context.Context) {
  284. ctx.Data["Title"] = ctx.Tr("repo.stargazers")
  285. ctx.Data["CardsTitle"] = ctx.Tr("repo.stargazers")
  286. ctx.Data["PageIsStargazers"] = true
  287. RenderUserCards(ctx, ctx.Repo.Repository.NumStars, ctx.Repo.Repository.GetStargazers, tplWatchers)
  288. }
  289. // Forks render repository's forked users
  290. func Forks(ctx *context.Context) {
  291. ctx.Data["Title"] = ctx.Tr("repos.forks")
  292. forks, err := ctx.Repo.Repository.GetForks()
  293. if err != nil {
  294. ctx.Handle(500, "GetForks", err)
  295. return
  296. }
  297. for _, fork := range forks {
  298. if err = fork.GetOwner(); err != nil {
  299. ctx.Handle(500, "GetOwner", err)
  300. return
  301. }
  302. }
  303. ctx.Data["Forks"] = forks
  304. ctx.HTML(200, tplForks)
  305. }