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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579
  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. // Check LFS Lock
  230. lfsLock, err := ctx.Repo.Repository.GetTreePathLock(ctx.Repo.TreePath)
  231. ctx.Data["LFSLock"] = lfsLock
  232. if err != nil {
  233. ctx.ServerError("GetTreePathLock", err)
  234. return
  235. }
  236. if lfsLock != nil {
  237. ctx.Data["LFSLockOwner"] = lfsLock.Owner.DisplayName()
  238. ctx.Data["LFSLockHint"] = ctx.Tr("repo.editor.this_file_locked")
  239. }
  240. // Assume file is not editable first.
  241. if isLFSFile {
  242. ctx.Data["EditFileTooltip"] = ctx.Tr("repo.editor.cannot_edit_lfs_files")
  243. } else if !isTextFile {
  244. ctx.Data["EditFileTooltip"] = ctx.Tr("repo.editor.cannot_edit_non_text_files")
  245. }
  246. switch {
  247. case isTextFile:
  248. if fileSize >= setting.UI.MaxDisplayFileSize {
  249. ctx.Data["IsFileTooLarge"] = true
  250. break
  251. }
  252. d, _ := ioutil.ReadAll(dataRc)
  253. buf = charset.ToUTF8WithFallback(append(buf, d...))
  254. readmeExist := markup.IsReadmeFile(blob.Name())
  255. ctx.Data["ReadmeExist"] = readmeExist
  256. if markupType := markup.Type(blob.Name()); markupType != "" {
  257. ctx.Data["IsMarkup"] = true
  258. ctx.Data["MarkupType"] = markupType
  259. ctx.Data["FileContent"] = string(markup.Render(blob.Name(), buf, path.Dir(treeLink), ctx.Repo.Repository.ComposeMetas()))
  260. } else if readmeExist {
  261. ctx.Data["IsRenderedHTML"] = true
  262. ctx.Data["FileContent"] = strings.Replace(
  263. gotemplate.HTMLEscapeString(string(buf)), "\n", `<br>`, -1,
  264. )
  265. } else {
  266. // Building code view blocks with line number on server side.
  267. var fileContent string
  268. if content, err := charset.ToUTF8WithErr(buf); err != nil {
  269. log.Error("ToUTF8WithErr: %v", err)
  270. fileContent = string(buf)
  271. } else {
  272. fileContent = content
  273. }
  274. var output bytes.Buffer
  275. lines := strings.Split(fileContent, "\n")
  276. ctx.Data["NumLines"] = len(lines)
  277. if len(lines) == 1 && lines[0] == "" {
  278. // If the file is completely empty, we show zero lines at the line counter
  279. ctx.Data["NumLines"] = 0
  280. }
  281. ctx.Data["NumLinesSet"] = true
  282. //Remove blank line at the end of file
  283. if len(lines) > 0 && lines[len(lines)-1] == "" {
  284. lines = lines[:len(lines)-1]
  285. }
  286. for index, line := range lines {
  287. line = gotemplate.HTMLEscapeString(line)
  288. if index != len(lines)-1 {
  289. line += "\n"
  290. }
  291. output.WriteString(fmt.Sprintf(`<li class="L%d" rel="L%d">%s</li>`, index+1, index+1, line))
  292. }
  293. ctx.Data["FileContent"] = gotemplate.HTML(output.String())
  294. output.Reset()
  295. for i := 0; i < len(lines); i++ {
  296. output.WriteString(fmt.Sprintf(`<span id="L%[1]d" data-line-number="%[1]d"></span>`, i+1))
  297. }
  298. ctx.Data["LineNums"] = gotemplate.HTML(output.String())
  299. }
  300. if !isLFSFile {
  301. if ctx.Repo.CanEnableEditor() {
  302. if lfsLock != nil && lfsLock.OwnerID != ctx.User.ID {
  303. ctx.Data["CanEditFile"] = false
  304. ctx.Data["EditFileTooltip"] = ctx.Tr("repo.editor.this_file_locked")
  305. } else {
  306. ctx.Data["CanEditFile"] = true
  307. ctx.Data["EditFileTooltip"] = ctx.Tr("repo.editor.edit_this_file")
  308. }
  309. } else if !ctx.Repo.IsViewBranch {
  310. ctx.Data["EditFileTooltip"] = ctx.Tr("repo.editor.must_be_on_a_branch")
  311. } else if !ctx.Repo.CanWrite(models.UnitTypeCode) {
  312. ctx.Data["EditFileTooltip"] = ctx.Tr("repo.editor.fork_before_edit")
  313. }
  314. }
  315. case base.IsPDFFile(buf):
  316. ctx.Data["IsPDFFile"] = true
  317. case base.IsVideoFile(buf):
  318. ctx.Data["IsVideoFile"] = true
  319. case base.IsAudioFile(buf):
  320. ctx.Data["IsAudioFile"] = true
  321. case base.IsImageFile(buf):
  322. ctx.Data["IsImageFile"] = true
  323. default:
  324. if fileSize >= setting.UI.MaxDisplayFileSize {
  325. ctx.Data["IsFileTooLarge"] = true
  326. break
  327. }
  328. if markupType := markup.Type(blob.Name()); markupType != "" {
  329. d, _ := ioutil.ReadAll(dataRc)
  330. buf = append(buf, d...)
  331. ctx.Data["IsMarkup"] = true
  332. ctx.Data["MarkupType"] = markupType
  333. ctx.Data["FileContent"] = string(markup.Render(blob.Name(), buf, path.Dir(treeLink), ctx.Repo.Repository.ComposeMetas()))
  334. }
  335. }
  336. if ctx.Repo.CanEnableEditor() {
  337. if lfsLock != nil && lfsLock.OwnerID != ctx.User.ID {
  338. ctx.Data["CanDeleteFile"] = false
  339. ctx.Data["DeleteFileTooltip"] = ctx.Tr("repo.editor.this_file_locked")
  340. } else {
  341. ctx.Data["CanDeleteFile"] = true
  342. ctx.Data["DeleteFileTooltip"] = ctx.Tr("repo.editor.delete_this_file")
  343. }
  344. } else if !ctx.Repo.IsViewBranch {
  345. ctx.Data["DeleteFileTooltip"] = ctx.Tr("repo.editor.must_be_on_a_branch")
  346. } else if !ctx.Repo.CanWrite(models.UnitTypeCode) {
  347. ctx.Data["DeleteFileTooltip"] = ctx.Tr("repo.editor.must_have_write_access")
  348. }
  349. }
  350. func safeURL(address string) string {
  351. u, err := url.Parse(address)
  352. if err != nil {
  353. return address
  354. }
  355. u.User = nil
  356. return u.String()
  357. }
  358. // Home render repository home page
  359. func Home(ctx *context.Context) {
  360. if len(ctx.Repo.Units) > 0 {
  361. if ctx.Repo.Repository.IsBeingCreated() {
  362. task, err := models.GetMigratingTask(ctx.Repo.Repository.ID)
  363. if err != nil {
  364. ctx.ServerError("models.GetMigratingTask", err)
  365. return
  366. }
  367. cfg, err := task.MigrateConfig()
  368. if err != nil {
  369. ctx.ServerError("task.MigrateConfig", err)
  370. return
  371. }
  372. ctx.Data["Repo"] = ctx.Repo
  373. ctx.Data["MigrateTask"] = task
  374. ctx.Data["CloneAddr"] = safeURL(cfg.CloneAddr)
  375. ctx.HTML(200, tplMigrating)
  376. return
  377. }
  378. var firstUnit *models.Unit
  379. for _, repoUnit := range ctx.Repo.Units {
  380. if repoUnit.Type == models.UnitTypeCode {
  381. renderCode(ctx)
  382. return
  383. }
  384. unit, ok := models.Units[repoUnit.Type]
  385. if ok && (firstUnit == nil || !firstUnit.IsLessThan(unit)) {
  386. firstUnit = &unit
  387. }
  388. }
  389. if firstUnit != nil {
  390. ctx.Redirect(fmt.Sprintf("%s/%s%s", setting.AppSubURL, ctx.Repo.Repository.FullName(), firstUnit.URI))
  391. return
  392. }
  393. }
  394. ctx.NotFound("Home", fmt.Errorf(ctx.Tr("units.error.no_unit_allowed_repo")))
  395. }
  396. func renderCode(ctx *context.Context) {
  397. ctx.Data["PageIsViewCode"] = true
  398. if ctx.Repo.Repository.IsEmpty {
  399. ctx.HTML(200, tplRepoEMPTY)
  400. return
  401. }
  402. title := ctx.Repo.Repository.Owner.Name + "/" + ctx.Repo.Repository.Name
  403. if len(ctx.Repo.Repository.Description) > 0 {
  404. title += ": " + ctx.Repo.Repository.Description
  405. }
  406. ctx.Data["Title"] = title
  407. ctx.Data["RequireHighlightJS"] = true
  408. branchLink := ctx.Repo.RepoLink + "/src/" + ctx.Repo.BranchNameSubURL()
  409. treeLink := branchLink
  410. rawLink := ctx.Repo.RepoLink + "/raw/" + ctx.Repo.BranchNameSubURL()
  411. if len(ctx.Repo.TreePath) > 0 {
  412. treeLink += "/" + ctx.Repo.TreePath
  413. }
  414. // Get Topics of this repo
  415. topics, err := models.FindTopics(&models.FindTopicOptions{
  416. RepoID: ctx.Repo.Repository.ID,
  417. })
  418. if err != nil {
  419. ctx.ServerError("models.FindTopics", err)
  420. return
  421. }
  422. ctx.Data["Topics"] = topics
  423. // Get current entry user currently looking at.
  424. entry, err := ctx.Repo.Commit.GetTreeEntryByPath(ctx.Repo.TreePath)
  425. if err != nil {
  426. ctx.NotFoundOrServerError("Repo.Commit.GetTreeEntryByPath", git.IsErrNotExist, err)
  427. return
  428. }
  429. if entry.IsDir() {
  430. renderDirectory(ctx, treeLink)
  431. } else {
  432. renderFile(ctx, entry, treeLink, rawLink)
  433. }
  434. if ctx.Written() {
  435. return
  436. }
  437. var treeNames []string
  438. paths := make([]string, 0, 5)
  439. if len(ctx.Repo.TreePath) > 0 {
  440. treeNames = strings.Split(ctx.Repo.TreePath, "/")
  441. for i := range treeNames {
  442. paths = append(paths, strings.Join(treeNames[:i+1], "/"))
  443. }
  444. ctx.Data["HasParentPath"] = true
  445. if len(paths)-2 >= 0 {
  446. ctx.Data["ParentPath"] = "/" + paths[len(paths)-2]
  447. }
  448. }
  449. ctx.Data["Paths"] = paths
  450. ctx.Data["TreeLink"] = treeLink
  451. ctx.Data["TreeNames"] = treeNames
  452. ctx.Data["BranchLink"] = branchLink
  453. ctx.HTML(200, tplRepoHome)
  454. }
  455. // RenderUserCards render a page show users according the input templaet
  456. func RenderUserCards(ctx *context.Context, total int, getter func(opts models.ListOptions) ([]*models.User, error), tpl base.TplName) {
  457. page := ctx.QueryInt("page")
  458. if page <= 0 {
  459. page = 1
  460. }
  461. pager := context.NewPagination(total, models.ItemsPerPage, page, 5)
  462. ctx.Data["Page"] = pager
  463. items, err := getter(models.ListOptions{Page: pager.Paginater.Current()})
  464. if err != nil {
  465. ctx.ServerError("getter", err)
  466. return
  467. }
  468. ctx.Data["Cards"] = items
  469. ctx.HTML(200, tpl)
  470. }
  471. // Watchers render repository's watch users
  472. func Watchers(ctx *context.Context) {
  473. ctx.Data["Title"] = ctx.Tr("repo.watchers")
  474. ctx.Data["CardsTitle"] = ctx.Tr("repo.watchers")
  475. ctx.Data["PageIsWatchers"] = true
  476. RenderUserCards(ctx, ctx.Repo.Repository.NumWatches, ctx.Repo.Repository.GetWatchers, tplWatchers)
  477. }
  478. // Stars render repository's starred users
  479. func Stars(ctx *context.Context) {
  480. ctx.Data["Title"] = ctx.Tr("repo.stargazers")
  481. ctx.Data["CardsTitle"] = ctx.Tr("repo.stargazers")
  482. ctx.Data["PageIsStargazers"] = true
  483. RenderUserCards(ctx, ctx.Repo.Repository.NumStars, ctx.Repo.Repository.GetStargazers, tplWatchers)
  484. }
  485. // Forks render repository's forked users
  486. func Forks(ctx *context.Context) {
  487. ctx.Data["Title"] = ctx.Tr("repos.forks")
  488. forks, err := ctx.Repo.Repository.GetForks(models.ListOptions{})
  489. if err != nil {
  490. ctx.ServerError("GetForks", err)
  491. return
  492. }
  493. for _, fork := range forks {
  494. if err = fork.GetOwner(); err != nil {
  495. ctx.ServerError("GetOwner", err)
  496. return
  497. }
  498. }
  499. ctx.Data["Forks"] = forks
  500. ctx.HTML(200, tplForks)
  501. }