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 13KB

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