Fork to maintain patches against the official gitea for https://code.ceondo.com https://github.com/go-gitea/gitea

view.go 11KB

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