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

view.go 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  1. // Copyright 2017 The Gitea Authors. All rights reserved.
  2. // Copyright 2014 The Gogs Authors. All rights reserved.
  3. // Use of this source code is governed by a MIT-style
  4. // license that can be found in the LICENSE file.
  5. package repo
  6. import (
  7. "bytes"
  8. "encoding/base64"
  9. "fmt"
  10. gotemplate "html/template"
  11. "io/ioutil"
  12. "path"
  13. "strconv"
  14. "strings"
  15. "code.gitea.io/git"
  16. "code.gitea.io/gitea/models"
  17. "code.gitea.io/gitea/modules/base"
  18. "code.gitea.io/gitea/modules/context"
  19. "code.gitea.io/gitea/modules/highlight"
  20. "code.gitea.io/gitea/modules/lfs"
  21. "code.gitea.io/gitea/modules/log"
  22. "code.gitea.io/gitea/modules/markup"
  23. "code.gitea.io/gitea/modules/setting"
  24. "code.gitea.io/gitea/modules/templates"
  25. "github.com/Unknwon/paginater"
  26. )
  27. const (
  28. tplRepoBARE base.TplName = "repo/bare"
  29. tplRepoHome base.TplName = "repo/home"
  30. tplWatchers base.TplName = "repo/watchers"
  31. tplForks base.TplName = "repo/forks"
  32. )
  33. func renderDirectory(ctx *context.Context, treeLink string) {
  34. tree, err := ctx.Repo.Commit.SubTree(ctx.Repo.TreePath)
  35. if err != nil {
  36. ctx.NotFoundOrServerError("Repo.Commit.SubTree", git.IsErrNotExist, err)
  37. return
  38. }
  39. entries, err := tree.ListEntries()
  40. if err != nil {
  41. ctx.Handle(500, "ListEntries", err)
  42. return
  43. }
  44. entries.CustomSort(base.NaturalSortLess)
  45. ctx.Data["Files"], err = entries.GetCommitsInfo(ctx.Repo.Commit, ctx.Repo.TreePath)
  46. if err != nil {
  47. ctx.Handle(500, "GetCommitsInfo", err)
  48. return
  49. }
  50. var readmeFile *git.Blob
  51. for _, entry := range entries {
  52. if entry.IsDir() {
  53. continue
  54. }
  55. if !markup.IsReadmeFile(entry.Name()) {
  56. continue
  57. }
  58. readmeFile = entry.Blob()
  59. if markup.Type(entry.Name()) != "" {
  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["IsMarkup"] = 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["IsMarkup"] = false
  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. statuses, err := models.GetLatestCommitStatus(ctx.Repo.Repository, ctx.Repo.Commit.ID.String(), 0)
  108. if err != nil {
  109. log.Error(3, "GetLatestCommitStatus: %v", err)
  110. }
  111. ctx.Data["LatestCommitStatus"] = models.CalcCommitStatus(statuses)
  112. // Check permission to add or upload new file.
  113. if ctx.Repo.IsWriter() && ctx.Repo.IsViewBranch {
  114. ctx.Data["CanAddFile"] = true
  115. ctx.Data["CanUploadFile"] = setting.Repository.Upload.Enabled
  116. }
  117. }
  118. func renderFile(ctx *context.Context, entry *git.TreeEntry, treeLink, rawLink string) {
  119. ctx.Data["IsViewFile"] = true
  120. blob := entry.Blob()
  121. dataRc, err := blob.Data()
  122. if err != nil {
  123. ctx.Handle(500, "Data", err)
  124. return
  125. }
  126. ctx.Data["FileSize"] = blob.Size()
  127. ctx.Data["FileName"] = blob.Name()
  128. ctx.Data["HighlightClass"] = highlight.FileNameToHighlightClass(blob.Name())
  129. ctx.Data["RawFileLink"] = rawLink + "/" + ctx.Repo.TreePath
  130. buf := make([]byte, 1024)
  131. n, _ := dataRc.Read(buf)
  132. buf = buf[:n]
  133. isTextFile := base.IsTextFile(buf)
  134. ctx.Data["IsTextFile"] = isTextFile
  135. //Check for LFS meta file
  136. if isTextFile && setting.LFS.StartServer {
  137. headString := string(buf)
  138. if strings.HasPrefix(headString, models.LFSMetaFileIdentifier) {
  139. splitLines := strings.Split(headString, "\n")
  140. if len(splitLines) >= 3 {
  141. oid := strings.TrimPrefix(splitLines[1], models.LFSMetaFileOidPrefix)
  142. size, err := strconv.ParseInt(strings.TrimPrefix(splitLines[2], "size "), 10, 64)
  143. if len(oid) == 64 && err == nil {
  144. contentStore := &lfs.ContentStore{BasePath: setting.LFS.ContentPath}
  145. meta := &models.LFSMetaObject{Oid: oid}
  146. if contentStore.Exists(meta) {
  147. ctx.Data["IsTextFile"] = false
  148. isTextFile = false
  149. ctx.Data["IsLFSFile"] = true
  150. ctx.Data["FileSize"] = size
  151. filenameBase64 := base64.RawURLEncoding.EncodeToString([]byte(blob.Name()))
  152. ctx.Data["RawFileLink"] = fmt.Sprintf("%s%s/info/lfs/objects/%s/%s", setting.AppURL, ctx.Repo.Repository.FullName(), oid, filenameBase64)
  153. }
  154. }
  155. }
  156. }
  157. }
  158. // Assume file is not editable first.
  159. if !isTextFile {
  160. ctx.Data["EditFileTooltip"] = ctx.Tr("repo.editor.cannot_edit_non_text_files")
  161. }
  162. switch {
  163. case isTextFile:
  164. if blob.Size() >= setting.UI.MaxDisplayFileSize {
  165. ctx.Data["IsFileTooLarge"] = true
  166. break
  167. }
  168. d, _ := ioutil.ReadAll(dataRc)
  169. buf = append(buf, d...)
  170. tp := markup.Type(blob.Name())
  171. isSupportedMarkup := tp != ""
  172. ctx.Data["IsMarkup"] = isSupportedMarkup
  173. readmeExist := markup.IsReadmeFile(blob.Name())
  174. ctx.Data["ReadmeExist"] = readmeExist
  175. if isSupportedMarkup {
  176. ctx.Data["FileContent"] = string(markup.Render(blob.Name(), buf, path.Dir(treeLink), ctx.Repo.Repository.ComposeMetas()))
  177. } else if readmeExist {
  178. ctx.Data["FileContent"] = string(bytes.Replace(buf, []byte("\n"), []byte(`<br>`), -1))
  179. } else {
  180. // Building code view blocks with line number on server side.
  181. var fileContent string
  182. if content, err := templates.ToUTF8WithErr(buf); err != nil {
  183. if err != nil {
  184. log.Error(4, "ToUTF8WithErr: %v", err)
  185. }
  186. fileContent = string(buf)
  187. } else {
  188. fileContent = content
  189. }
  190. var output bytes.Buffer
  191. lines := strings.Split(fileContent, "\n")
  192. for index, line := range lines {
  193. line = gotemplate.HTMLEscapeString(line)
  194. if index != len(lines)-1 {
  195. line += "\n"
  196. }
  197. output.WriteString(fmt.Sprintf(`<li class="L%d" rel="L%d">%s</li>`, index+1, index+1, line))
  198. }
  199. ctx.Data["FileContent"] = gotemplate.HTML(output.String())
  200. output.Reset()
  201. for i := 0; i < len(lines); i++ {
  202. output.WriteString(fmt.Sprintf(`<span id="L%d">%d</span>`, i+1, i+1))
  203. }
  204. ctx.Data["LineNums"] = gotemplate.HTML(output.String())
  205. }
  206. if ctx.Repo.CanEnableEditor() {
  207. ctx.Data["CanEditFile"] = true
  208. ctx.Data["EditFileTooltip"] = ctx.Tr("repo.editor.edit_this_file")
  209. } else if !ctx.Repo.IsViewBranch {
  210. ctx.Data["EditFileTooltip"] = ctx.Tr("repo.editor.must_be_on_a_branch")
  211. } else if !ctx.Repo.IsWriter() {
  212. ctx.Data["EditFileTooltip"] = ctx.Tr("repo.editor.fork_before_edit")
  213. }
  214. case base.IsPDFFile(buf):
  215. ctx.Data["IsPDFFile"] = true
  216. case base.IsVideoFile(buf):
  217. ctx.Data["IsVideoFile"] = true
  218. case base.IsImageFile(buf):
  219. ctx.Data["IsImageFile"] = true
  220. }
  221. if ctx.Repo.CanEnableEditor() {
  222. ctx.Data["CanDeleteFile"] = true
  223. ctx.Data["DeleteFileTooltip"] = ctx.Tr("repo.editor.delete_this_file")
  224. } else if !ctx.Repo.IsViewBranch {
  225. ctx.Data["DeleteFileTooltip"] = ctx.Tr("repo.editor.must_be_on_a_branch")
  226. } else if !ctx.Repo.IsWriter() {
  227. ctx.Data["DeleteFileTooltip"] = ctx.Tr("repo.editor.must_have_write_access")
  228. }
  229. }
  230. // Home render repository home page
  231. func Home(ctx *context.Context) {
  232. if len(ctx.Repo.Repository.Units) > 0 {
  233. var firstUnit *models.Unit
  234. for _, repoUnit := range ctx.Repo.Repository.Units {
  235. if repoUnit.Type == models.UnitTypeCode {
  236. renderCode(ctx)
  237. return
  238. }
  239. unit, ok := models.Units[repoUnit.Type]
  240. if ok && (firstUnit == nil || !firstUnit.IsLessThan(unit)) {
  241. firstUnit = &unit
  242. }
  243. }
  244. if firstUnit != nil {
  245. ctx.Redirect(fmt.Sprintf("%s/%s%s", setting.AppSubURL, ctx.Repo.Repository.FullName(), firstUnit.URI))
  246. return
  247. }
  248. }
  249. ctx.Handle(404, "Home", fmt.Errorf(ctx.Tr("units.error.no_unit_allowed_repo")))
  250. }
  251. func renderCode(ctx *context.Context) {
  252. ctx.Data["PageIsViewCode"] = true
  253. if ctx.Repo.Repository.IsBare {
  254. ctx.HTML(200, tplRepoBARE)
  255. return
  256. }
  257. title := ctx.Repo.Repository.Owner.Name + "/" + ctx.Repo.Repository.Name
  258. if len(ctx.Repo.Repository.Description) > 0 {
  259. title += ": " + ctx.Repo.Repository.Description
  260. }
  261. ctx.Data["Title"] = title
  262. ctx.Data["RequireHighlightJS"] = true
  263. branchLink := ctx.Repo.RepoLink + "/src/" + ctx.Repo.BranchName
  264. treeLink := branchLink
  265. rawLink := ctx.Repo.RepoLink + "/raw/" + ctx.Repo.BranchName
  266. if len(ctx.Repo.TreePath) > 0 {
  267. treeLink += "/" + ctx.Repo.TreePath
  268. }
  269. // Get current entry user currently looking at.
  270. entry, err := ctx.Repo.Commit.GetTreeEntryByPath(ctx.Repo.TreePath)
  271. if err != nil {
  272. ctx.NotFoundOrServerError("Repo.Commit.GetTreeEntryByPath", git.IsErrNotExist, err)
  273. return
  274. }
  275. if entry.IsDir() {
  276. renderDirectory(ctx, treeLink)
  277. } else {
  278. renderFile(ctx, entry, treeLink, rawLink)
  279. }
  280. if ctx.Written() {
  281. return
  282. }
  283. var treeNames []string
  284. paths := make([]string, 0, 5)
  285. if len(ctx.Repo.TreePath) > 0 {
  286. treeNames = strings.Split(ctx.Repo.TreePath, "/")
  287. for i := range treeNames {
  288. paths = append(paths, strings.Join(treeNames[:i+1], "/"))
  289. }
  290. ctx.Data["HasParentPath"] = true
  291. if len(paths)-2 >= 0 {
  292. ctx.Data["ParentPath"] = "/" + paths[len(paths)-2]
  293. }
  294. }
  295. ctx.Data["Paths"] = paths
  296. ctx.Data["TreeLink"] = treeLink
  297. ctx.Data["TreeNames"] = treeNames
  298. ctx.Data["BranchLink"] = branchLink
  299. ctx.HTML(200, tplRepoHome)
  300. }
  301. // RenderUserCards render a page show users according the input templaet
  302. func RenderUserCards(ctx *context.Context, total int, getter func(page int) ([]*models.User, error), tpl base.TplName) {
  303. page := ctx.QueryInt("page")
  304. if page <= 0 {
  305. page = 1
  306. }
  307. pager := paginater.New(total, models.ItemsPerPage, page, 5)
  308. ctx.Data["Page"] = pager
  309. items, err := getter(pager.Current())
  310. if err != nil {
  311. ctx.Handle(500, "getter", err)
  312. return
  313. }
  314. ctx.Data["Cards"] = items
  315. ctx.HTML(200, tpl)
  316. }
  317. // Watchers render repository's watch users
  318. func Watchers(ctx *context.Context) {
  319. ctx.Data["Title"] = ctx.Tr("repo.watchers")
  320. ctx.Data["CardsTitle"] = ctx.Tr("repo.watchers")
  321. ctx.Data["PageIsWatchers"] = true
  322. RenderUserCards(ctx, ctx.Repo.Repository.NumWatches, ctx.Repo.Repository.GetWatchers, tplWatchers)
  323. }
  324. // Stars render repository's starred users
  325. func Stars(ctx *context.Context) {
  326. ctx.Data["Title"] = ctx.Tr("repo.stargazers")
  327. ctx.Data["CardsTitle"] = ctx.Tr("repo.stargazers")
  328. ctx.Data["PageIsStargazers"] = true
  329. RenderUserCards(ctx, ctx.Repo.Repository.NumStars, ctx.Repo.Repository.GetStargazers, tplWatchers)
  330. }
  331. // Forks render repository's forked users
  332. func Forks(ctx *context.Context) {
  333. ctx.Data["Title"] = ctx.Tr("repos.forks")
  334. forks, err := ctx.Repo.Repository.GetForks()
  335. if err != nil {
  336. ctx.Handle(500, "GetForks", err)
  337. return
  338. }
  339. for _, fork := range forks {
  340. if err = fork.GetOwner(); err != nil {
  341. ctx.Handle(500, "GetOwner", err)
  342. return
  343. }
  344. }
  345. ctx.Data["Forks"] = forks
  346. ctx.HTML(200, tplForks)
  347. }