本站源代码
Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

554 lines
15KB

  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. "net/url"
  13. "path"
  14. "strings"
  15. "code.gitea.io/gitea/models"
  16. "code.gitea.io/gitea/modules/base"
  17. "code.gitea.io/gitea/modules/charset"
  18. "code.gitea.io/gitea/modules/context"
  19. "code.gitea.io/gitea/modules/git"
  20. "code.gitea.io/gitea/modules/highlight"
  21. "code.gitea.io/gitea/modules/lfs"
  22. "code.gitea.io/gitea/modules/log"
  23. "code.gitea.io/gitea/modules/markup"
  24. "code.gitea.io/gitea/modules/setting"
  25. )
  26. const (
  27. tplRepoEMPTY base.TplName = "repo/empty"
  28. tplRepoHome base.TplName = "repo/home"
  29. tplWatchers base.TplName = "repo/watchers"
  30. tplForks base.TplName = "repo/forks"
  31. tplMigrating base.TplName = "repo/migrating"
  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. var latestCommit *git.Commit
  46. ctx.Data["Files"], latestCommit, err = entries.GetCommitsInfo(ctx.Repo.Commit, ctx.Repo.TreePath, nil)
  47. if err != nil {
  48. ctx.ServerError("GetCommitsInfo", err)
  49. return
  50. }
  51. // 3 for the extensions in exts[] in order
  52. // the last one is for a readme that doesn't
  53. // strictly match an extension
  54. var readmeFiles [4]*git.Blob
  55. var exts = []string{".md", ".txt", ""} // sorted by priority
  56. for _, entry := range entries {
  57. if entry.IsDir() {
  58. continue
  59. }
  60. for i, ext := range exts {
  61. if markup.IsReadmeFile(entry.Name(), ext) {
  62. readmeFiles[i] = entry.Blob()
  63. }
  64. }
  65. if markup.IsReadmeFile(entry.Name()) {
  66. readmeFiles[3] = entry.Blob()
  67. }
  68. }
  69. var readmeFile *git.Blob
  70. for _, f := range readmeFiles {
  71. if f != nil {
  72. readmeFile = f
  73. break
  74. }
  75. }
  76. if readmeFile != nil {
  77. ctx.Data["RawFileLink"] = ""
  78. ctx.Data["ReadmeInList"] = true
  79. ctx.Data["ReadmeExist"] = true
  80. dataRc, err := readmeFile.DataAsync()
  81. if err != nil {
  82. ctx.ServerError("Data", err)
  83. return
  84. }
  85. defer dataRc.Close()
  86. buf := make([]byte, 1024)
  87. n, _ := dataRc.Read(buf)
  88. buf = buf[:n]
  89. isTextFile := base.IsTextFile(buf)
  90. ctx.Data["FileIsText"] = isTextFile
  91. ctx.Data["FileName"] = readmeFile.Name()
  92. fileSize := int64(0)
  93. isLFSFile := false
  94. ctx.Data["IsLFSFile"] = false
  95. // FIXME: what happens when README file is an image?
  96. if isTextFile && setting.LFS.StartServer {
  97. meta := lfs.IsPointerFile(&buf)
  98. if meta != nil {
  99. meta, err = ctx.Repo.Repository.GetLFSMetaObjectByOid(meta.Oid)
  100. if err != nil && err != models.ErrLFSObjectNotExist {
  101. ctx.ServerError("GetLFSMetaObject", err)
  102. return
  103. }
  104. }
  105. if meta != nil {
  106. ctx.Data["IsLFSFile"] = true
  107. isLFSFile = true
  108. // OK read the lfs object
  109. var err error
  110. dataRc, err = lfs.ReadMetaObject(meta)
  111. if err != nil {
  112. ctx.ServerError("ReadMetaObject", err)
  113. return
  114. }
  115. defer dataRc.Close()
  116. buf = make([]byte, 1024)
  117. n, err = dataRc.Read(buf)
  118. if err != nil {
  119. ctx.ServerError("Data", err)
  120. return
  121. }
  122. buf = buf[:n]
  123. isTextFile = base.IsTextFile(buf)
  124. ctx.Data["IsTextFile"] = isTextFile
  125. fileSize = meta.Size
  126. ctx.Data["FileSize"] = meta.Size
  127. filenameBase64 := base64.RawURLEncoding.EncodeToString([]byte(readmeFile.Name()))
  128. ctx.Data["RawFileLink"] = fmt.Sprintf("%s%s.git/info/lfs/objects/%s/%s", setting.AppURL, ctx.Repo.Repository.FullName(), meta.Oid, filenameBase64)
  129. }
  130. }
  131. if !isLFSFile {
  132. fileSize = readmeFile.Size()
  133. }
  134. if isTextFile {
  135. if fileSize >= setting.UI.MaxDisplayFileSize {
  136. // Pretend that this is a normal text file to display 'This file is too large to be shown'
  137. ctx.Data["IsFileTooLarge"] = true
  138. ctx.Data["IsTextFile"] = true
  139. ctx.Data["FileSize"] = fileSize
  140. } else {
  141. d, _ := ioutil.ReadAll(dataRc)
  142. buf = charset.ToUTF8WithFallback(append(buf, d...))
  143. if markupType := markup.Type(readmeFile.Name()); markupType != "" {
  144. ctx.Data["IsMarkup"] = true
  145. ctx.Data["MarkupType"] = string(markupType)
  146. ctx.Data["FileContent"] = string(markup.Render(readmeFile.Name(), buf, treeLink, ctx.Repo.Repository.ComposeMetas()))
  147. } else {
  148. ctx.Data["IsRenderedHTML"] = true
  149. ctx.Data["FileContent"] = strings.Replace(
  150. gotemplate.HTMLEscapeString(string(buf)), "\n", `<br>`, -1,
  151. )
  152. }
  153. }
  154. }
  155. }
  156. // Show latest commit info of repository in table header,
  157. // or of directory if not in root directory.
  158. ctx.Data["LatestCommit"] = latestCommit
  159. ctx.Data["LatestCommitVerification"] = models.ParseCommitWithSignature(latestCommit)
  160. ctx.Data["LatestCommitUser"] = models.ValidateCommitWithEmail(latestCommit)
  161. statuses, err := models.GetLatestCommitStatus(ctx.Repo.Repository, ctx.Repo.Commit.ID.String(), 0)
  162. if err != nil {
  163. log.Error("GetLatestCommitStatus: %v", err)
  164. }
  165. ctx.Data["LatestCommitStatus"] = models.CalcCommitStatus(statuses)
  166. // Check permission to add or upload new file.
  167. if ctx.Repo.CanWrite(models.UnitTypeCode) && ctx.Repo.IsViewBranch {
  168. ctx.Data["CanAddFile"] = !ctx.Repo.Repository.IsArchived
  169. ctx.Data["CanUploadFile"] = setting.Repository.Upload.Enabled && !ctx.Repo.Repository.IsArchived
  170. }
  171. }
  172. func renderFile(ctx *context.Context, entry *git.TreeEntry, treeLink, rawLink string) {
  173. ctx.Data["IsViewFile"] = true
  174. blob := entry.Blob()
  175. dataRc, err := blob.DataAsync()
  176. if err != nil {
  177. ctx.ServerError("DataAsync", err)
  178. return
  179. }
  180. defer dataRc.Close()
  181. ctx.Data["Title"] = ctx.Data["Title"].(string) + " - " + ctx.Repo.TreePath + " at " + ctx.Repo.BranchName
  182. fileSize := blob.Size()
  183. ctx.Data["FileSize"] = fileSize
  184. ctx.Data["FileName"] = blob.Name()
  185. ctx.Data["HighlightClass"] = highlight.FileNameToHighlightClass(blob.Name())
  186. ctx.Data["RawFileLink"] = rawLink + "/" + ctx.Repo.TreePath
  187. buf := make([]byte, 1024)
  188. n, _ := dataRc.Read(buf)
  189. buf = buf[:n]
  190. isTextFile := base.IsTextFile(buf)
  191. isLFSFile := false
  192. ctx.Data["IsTextFile"] = isTextFile
  193. //Check for LFS meta file
  194. if isTextFile && setting.LFS.StartServer {
  195. meta := lfs.IsPointerFile(&buf)
  196. if meta != nil {
  197. meta, err = ctx.Repo.Repository.GetLFSMetaObjectByOid(meta.Oid)
  198. if err != nil && err != models.ErrLFSObjectNotExist {
  199. ctx.ServerError("GetLFSMetaObject", err)
  200. return
  201. }
  202. }
  203. if meta != nil {
  204. ctx.Data["IsLFSFile"] = true
  205. isLFSFile = true
  206. // OK read the lfs object
  207. var err error
  208. dataRc, err = lfs.ReadMetaObject(meta)
  209. if err != nil {
  210. ctx.ServerError("ReadMetaObject", err)
  211. return
  212. }
  213. defer dataRc.Close()
  214. buf = make([]byte, 1024)
  215. n, err = dataRc.Read(buf)
  216. if err != nil {
  217. ctx.ServerError("Data", err)
  218. return
  219. }
  220. buf = buf[:n]
  221. isTextFile = base.IsTextFile(buf)
  222. ctx.Data["IsTextFile"] = isTextFile
  223. fileSize = meta.Size
  224. ctx.Data["FileSize"] = meta.Size
  225. filenameBase64 := base64.RawURLEncoding.EncodeToString([]byte(blob.Name()))
  226. ctx.Data["RawFileLink"] = fmt.Sprintf("%s%s.git/info/lfs/objects/%s/%s", setting.AppURL, ctx.Repo.Repository.FullName(), meta.Oid, filenameBase64)
  227. }
  228. }
  229. // Assume file is not editable first.
  230. if isLFSFile {
  231. ctx.Data["EditFileTooltip"] = ctx.Tr("repo.editor.cannot_edit_lfs_files")
  232. } else if !isTextFile {
  233. ctx.Data["EditFileTooltip"] = ctx.Tr("repo.editor.cannot_edit_non_text_files")
  234. }
  235. switch {
  236. case isTextFile:
  237. if fileSize >= setting.UI.MaxDisplayFileSize {
  238. ctx.Data["IsFileTooLarge"] = true
  239. break
  240. }
  241. d, _ := ioutil.ReadAll(dataRc)
  242. buf = charset.ToUTF8WithFallback(append(buf, d...))
  243. readmeExist := markup.IsReadmeFile(blob.Name())
  244. ctx.Data["ReadmeExist"] = readmeExist
  245. if markupType := markup.Type(blob.Name()); markupType != "" {
  246. ctx.Data["IsMarkup"] = true
  247. ctx.Data["MarkupType"] = markupType
  248. ctx.Data["FileContent"] = string(markup.Render(blob.Name(), buf, path.Dir(treeLink), ctx.Repo.Repository.ComposeMetas()))
  249. } else if readmeExist {
  250. ctx.Data["IsRenderedHTML"] = true
  251. ctx.Data["FileContent"] = strings.Replace(
  252. gotemplate.HTMLEscapeString(string(buf)), "\n", `<br>`, -1,
  253. )
  254. } else {
  255. // Building code view blocks with line number on server side.
  256. var fileContent string
  257. if content, err := charset.ToUTF8WithErr(buf); err != nil {
  258. log.Error("ToUTF8WithErr: %v", err)
  259. fileContent = string(buf)
  260. } else {
  261. fileContent = content
  262. }
  263. var output bytes.Buffer
  264. lines := strings.Split(fileContent, "\n")
  265. ctx.Data["NumLines"] = len(lines)
  266. //Remove blank line at the end of file
  267. if len(lines) > 0 && lines[len(lines)-1] == "" {
  268. lines = lines[:len(lines)-1]
  269. }
  270. for index, line := range lines {
  271. line = gotemplate.HTMLEscapeString(line)
  272. if index != len(lines)-1 {
  273. line += "\n"
  274. }
  275. output.WriteString(fmt.Sprintf(`<li class="L%d" rel="L%d">%s</li>`, index+1, index+1, line))
  276. }
  277. ctx.Data["FileContent"] = gotemplate.HTML(output.String())
  278. output.Reset()
  279. for i := 0; i < len(lines); i++ {
  280. output.WriteString(fmt.Sprintf(`<span id="L%[1]d" data-line-number="%[1]d"></span>`, i+1))
  281. }
  282. ctx.Data["LineNums"] = gotemplate.HTML(output.String())
  283. }
  284. if !isLFSFile {
  285. if ctx.Repo.CanEnableEditor() {
  286. ctx.Data["CanEditFile"] = true
  287. ctx.Data["EditFileTooltip"] = ctx.Tr("repo.editor.edit_this_file")
  288. } else if !ctx.Repo.IsViewBranch {
  289. ctx.Data["EditFileTooltip"] = ctx.Tr("repo.editor.must_be_on_a_branch")
  290. } else if !ctx.Repo.CanWrite(models.UnitTypeCode) {
  291. ctx.Data["EditFileTooltip"] = ctx.Tr("repo.editor.fork_before_edit")
  292. }
  293. }
  294. case base.IsPDFFile(buf):
  295. ctx.Data["IsPDFFile"] = true
  296. case base.IsVideoFile(buf):
  297. ctx.Data["IsVideoFile"] = true
  298. case base.IsAudioFile(buf):
  299. ctx.Data["IsAudioFile"] = true
  300. case base.IsImageFile(buf):
  301. ctx.Data["IsImageFile"] = true
  302. default:
  303. if fileSize >= setting.UI.MaxDisplayFileSize {
  304. ctx.Data["IsFileTooLarge"] = true
  305. break
  306. }
  307. if markupType := markup.Type(blob.Name()); markupType != "" {
  308. d, _ := ioutil.ReadAll(dataRc)
  309. buf = append(buf, d...)
  310. ctx.Data["IsMarkup"] = true
  311. ctx.Data["MarkupType"] = markupType
  312. ctx.Data["FileContent"] = string(markup.Render(blob.Name(), buf, path.Dir(treeLink), ctx.Repo.Repository.ComposeMetas()))
  313. }
  314. }
  315. if ctx.Repo.CanEnableEditor() {
  316. ctx.Data["CanDeleteFile"] = true
  317. ctx.Data["DeleteFileTooltip"] = ctx.Tr("repo.editor.delete_this_file")
  318. } else if !ctx.Repo.IsViewBranch {
  319. ctx.Data["DeleteFileTooltip"] = ctx.Tr("repo.editor.must_be_on_a_branch")
  320. } else if !ctx.Repo.CanWrite(models.UnitTypeCode) {
  321. ctx.Data["DeleteFileTooltip"] = ctx.Tr("repo.editor.must_have_write_access")
  322. }
  323. }
  324. func safeURL(address string) string {
  325. u, err := url.Parse(address)
  326. if err != nil {
  327. return address
  328. }
  329. u.User = nil
  330. return u.String()
  331. }
  332. // Home render repository home page
  333. func Home(ctx *context.Context) {
  334. if len(ctx.Repo.Units) > 0 {
  335. if ctx.Repo.Repository.IsBeingCreated() {
  336. task, err := models.GetMigratingTask(ctx.Repo.Repository.ID)
  337. if err != nil {
  338. ctx.ServerError("models.GetMigratingTask", err)
  339. return
  340. }
  341. cfg, err := task.MigrateConfig()
  342. if err != nil {
  343. ctx.ServerError("task.MigrateConfig", err)
  344. return
  345. }
  346. ctx.Data["Repo"] = ctx.Repo
  347. ctx.Data["MigrateTask"] = task
  348. ctx.Data["CloneAddr"] = safeURL(cfg.CloneAddr)
  349. ctx.HTML(200, tplMigrating)
  350. return
  351. }
  352. var firstUnit *models.Unit
  353. for _, repoUnit := range ctx.Repo.Units {
  354. if repoUnit.Type == models.UnitTypeCode {
  355. renderCode(ctx)
  356. return
  357. }
  358. unit, ok := models.Units[repoUnit.Type]
  359. if ok && (firstUnit == nil || !firstUnit.IsLessThan(unit)) {
  360. firstUnit = &unit
  361. }
  362. }
  363. if firstUnit != nil {
  364. ctx.Redirect(fmt.Sprintf("%s/%s%s", setting.AppSubURL, ctx.Repo.Repository.FullName(), firstUnit.URI))
  365. return
  366. }
  367. }
  368. ctx.NotFound("Home", fmt.Errorf(ctx.Tr("units.error.no_unit_allowed_repo")))
  369. }
  370. func renderCode(ctx *context.Context) {
  371. ctx.Data["PageIsViewCode"] = true
  372. if ctx.Repo.Repository.IsEmpty {
  373. ctx.HTML(200, tplRepoEMPTY)
  374. return
  375. }
  376. title := ctx.Repo.Repository.Owner.Name + "/" + ctx.Repo.Repository.Name
  377. if len(ctx.Repo.Repository.Description) > 0 {
  378. title += ": " + ctx.Repo.Repository.Description
  379. }
  380. ctx.Data["Title"] = title
  381. ctx.Data["RequireHighlightJS"] = true
  382. branchLink := ctx.Repo.RepoLink + "/src/" + ctx.Repo.BranchNameSubURL()
  383. treeLink := branchLink
  384. rawLink := ctx.Repo.RepoLink + "/raw/" + ctx.Repo.BranchNameSubURL()
  385. if len(ctx.Repo.TreePath) > 0 {
  386. treeLink += "/" + ctx.Repo.TreePath
  387. }
  388. // Get Topics of this repo
  389. topics, err := models.FindTopics(&models.FindTopicOptions{
  390. RepoID: ctx.Repo.Repository.ID,
  391. })
  392. if err != nil {
  393. ctx.ServerError("models.FindTopics", err)
  394. return
  395. }
  396. ctx.Data["Topics"] = topics
  397. // Get current entry user currently looking at.
  398. entry, err := ctx.Repo.Commit.GetTreeEntryByPath(ctx.Repo.TreePath)
  399. if err != nil {
  400. ctx.NotFoundOrServerError("Repo.Commit.GetTreeEntryByPath", git.IsErrNotExist, err)
  401. return
  402. }
  403. if entry.IsDir() {
  404. renderDirectory(ctx, treeLink)
  405. } else {
  406. renderFile(ctx, entry, treeLink, rawLink)
  407. }
  408. if ctx.Written() {
  409. return
  410. }
  411. var treeNames []string
  412. paths := make([]string, 0, 5)
  413. if len(ctx.Repo.TreePath) > 0 {
  414. treeNames = strings.Split(ctx.Repo.TreePath, "/")
  415. for i := range treeNames {
  416. paths = append(paths, strings.Join(treeNames[:i+1], "/"))
  417. }
  418. ctx.Data["HasParentPath"] = true
  419. if len(paths)-2 >= 0 {
  420. ctx.Data["ParentPath"] = "/" + paths[len(paths)-2]
  421. }
  422. }
  423. ctx.Data["Paths"] = paths
  424. ctx.Data["TreeLink"] = treeLink
  425. ctx.Data["TreeNames"] = treeNames
  426. ctx.Data["BranchLink"] = branchLink
  427. ctx.HTML(200, tplRepoHome)
  428. }
  429. // RenderUserCards render a page show users according the input templaet
  430. func RenderUserCards(ctx *context.Context, total int, getter func(page int) ([]*models.User, error), tpl base.TplName) {
  431. page := ctx.QueryInt("page")
  432. if page <= 0 {
  433. page = 1
  434. }
  435. pager := context.NewPagination(total, models.ItemsPerPage, page, 5)
  436. ctx.Data["Page"] = pager
  437. items, err := getter(pager.Paginater.Current())
  438. if err != nil {
  439. ctx.ServerError("getter", err)
  440. return
  441. }
  442. ctx.Data["Cards"] = items
  443. ctx.HTML(200, tpl)
  444. }
  445. // Watchers render repository's watch users
  446. func Watchers(ctx *context.Context) {
  447. ctx.Data["Title"] = ctx.Tr("repo.watchers")
  448. ctx.Data["CardsTitle"] = ctx.Tr("repo.watchers")
  449. ctx.Data["PageIsWatchers"] = true
  450. RenderUserCards(ctx, ctx.Repo.Repository.NumWatches, ctx.Repo.Repository.GetWatchers, tplWatchers)
  451. }
  452. // Stars render repository's starred users
  453. func Stars(ctx *context.Context) {
  454. ctx.Data["Title"] = ctx.Tr("repo.stargazers")
  455. ctx.Data["CardsTitle"] = ctx.Tr("repo.stargazers")
  456. ctx.Data["PageIsStargazers"] = true
  457. RenderUserCards(ctx, ctx.Repo.Repository.NumStars, ctx.Repo.Repository.GetStargazers, tplWatchers)
  458. }
  459. // Forks render repository's forked users
  460. func Forks(ctx *context.Context) {
  461. ctx.Data["Title"] = ctx.Tr("repos.forks")
  462. forks, err := ctx.Repo.Repository.GetForks()
  463. if err != nil {
  464. ctx.ServerError("GetForks", err)
  465. return
  466. }
  467. for _, fork := range forks {
  468. if err = fork.GetOwner(); err != nil {
  469. ctx.ServerError("GetOwner", err)
  470. return
  471. }
  472. }
  473. ctx.Data["Forks"] = forks
  474. ctx.HTML(200, tplForks)
  475. }
上海开阖软件有限公司 沪ICP备12045867号-1