選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

view.go 10KB

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