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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094
  1. // Copyright 2017 The Gitea Authors. All rights reserved.
  2. // Copyright 2014 The Gogs Authors. All rights reserved.
  3. // SPDX-License-Identifier: MIT
  4. package repo
  5. import (
  6. "bytes"
  7. gocontext "context"
  8. "encoding/base64"
  9. "fmt"
  10. "html/template"
  11. "image"
  12. "io"
  13. "net/http"
  14. "net/url"
  15. "path"
  16. "slices"
  17. "strings"
  18. "time"
  19. _ "image/gif" // for processing gif images
  20. _ "image/jpeg" // for processing jpeg images
  21. _ "image/png" // for processing png images
  22. activities_model "code.gitea.io/gitea/models/activities"
  23. admin_model "code.gitea.io/gitea/models/admin"
  24. asymkey_model "code.gitea.io/gitea/models/asymkey"
  25. "code.gitea.io/gitea/models/db"
  26. git_model "code.gitea.io/gitea/models/git"
  27. issue_model "code.gitea.io/gitea/models/issues"
  28. repo_model "code.gitea.io/gitea/models/repo"
  29. unit_model "code.gitea.io/gitea/models/unit"
  30. user_model "code.gitea.io/gitea/models/user"
  31. "code.gitea.io/gitea/modules/actions"
  32. "code.gitea.io/gitea/modules/base"
  33. "code.gitea.io/gitea/modules/charset"
  34. "code.gitea.io/gitea/modules/container"
  35. "code.gitea.io/gitea/modules/context"
  36. "code.gitea.io/gitea/modules/git"
  37. "code.gitea.io/gitea/modules/highlight"
  38. "code.gitea.io/gitea/modules/lfs"
  39. "code.gitea.io/gitea/modules/log"
  40. "code.gitea.io/gitea/modules/markup"
  41. repo_module "code.gitea.io/gitea/modules/repository"
  42. "code.gitea.io/gitea/modules/setting"
  43. "code.gitea.io/gitea/modules/structs"
  44. "code.gitea.io/gitea/modules/typesniffer"
  45. "code.gitea.io/gitea/modules/util"
  46. "code.gitea.io/gitea/routers/web/feed"
  47. issue_service "code.gitea.io/gitea/services/issue"
  48. "github.com/nektos/act/pkg/model"
  49. _ "golang.org/x/image/bmp" // for processing bmp images
  50. _ "golang.org/x/image/webp" // for processing webp images
  51. )
  52. const (
  53. tplRepoEMPTY base.TplName = "repo/empty"
  54. tplRepoHome base.TplName = "repo/home"
  55. tplRepoViewList base.TplName = "repo/view_list"
  56. tplWatchers base.TplName = "repo/watchers"
  57. tplForks base.TplName = "repo/forks"
  58. tplMigrating base.TplName = "repo/migrate/migrating"
  59. )
  60. // locate a README for a tree in one of the supported paths.
  61. //
  62. // entries is passed to reduce calls to ListEntries(), so
  63. // this has precondition:
  64. //
  65. // entries == ctx.Repo.Commit.SubTree(ctx.Repo.TreePath).ListEntries()
  66. //
  67. // FIXME: There has to be a more efficient way of doing this
  68. func findReadmeFileInEntries(ctx *context.Context, entries []*git.TreeEntry, tryWellKnownDirs bool) (string, *git.TreeEntry, error) {
  69. // Create a list of extensions in priority order
  70. // 1. Markdown files - with and without localisation - e.g. README.en-us.md or README.md
  71. // 2. Txt files - e.g. README.txt
  72. // 3. No extension - e.g. README
  73. exts := append(localizedExtensions(".md", ctx.Locale.Language()), ".txt", "") // sorted by priority
  74. extCount := len(exts)
  75. readmeFiles := make([]*git.TreeEntry, extCount+1)
  76. docsEntries := make([]*git.TreeEntry, 3) // (one of docs/, .gitea/ or .github/)
  77. for _, entry := range entries {
  78. if tryWellKnownDirs && entry.IsDir() {
  79. // as a special case for the top-level repo introduction README,
  80. // fall back to subfolders, looking for e.g. docs/README.md, .gitea/README.zh-CN.txt, .github/README.txt, ...
  81. // (note that docsEntries is ignored unless we are at the root)
  82. lowerName := strings.ToLower(entry.Name())
  83. switch lowerName {
  84. case "docs":
  85. if entry.Name() == "docs" || docsEntries[0] == nil {
  86. docsEntries[0] = entry
  87. }
  88. case ".gitea":
  89. if entry.Name() == ".gitea" || docsEntries[1] == nil {
  90. docsEntries[1] = entry
  91. }
  92. case ".github":
  93. if entry.Name() == ".github" || docsEntries[2] == nil {
  94. docsEntries[2] = entry
  95. }
  96. }
  97. continue
  98. }
  99. if i, ok := util.IsReadmeFileExtension(entry.Name(), exts...); ok {
  100. log.Debug("Potential readme file: %s", entry.Name())
  101. if readmeFiles[i] == nil || base.NaturalSortLess(readmeFiles[i].Name(), entry.Blob().Name()) {
  102. if entry.IsLink() {
  103. target, err := entry.FollowLinks()
  104. if err != nil && !git.IsErrBadLink(err) {
  105. return "", nil, err
  106. } else if target != nil && (target.IsExecutable() || target.IsRegular()) {
  107. readmeFiles[i] = entry
  108. }
  109. } else {
  110. readmeFiles[i] = entry
  111. }
  112. }
  113. }
  114. }
  115. var readmeFile *git.TreeEntry
  116. for _, f := range readmeFiles {
  117. if f != nil {
  118. readmeFile = f
  119. break
  120. }
  121. }
  122. if ctx.Repo.TreePath == "" && readmeFile == nil {
  123. for _, subTreeEntry := range docsEntries {
  124. if subTreeEntry == nil {
  125. continue
  126. }
  127. subTree := subTreeEntry.Tree()
  128. if subTree == nil {
  129. // this should be impossible; if subTreeEntry exists so should this.
  130. continue
  131. }
  132. var err error
  133. childEntries, err := subTree.ListEntries()
  134. if err != nil {
  135. return "", nil, err
  136. }
  137. subfolder, readmeFile, err := findReadmeFileInEntries(ctx, childEntries, false)
  138. if err != nil && !git.IsErrNotExist(err) {
  139. return "", nil, err
  140. }
  141. if readmeFile != nil {
  142. return path.Join(subTreeEntry.Name(), subfolder), readmeFile, nil
  143. }
  144. }
  145. }
  146. return "", readmeFile, nil
  147. }
  148. func renderDirectory(ctx *context.Context, treeLink string) {
  149. entries := renderDirectoryFiles(ctx, 1*time.Second)
  150. if ctx.Written() {
  151. return
  152. }
  153. if ctx.Repo.TreePath != "" {
  154. ctx.Data["HideRepoInfo"] = true
  155. ctx.Data["Title"] = ctx.Tr("repo.file.title", ctx.Repo.Repository.Name+"/"+path.Base(ctx.Repo.TreePath), ctx.Repo.RefName)
  156. }
  157. subfolder, readmeFile, err := findReadmeFileInEntries(ctx, entries, true)
  158. if err != nil {
  159. ctx.ServerError("findReadmeFileInEntries", err)
  160. return
  161. }
  162. renderReadmeFile(ctx, subfolder, readmeFile, treeLink)
  163. }
  164. // localizedExtensions prepends the provided language code with and without a
  165. // regional identifier to the provided extension.
  166. // Note: the language code will always be lower-cased, if a region is present it must be separated with a `-`
  167. // Note: ext should be prefixed with a `.`
  168. func localizedExtensions(ext, languageCode string) (localizedExts []string) {
  169. if len(languageCode) < 1 {
  170. return []string{ext}
  171. }
  172. lowerLangCode := "." + strings.ToLower(languageCode)
  173. if strings.Contains(lowerLangCode, "-") {
  174. underscoreLangCode := strings.ReplaceAll(lowerLangCode, "-", "_")
  175. indexOfDash := strings.Index(lowerLangCode, "-")
  176. // e.g. [.zh-cn.md, .zh_cn.md, .zh.md, _zh.md, .md]
  177. return []string{lowerLangCode + ext, underscoreLangCode + ext, lowerLangCode[:indexOfDash] + ext, "_" + lowerLangCode[1:indexOfDash] + ext, ext}
  178. }
  179. // e.g. [.en.md, .md]
  180. return []string{lowerLangCode + ext, ext}
  181. }
  182. type fileInfo struct {
  183. isTextFile bool
  184. isLFSFile bool
  185. fileSize int64
  186. lfsMeta *lfs.Pointer
  187. st typesniffer.SniffedType
  188. }
  189. func getFileReader(ctx gocontext.Context, repoID int64, blob *git.Blob) ([]byte, io.ReadCloser, *fileInfo, error) {
  190. dataRc, err := blob.DataAsync()
  191. if err != nil {
  192. return nil, nil, nil, err
  193. }
  194. buf := make([]byte, 1024)
  195. n, _ := util.ReadAtMost(dataRc, buf)
  196. buf = buf[:n]
  197. st := typesniffer.DetectContentType(buf)
  198. isTextFile := st.IsText()
  199. // FIXME: what happens when README file is an image?
  200. if !isTextFile || !setting.LFS.StartServer {
  201. return buf, dataRc, &fileInfo{isTextFile, false, blob.Size(), nil, st}, nil
  202. }
  203. pointer, _ := lfs.ReadPointerFromBuffer(buf)
  204. if !pointer.IsValid() { // fallback to plain file
  205. return buf, dataRc, &fileInfo{isTextFile, false, blob.Size(), nil, st}, nil
  206. }
  207. meta, err := git_model.GetLFSMetaObjectByOid(ctx, repoID, pointer.Oid)
  208. if err != nil && err != git_model.ErrLFSObjectNotExist { // fallback to plain file
  209. return buf, dataRc, &fileInfo{isTextFile, false, blob.Size(), nil, st}, nil
  210. }
  211. dataRc.Close()
  212. if err != nil {
  213. return nil, nil, nil, err
  214. }
  215. dataRc, err = lfs.ReadMetaObject(pointer)
  216. if err != nil {
  217. return nil, nil, nil, err
  218. }
  219. buf = make([]byte, 1024)
  220. n, err = util.ReadAtMost(dataRc, buf)
  221. if err != nil {
  222. dataRc.Close()
  223. return nil, nil, nil, err
  224. }
  225. buf = buf[:n]
  226. st = typesniffer.DetectContentType(buf)
  227. return buf, dataRc, &fileInfo{st.IsText(), true, meta.Size, &meta.Pointer, st}, nil
  228. }
  229. func renderReadmeFile(ctx *context.Context, subfolder string, readmeFile *git.TreeEntry, readmeTreelink string) {
  230. target := readmeFile
  231. if readmeFile != nil && readmeFile.IsLink() {
  232. target, _ = readmeFile.FollowLinks()
  233. }
  234. if target == nil {
  235. // if findReadmeFile() failed and/or gave us a broken symlink (which it shouldn't)
  236. // simply skip rendering the README
  237. return
  238. }
  239. ctx.Data["RawFileLink"] = ""
  240. ctx.Data["ReadmeInList"] = true
  241. ctx.Data["ReadmeExist"] = true
  242. ctx.Data["FileIsSymlink"] = readmeFile.IsLink()
  243. buf, dataRc, fInfo, err := getFileReader(ctx, ctx.Repo.Repository.ID, target.Blob())
  244. if err != nil {
  245. ctx.ServerError("getFileReader", err)
  246. return
  247. }
  248. defer dataRc.Close()
  249. ctx.Data["FileIsText"] = fInfo.isTextFile
  250. ctx.Data["FileName"] = path.Join(subfolder, readmeFile.Name())
  251. ctx.Data["IsLFSFile"] = fInfo.isLFSFile
  252. if fInfo.isLFSFile {
  253. filenameBase64 := base64.RawURLEncoding.EncodeToString([]byte(readmeFile.Name()))
  254. ctx.Data["RawFileLink"] = fmt.Sprintf("%s.git/info/lfs/objects/%s/%s", ctx.Repo.Repository.Link(), url.PathEscape(fInfo.lfsMeta.Oid), url.PathEscape(filenameBase64))
  255. }
  256. if !fInfo.isTextFile {
  257. return
  258. }
  259. if fInfo.fileSize >= setting.UI.MaxDisplayFileSize {
  260. // Pretend that this is a normal text file to display 'This file is too large to be shown'
  261. ctx.Data["IsFileTooLarge"] = true
  262. ctx.Data["IsTextFile"] = true
  263. ctx.Data["FileSize"] = fInfo.fileSize
  264. return
  265. }
  266. rd := charset.ToUTF8WithFallbackReader(io.MultiReader(bytes.NewReader(buf), dataRc))
  267. if markupType := markup.Type(readmeFile.Name()); markupType != "" {
  268. ctx.Data["IsMarkup"] = true
  269. ctx.Data["MarkupType"] = markupType
  270. ctx.Data["EscapeStatus"], ctx.Data["FileContent"], err = markupRender(ctx, &markup.RenderContext{
  271. Ctx: ctx,
  272. RelativePath: path.Join(ctx.Repo.TreePath, readmeFile.Name()), // ctx.Repo.TreePath is the directory not the Readme so we must append the Readme filename (and path).
  273. URLPrefix: path.Join(readmeTreelink, subfolder),
  274. Metas: ctx.Repo.Repository.ComposeDocumentMetas(),
  275. GitRepo: ctx.Repo.GitRepo,
  276. }, rd)
  277. if err != nil {
  278. log.Error("Render failed for %s in %-v: %v Falling back to rendering source", readmeFile.Name(), ctx.Repo.Repository, err)
  279. delete(ctx.Data, "IsMarkup")
  280. }
  281. }
  282. if ctx.Data["IsMarkup"] != true {
  283. ctx.Data["IsPlainText"] = true
  284. content, err := io.ReadAll(rd)
  285. if err != nil {
  286. log.Error("Read readme content failed: %v", err)
  287. }
  288. contentEscaped := template.HTMLEscapeString(util.UnsafeBytesToString(content))
  289. ctx.Data["EscapeStatus"], ctx.Data["FileContent"] = charset.EscapeControlHTML(template.HTML(contentEscaped), ctx.Locale)
  290. }
  291. }
  292. func renderFile(ctx *context.Context, entry *git.TreeEntry, treeLink, rawLink string) {
  293. ctx.Data["IsViewFile"] = true
  294. ctx.Data["HideRepoInfo"] = true
  295. blob := entry.Blob()
  296. buf, dataRc, fInfo, err := getFileReader(ctx, ctx.Repo.Repository.ID, blob)
  297. if err != nil {
  298. ctx.ServerError("getFileReader", err)
  299. return
  300. }
  301. defer dataRc.Close()
  302. ctx.Data["Title"] = ctx.Tr("repo.file.title", ctx.Repo.Repository.Name+"/"+path.Base(ctx.Repo.TreePath), ctx.Repo.RefName)
  303. ctx.Data["FileIsSymlink"] = entry.IsLink()
  304. ctx.Data["FileName"] = blob.Name()
  305. ctx.Data["RawFileLink"] = rawLink + "/" + util.PathEscapeSegments(ctx.Repo.TreePath)
  306. if ctx.Repo.TreePath == ".editorconfig" {
  307. _, editorconfigWarning, editorconfigErr := ctx.Repo.GetEditorconfig(ctx.Repo.Commit)
  308. if editorconfigWarning != nil {
  309. ctx.Data["FileWarning"] = strings.TrimSpace(editorconfigWarning.Error())
  310. }
  311. if editorconfigErr != nil {
  312. ctx.Data["FileError"] = strings.TrimSpace(editorconfigErr.Error())
  313. }
  314. } else if issue_service.IsTemplateConfig(ctx.Repo.TreePath) {
  315. _, issueConfigErr := issue_service.GetTemplateConfig(ctx.Repo.GitRepo, ctx.Repo.TreePath, ctx.Repo.Commit)
  316. if issueConfigErr != nil {
  317. ctx.Data["FileError"] = strings.TrimSpace(issueConfigErr.Error())
  318. }
  319. } else if actions.IsWorkflow(ctx.Repo.TreePath) {
  320. content, err := actions.GetContentFromEntry(entry)
  321. if err != nil {
  322. log.Error("actions.GetContentFromEntry: %v", err)
  323. }
  324. _, workFlowErr := model.ReadWorkflow(bytes.NewReader(content))
  325. if workFlowErr != nil {
  326. ctx.Data["FileError"] = ctx.Locale.Tr("actions.runs.invalid_workflow_helper", workFlowErr.Error())
  327. }
  328. } else if slices.Contains([]string{"CODEOWNERS", "docs/CODEOWNERS", ".gitea/CODEOWNERS"}, ctx.Repo.TreePath) {
  329. if data, err := blob.GetBlobContent(setting.UI.MaxDisplayFileSize); err == nil {
  330. _, warnings := issue_model.GetCodeOwnersFromContent(ctx, data)
  331. if len(warnings) > 0 {
  332. ctx.Data["FileWarning"] = strings.Join(warnings, "\n")
  333. }
  334. }
  335. }
  336. isDisplayingSource := ctx.FormString("display") == "source"
  337. isDisplayingRendered := !isDisplayingSource
  338. if fInfo.isLFSFile {
  339. ctx.Data["RawFileLink"] = ctx.Repo.RepoLink + "/media/" + ctx.Repo.BranchNameSubURL() + "/" + util.PathEscapeSegments(ctx.Repo.TreePath)
  340. }
  341. isRepresentableAsText := fInfo.st.IsRepresentableAsText()
  342. if !isRepresentableAsText {
  343. // If we can't show plain text, always try to render.
  344. isDisplayingSource = false
  345. isDisplayingRendered = true
  346. }
  347. ctx.Data["IsLFSFile"] = fInfo.isLFSFile
  348. ctx.Data["FileSize"] = fInfo.fileSize
  349. ctx.Data["IsTextFile"] = fInfo.isTextFile
  350. ctx.Data["IsRepresentableAsText"] = isRepresentableAsText
  351. ctx.Data["IsDisplayingSource"] = isDisplayingSource
  352. ctx.Data["IsDisplayingRendered"] = isDisplayingRendered
  353. ctx.Data["IsExecutable"] = entry.IsExecutable()
  354. isTextSource := fInfo.isTextFile || isDisplayingSource
  355. ctx.Data["IsTextSource"] = isTextSource
  356. if isTextSource {
  357. ctx.Data["CanCopyContent"] = true
  358. }
  359. // Check LFS Lock
  360. lfsLock, err := git_model.GetTreePathLock(ctx, ctx.Repo.Repository.ID, ctx.Repo.TreePath)
  361. ctx.Data["LFSLock"] = lfsLock
  362. if err != nil {
  363. ctx.ServerError("GetTreePathLock", err)
  364. return
  365. }
  366. if lfsLock != nil {
  367. u, err := user_model.GetUserByID(ctx, lfsLock.OwnerID)
  368. if err != nil {
  369. ctx.ServerError("GetTreePathLock", err)
  370. return
  371. }
  372. ctx.Data["LFSLockOwner"] = u.Name
  373. ctx.Data["LFSLockOwnerHomeLink"] = u.HomeLink()
  374. ctx.Data["LFSLockHint"] = ctx.Tr("repo.editor.this_file_locked")
  375. }
  376. // Assume file is not editable first.
  377. if fInfo.isLFSFile {
  378. ctx.Data["EditFileTooltip"] = ctx.Tr("repo.editor.cannot_edit_lfs_files")
  379. } else if !isRepresentableAsText {
  380. ctx.Data["EditFileTooltip"] = ctx.Tr("repo.editor.cannot_edit_non_text_files")
  381. }
  382. switch {
  383. case isRepresentableAsText:
  384. if fInfo.st.IsSvgImage() {
  385. ctx.Data["IsImageFile"] = true
  386. ctx.Data["CanCopyContent"] = true
  387. ctx.Data["HasSourceRenderedToggle"] = true
  388. }
  389. if fInfo.fileSize >= setting.UI.MaxDisplayFileSize {
  390. ctx.Data["IsFileTooLarge"] = true
  391. break
  392. }
  393. rd := charset.ToUTF8WithFallbackReader(io.MultiReader(bytes.NewReader(buf), dataRc))
  394. shouldRenderSource := ctx.FormString("display") == "source"
  395. readmeExist := util.IsReadmeFileName(blob.Name())
  396. ctx.Data["ReadmeExist"] = readmeExist
  397. markupType := markup.Type(blob.Name())
  398. // If the markup is detected by custom markup renderer it should not be reset later on
  399. // to not pass it down to the render context.
  400. detected := false
  401. if markupType == "" {
  402. detected = true
  403. markupType = markup.DetectRendererType(blob.Name(), bytes.NewReader(buf))
  404. }
  405. if markupType != "" {
  406. ctx.Data["HasSourceRenderedToggle"] = true
  407. }
  408. if markupType != "" && !shouldRenderSource {
  409. ctx.Data["IsMarkup"] = true
  410. ctx.Data["MarkupType"] = markupType
  411. if !detected {
  412. markupType = ""
  413. }
  414. metas := ctx.Repo.Repository.ComposeDocumentMetas()
  415. metas["BranchNameSubURL"] = ctx.Repo.BranchNameSubURL()
  416. ctx.Data["EscapeStatus"], ctx.Data["FileContent"], err = markupRender(ctx, &markup.RenderContext{
  417. Ctx: ctx,
  418. Type: markupType,
  419. RelativePath: ctx.Repo.TreePath,
  420. URLPrefix: path.Dir(treeLink),
  421. Metas: metas,
  422. GitRepo: ctx.Repo.GitRepo,
  423. }, rd)
  424. if err != nil {
  425. ctx.ServerError("Render", err)
  426. return
  427. }
  428. // to prevent iframe load third-party url
  429. ctx.Resp.Header().Add("Content-Security-Policy", "frame-src 'self'")
  430. } else {
  431. buf, _ := io.ReadAll(rd)
  432. // empty: 0 lines; "a": one line; "a\n": two lines; "a\nb": two lines;
  433. // the NumLines is only used for the display on the UI: "xxx lines"
  434. if len(buf) == 0 {
  435. ctx.Data["NumLines"] = 0
  436. } else {
  437. ctx.Data["NumLines"] = bytes.Count(buf, []byte{'\n'}) + 1
  438. }
  439. ctx.Data["NumLinesSet"] = true
  440. language := ""
  441. indexFilename, worktree, deleteTemporaryFile, err := ctx.Repo.GitRepo.ReadTreeToTemporaryIndex(ctx.Repo.CommitID)
  442. if err == nil {
  443. defer deleteTemporaryFile()
  444. filename2attribute2info, err := ctx.Repo.GitRepo.CheckAttribute(git.CheckAttributeOpts{
  445. CachedOnly: true,
  446. Attributes: []string{"linguist-language", "gitlab-language"},
  447. Filenames: []string{ctx.Repo.TreePath},
  448. IndexFile: indexFilename,
  449. WorkTree: worktree,
  450. })
  451. if err != nil {
  452. log.Error("Unable to load attributes for %-v:%s. Error: %v", ctx.Repo.Repository, ctx.Repo.TreePath, err)
  453. }
  454. language = filename2attribute2info[ctx.Repo.TreePath]["linguist-language"]
  455. if language == "" || language == "unspecified" {
  456. language = filename2attribute2info[ctx.Repo.TreePath]["gitlab-language"]
  457. }
  458. if language == "unspecified" {
  459. language = ""
  460. }
  461. }
  462. fileContent, lexerName, err := highlight.File(blob.Name(), language, buf)
  463. ctx.Data["LexerName"] = lexerName
  464. if err != nil {
  465. log.Error("highlight.File failed, fallback to plain text: %v", err)
  466. fileContent = highlight.PlainText(buf)
  467. }
  468. status := &charset.EscapeStatus{}
  469. statuses := make([]*charset.EscapeStatus, len(fileContent))
  470. for i, line := range fileContent {
  471. statuses[i], fileContent[i] = charset.EscapeControlHTML(line, ctx.Locale)
  472. status = status.Or(statuses[i])
  473. }
  474. ctx.Data["EscapeStatus"] = status
  475. ctx.Data["FileContent"] = fileContent
  476. ctx.Data["LineEscapeStatus"] = statuses
  477. }
  478. if !fInfo.isLFSFile {
  479. if ctx.Repo.CanEnableEditor(ctx, ctx.Doer) {
  480. if lfsLock != nil && lfsLock.OwnerID != ctx.Doer.ID {
  481. ctx.Data["CanEditFile"] = false
  482. ctx.Data["EditFileTooltip"] = ctx.Tr("repo.editor.this_file_locked")
  483. } else {
  484. ctx.Data["CanEditFile"] = true
  485. ctx.Data["EditFileTooltip"] = ctx.Tr("repo.editor.edit_this_file")
  486. }
  487. } else if !ctx.Repo.IsViewBranch {
  488. ctx.Data["EditFileTooltip"] = ctx.Tr("repo.editor.must_be_on_a_branch")
  489. } else if !ctx.Repo.CanWriteToBranch(ctx, ctx.Doer, ctx.Repo.BranchName) {
  490. ctx.Data["EditFileTooltip"] = ctx.Tr("repo.editor.fork_before_edit")
  491. }
  492. }
  493. case fInfo.st.IsPDF():
  494. ctx.Data["IsPDFFile"] = true
  495. case fInfo.st.IsVideo():
  496. ctx.Data["IsVideoFile"] = true
  497. case fInfo.st.IsAudio():
  498. ctx.Data["IsAudioFile"] = true
  499. case fInfo.st.IsImage() && (setting.UI.SVG.Enabled || !fInfo.st.IsSvgImage()):
  500. ctx.Data["IsImageFile"] = true
  501. ctx.Data["CanCopyContent"] = true
  502. default:
  503. if fInfo.fileSize >= setting.UI.MaxDisplayFileSize {
  504. ctx.Data["IsFileTooLarge"] = true
  505. break
  506. }
  507. if markupType := markup.Type(blob.Name()); markupType != "" {
  508. rd := io.MultiReader(bytes.NewReader(buf), dataRc)
  509. ctx.Data["IsMarkup"] = true
  510. ctx.Data["MarkupType"] = markupType
  511. ctx.Data["EscapeStatus"], ctx.Data["FileContent"], err = markupRender(ctx, &markup.RenderContext{
  512. Ctx: ctx,
  513. RelativePath: ctx.Repo.TreePath,
  514. URLPrefix: path.Dir(treeLink),
  515. Metas: ctx.Repo.Repository.ComposeDocumentMetas(),
  516. GitRepo: ctx.Repo.GitRepo,
  517. }, rd)
  518. if err != nil {
  519. ctx.ServerError("Render", err)
  520. return
  521. }
  522. }
  523. }
  524. if fInfo.st.IsImage() && !fInfo.st.IsSvgImage() {
  525. img, _, err := image.DecodeConfig(bytes.NewReader(buf))
  526. if err == nil {
  527. // There are Image formats go can't decode
  528. // Instead of throwing an error in that case, we show the size only when we can decode
  529. ctx.Data["ImageSize"] = fmt.Sprintf("%dx%dpx", img.Width, img.Height)
  530. }
  531. }
  532. if ctx.Repo.CanEnableEditor(ctx, ctx.Doer) {
  533. if lfsLock != nil && lfsLock.OwnerID != ctx.Doer.ID {
  534. ctx.Data["CanDeleteFile"] = false
  535. ctx.Data["DeleteFileTooltip"] = ctx.Tr("repo.editor.this_file_locked")
  536. } else {
  537. ctx.Data["CanDeleteFile"] = true
  538. ctx.Data["DeleteFileTooltip"] = ctx.Tr("repo.editor.delete_this_file")
  539. }
  540. } else if !ctx.Repo.IsViewBranch {
  541. ctx.Data["DeleteFileTooltip"] = ctx.Tr("repo.editor.must_be_on_a_branch")
  542. } else if !ctx.Repo.CanWriteToBranch(ctx, ctx.Doer, ctx.Repo.BranchName) {
  543. ctx.Data["DeleteFileTooltip"] = ctx.Tr("repo.editor.must_have_write_access")
  544. }
  545. }
  546. func markupRender(ctx *context.Context, renderCtx *markup.RenderContext, input io.Reader) (escaped *charset.EscapeStatus, output template.HTML, err error) {
  547. markupRd, markupWr := io.Pipe()
  548. defer markupWr.Close()
  549. done := make(chan struct{})
  550. go func() {
  551. sb := &strings.Builder{}
  552. // We allow NBSP here this is rendered
  553. escaped, _ = charset.EscapeControlReader(markupRd, sb, ctx.Locale, charset.RuneNBSP)
  554. output = template.HTML(sb.String())
  555. close(done)
  556. }()
  557. err = markup.Render(renderCtx, input, markupWr)
  558. _ = markupWr.CloseWithError(err)
  559. <-done
  560. return escaped, output, err
  561. }
  562. func checkHomeCodeViewable(ctx *context.Context) {
  563. if len(ctx.Repo.Units) > 0 {
  564. if ctx.Repo.Repository.IsBeingCreated() {
  565. task, err := admin_model.GetMigratingTask(ctx, ctx.Repo.Repository.ID)
  566. if err != nil {
  567. if admin_model.IsErrTaskDoesNotExist(err) {
  568. ctx.Data["Repo"] = ctx.Repo
  569. ctx.Data["CloneAddr"] = ""
  570. ctx.Data["Failed"] = true
  571. ctx.HTML(http.StatusOK, tplMigrating)
  572. return
  573. }
  574. ctx.ServerError("models.GetMigratingTask", err)
  575. return
  576. }
  577. cfg, err := task.MigrateConfig()
  578. if err != nil {
  579. ctx.ServerError("task.MigrateConfig", err)
  580. return
  581. }
  582. ctx.Data["Repo"] = ctx.Repo
  583. ctx.Data["MigrateTask"] = task
  584. ctx.Data["CloneAddr"], _ = util.SanitizeURL(cfg.CloneAddr)
  585. ctx.Data["Failed"] = task.Status == structs.TaskStatusFailed
  586. ctx.HTML(http.StatusOK, tplMigrating)
  587. return
  588. }
  589. if ctx.IsSigned {
  590. // Set repo notification-status read if unread
  591. if err := activities_model.SetRepoReadBy(ctx, ctx.Repo.Repository.ID, ctx.Doer.ID); err != nil {
  592. ctx.ServerError("ReadBy", err)
  593. return
  594. }
  595. }
  596. var firstUnit *unit_model.Unit
  597. for _, repoUnit := range ctx.Repo.Units {
  598. if repoUnit.Type == unit_model.TypeCode {
  599. return
  600. }
  601. unit, ok := unit_model.Units[repoUnit.Type]
  602. if ok && (firstUnit == nil || !firstUnit.IsLessThan(unit)) {
  603. firstUnit = &unit
  604. }
  605. }
  606. if firstUnit != nil {
  607. ctx.Redirect(fmt.Sprintf("%s%s", ctx.Repo.Repository.Link(), firstUnit.URI))
  608. return
  609. }
  610. }
  611. ctx.NotFound("Home", fmt.Errorf(ctx.Tr("units.error.no_unit_allowed_repo")))
  612. }
  613. func checkCitationFile(ctx *context.Context, entry *git.TreeEntry) {
  614. if entry.Name() != "" {
  615. return
  616. }
  617. tree, err := ctx.Repo.Commit.SubTree(ctx.Repo.TreePath)
  618. if err != nil {
  619. HandleGitError(ctx, "Repo.Commit.SubTree", err)
  620. return
  621. }
  622. allEntries, err := tree.ListEntries()
  623. if err != nil {
  624. ctx.ServerError("ListEntries", err)
  625. return
  626. }
  627. for _, entry := range allEntries {
  628. if entry.Name() == "CITATION.cff" || entry.Name() == "CITATION.bib" {
  629. // Read Citation file contents
  630. if content, err := entry.Blob().GetBlobContent(setting.UI.MaxDisplayFileSize); err != nil {
  631. log.Error("checkCitationFile: GetBlobContent: %v", err)
  632. } else {
  633. ctx.Data["CitiationExist"] = true
  634. ctx.PageData["citationFileContent"] = content
  635. break
  636. }
  637. }
  638. }
  639. }
  640. // Home render repository home page
  641. func Home(ctx *context.Context) {
  642. if setting.Other.EnableFeed {
  643. isFeed, _, showFeedType := feed.GetFeedType(ctx.Params(":reponame"), ctx.Req)
  644. if isFeed {
  645. switch {
  646. case ctx.Link == fmt.Sprintf("%s.%s", ctx.Repo.RepoLink, showFeedType):
  647. feed.ShowRepoFeed(ctx, ctx.Repo.Repository, showFeedType)
  648. case ctx.Repo.TreePath == "":
  649. feed.ShowBranchFeed(ctx, ctx.Repo.Repository, showFeedType)
  650. case ctx.Repo.TreePath != "":
  651. feed.ShowFileFeed(ctx, ctx.Repo.Repository, showFeedType)
  652. }
  653. return
  654. }
  655. }
  656. checkHomeCodeViewable(ctx)
  657. if ctx.Written() {
  658. return
  659. }
  660. renderCode(ctx)
  661. }
  662. // LastCommit returns lastCommit data for the provided branch/tag/commit and directory (in url) and filenames in body
  663. func LastCommit(ctx *context.Context) {
  664. checkHomeCodeViewable(ctx)
  665. if ctx.Written() {
  666. return
  667. }
  668. renderDirectoryFiles(ctx, 0)
  669. if ctx.Written() {
  670. return
  671. }
  672. var treeNames []string
  673. paths := make([]string, 0, 5)
  674. if len(ctx.Repo.TreePath) > 0 {
  675. treeNames = strings.Split(ctx.Repo.TreePath, "/")
  676. for i := range treeNames {
  677. paths = append(paths, strings.Join(treeNames[:i+1], "/"))
  678. }
  679. ctx.Data["HasParentPath"] = true
  680. if len(paths)-2 >= 0 {
  681. ctx.Data["ParentPath"] = "/" + paths[len(paths)-2]
  682. }
  683. }
  684. branchLink := ctx.Repo.RepoLink + "/src/" + ctx.Repo.BranchNameSubURL()
  685. ctx.Data["BranchLink"] = branchLink
  686. ctx.HTML(http.StatusOK, tplRepoViewList)
  687. }
  688. func renderDirectoryFiles(ctx *context.Context, timeout time.Duration) git.Entries {
  689. tree, err := ctx.Repo.Commit.SubTree(ctx.Repo.TreePath)
  690. if err != nil {
  691. HandleGitError(ctx, "Repo.Commit.SubTree", err)
  692. return nil
  693. }
  694. ctx.Data["LastCommitLoaderURL"] = ctx.Repo.RepoLink + "/lastcommit/" + url.PathEscape(ctx.Repo.CommitID) + "/" + util.PathEscapeSegments(ctx.Repo.TreePath)
  695. // Get current entry user currently looking at.
  696. entry, err := ctx.Repo.Commit.GetTreeEntryByPath(ctx.Repo.TreePath)
  697. if err != nil {
  698. HandleGitError(ctx, "Repo.Commit.GetTreeEntryByPath", err)
  699. return nil
  700. }
  701. if !entry.IsDir() {
  702. HandleGitError(ctx, "Repo.Commit.GetTreeEntryByPath", err)
  703. return nil
  704. }
  705. allEntries, err := tree.ListEntries()
  706. if err != nil {
  707. ctx.ServerError("ListEntries", err)
  708. return nil
  709. }
  710. allEntries.CustomSort(base.NaturalSortLess)
  711. commitInfoCtx := gocontext.Context(ctx)
  712. if timeout > 0 {
  713. var cancel gocontext.CancelFunc
  714. commitInfoCtx, cancel = gocontext.WithTimeout(ctx, timeout)
  715. defer cancel()
  716. }
  717. selected := make(container.Set[string])
  718. selected.AddMultiple(ctx.FormStrings("f[]")...)
  719. entries := allEntries
  720. if len(selected) > 0 {
  721. entries = make(git.Entries, 0, len(selected))
  722. for _, entry := range allEntries {
  723. if selected.Contains(entry.Name()) {
  724. entries = append(entries, entry)
  725. }
  726. }
  727. }
  728. var latestCommit *git.Commit
  729. ctx.Data["Files"], latestCommit, err = entries.GetCommitsInfo(commitInfoCtx, ctx.Repo.Commit, ctx.Repo.TreePath)
  730. if err != nil {
  731. ctx.ServerError("GetCommitsInfo", err)
  732. return nil
  733. }
  734. // Show latest commit info of repository in table header,
  735. // or of directory if not in root directory.
  736. ctx.Data["LatestCommit"] = latestCommit
  737. if latestCommit != nil {
  738. verification := asymkey_model.ParseCommitWithSignature(ctx, latestCommit)
  739. if err := asymkey_model.CalculateTrustStatus(verification, ctx.Repo.Repository.GetTrustModel(), func(user *user_model.User) (bool, error) {
  740. return repo_model.IsOwnerMemberCollaborator(ctx, ctx.Repo.Repository, user.ID)
  741. }, nil); err != nil {
  742. ctx.ServerError("CalculateTrustStatus", err)
  743. return nil
  744. }
  745. ctx.Data["LatestCommitVerification"] = verification
  746. ctx.Data["LatestCommitUser"] = user_model.ValidateCommitWithEmail(ctx, latestCommit)
  747. statuses, _, err := git_model.GetLatestCommitStatus(ctx, ctx.Repo.Repository.ID, latestCommit.ID.String(), db.ListOptions{ListAll: true})
  748. if err != nil {
  749. log.Error("GetLatestCommitStatus: %v", err)
  750. }
  751. ctx.Data["LatestCommitStatus"] = git_model.CalcCommitStatus(statuses)
  752. ctx.Data["LatestCommitStatuses"] = statuses
  753. }
  754. branchLink := ctx.Repo.RepoLink + "/src/" + ctx.Repo.BranchNameSubURL()
  755. treeLink := branchLink
  756. if len(ctx.Repo.TreePath) > 0 {
  757. treeLink += "/" + util.PathEscapeSegments(ctx.Repo.TreePath)
  758. }
  759. ctx.Data["TreeLink"] = treeLink
  760. ctx.Data["SSHDomain"] = setting.SSH.Domain
  761. return allEntries
  762. }
  763. func renderLanguageStats(ctx *context.Context) {
  764. langs, err := repo_model.GetTopLanguageStats(ctx.Repo.Repository, 5)
  765. if err != nil {
  766. ctx.ServerError("Repo.GetTopLanguageStats", err)
  767. return
  768. }
  769. ctx.Data["LanguageStats"] = langs
  770. }
  771. func renderRepoTopics(ctx *context.Context) {
  772. topics, _, err := repo_model.FindTopics(ctx, &repo_model.FindTopicOptions{
  773. RepoID: ctx.Repo.Repository.ID,
  774. })
  775. if err != nil {
  776. ctx.ServerError("models.FindTopics", err)
  777. return
  778. }
  779. ctx.Data["Topics"] = topics
  780. }
  781. func renderCode(ctx *context.Context) {
  782. ctx.Data["PageIsViewCode"] = true
  783. ctx.Data["RepositoryUploadEnabled"] = setting.Repository.Upload.Enabled
  784. if ctx.Repo.Commit == nil || ctx.Repo.Repository.IsEmpty || ctx.Repo.Repository.IsBroken() {
  785. showEmpty := true
  786. var err error
  787. if ctx.Repo.GitRepo != nil {
  788. showEmpty, err = ctx.Repo.GitRepo.IsEmpty()
  789. if err != nil {
  790. log.Error("GitRepo.IsEmpty: %v", err)
  791. ctx.Repo.Repository.Status = repo_model.RepositoryBroken
  792. showEmpty = true
  793. ctx.Flash.Error(ctx.Tr("error.occurred"), true)
  794. }
  795. }
  796. if showEmpty {
  797. ctx.HTML(http.StatusOK, tplRepoEMPTY)
  798. return
  799. }
  800. // the repo is not really empty, so we should update the modal in database
  801. // such problem may be caused by:
  802. // 1) an error occurs during pushing/receiving. 2) the user replaces an empty git repo manually
  803. // and even more: the IsEmpty flag is deeply broken and should be removed with the UI changed to manage to cope with empty repos.
  804. // it's possible for a repository to be non-empty by that flag but still 500
  805. // because there are no branches - only tags -or the default branch is non-extant as it has been 0-pushed.
  806. ctx.Repo.Repository.IsEmpty = false
  807. if err = repo_model.UpdateRepositoryCols(ctx, ctx.Repo.Repository, "is_empty"); err != nil {
  808. ctx.ServerError("UpdateRepositoryCols", err)
  809. return
  810. }
  811. if err = repo_module.UpdateRepoSize(ctx, ctx.Repo.Repository); err != nil {
  812. ctx.ServerError("UpdateRepoSize", err)
  813. return
  814. }
  815. // the repo's IsEmpty has been updated, redirect to this page to make sure middlewares can get the correct values
  816. link := ctx.Link
  817. if ctx.Req.URL.RawQuery != "" {
  818. link += "?" + ctx.Req.URL.RawQuery
  819. }
  820. ctx.Redirect(link)
  821. return
  822. }
  823. title := ctx.Repo.Repository.Owner.Name + "/" + ctx.Repo.Repository.Name
  824. if len(ctx.Repo.Repository.Description) > 0 {
  825. title += ": " + ctx.Repo.Repository.Description
  826. }
  827. ctx.Data["Title"] = title
  828. branchLink := ctx.Repo.RepoLink + "/src/" + ctx.Repo.BranchNameSubURL()
  829. treeLink := branchLink
  830. rawLink := ctx.Repo.RepoLink + "/raw/" + ctx.Repo.BranchNameSubURL()
  831. if len(ctx.Repo.TreePath) > 0 {
  832. treeLink += "/" + util.PathEscapeSegments(ctx.Repo.TreePath)
  833. }
  834. // Get Topics of this repo
  835. renderRepoTopics(ctx)
  836. if ctx.Written() {
  837. return
  838. }
  839. // Get current entry user currently looking at.
  840. entry, err := ctx.Repo.Commit.GetTreeEntryByPath(ctx.Repo.TreePath)
  841. if err != nil {
  842. HandleGitError(ctx, "Repo.Commit.GetTreeEntryByPath", err)
  843. return
  844. }
  845. checkCitationFile(ctx, entry)
  846. if ctx.Written() {
  847. return
  848. }
  849. renderLanguageStats(ctx)
  850. if ctx.Written() {
  851. return
  852. }
  853. if entry.IsDir() {
  854. renderDirectory(ctx, treeLink)
  855. } else {
  856. renderFile(ctx, entry, treeLink, rawLink)
  857. }
  858. if ctx.Written() {
  859. return
  860. }
  861. if ctx.Doer != nil {
  862. if err := ctx.Repo.Repository.GetBaseRepo(ctx); err != nil {
  863. ctx.ServerError("GetBaseRepo", err)
  864. return
  865. }
  866. showRecentlyPushedNewBranches := true
  867. if ctx.Repo.Repository.IsMirror ||
  868. !ctx.Repo.Repository.UnitEnabled(ctx, unit_model.TypePullRequests) {
  869. showRecentlyPushedNewBranches = false
  870. }
  871. if showRecentlyPushedNewBranches {
  872. ctx.Data["RecentlyPushedNewBranches"], err = git_model.FindRecentlyPushedNewBranches(ctx, ctx.Repo.Repository.ID, ctx.Doer.ID, ctx.Repo.Repository.DefaultBranch)
  873. if err != nil {
  874. ctx.ServerError("GetRecentlyPushedBranches", err)
  875. return
  876. }
  877. }
  878. }
  879. var treeNames []string
  880. paths := make([]string, 0, 5)
  881. if len(ctx.Repo.TreePath) > 0 {
  882. treeNames = strings.Split(ctx.Repo.TreePath, "/")
  883. for i := range treeNames {
  884. paths = append(paths, strings.Join(treeNames[:i+1], "/"))
  885. }
  886. ctx.Data["HasParentPath"] = true
  887. if len(paths)-2 >= 0 {
  888. ctx.Data["ParentPath"] = "/" + paths[len(paths)-2]
  889. }
  890. }
  891. ctx.Data["Paths"] = paths
  892. ctx.Data["TreeLink"] = treeLink
  893. ctx.Data["TreeNames"] = treeNames
  894. ctx.Data["BranchLink"] = branchLink
  895. ctx.HTML(http.StatusOK, tplRepoHome)
  896. }
  897. // RenderUserCards render a page show users according the input template
  898. func RenderUserCards(ctx *context.Context, total int, getter func(opts db.ListOptions) ([]*user_model.User, error), tpl base.TplName) {
  899. page := ctx.FormInt("page")
  900. if page <= 0 {
  901. page = 1
  902. }
  903. pager := context.NewPagination(total, setting.ItemsPerPage, page, 5)
  904. ctx.Data["Page"] = pager
  905. items, err := getter(db.ListOptions{
  906. Page: pager.Paginater.Current(),
  907. PageSize: setting.ItemsPerPage,
  908. })
  909. if err != nil {
  910. ctx.ServerError("getter", err)
  911. return
  912. }
  913. ctx.Data["Cards"] = items
  914. ctx.HTML(http.StatusOK, tpl)
  915. }
  916. // Watchers render repository's watch users
  917. func Watchers(ctx *context.Context) {
  918. ctx.Data["Title"] = ctx.Tr("repo.watchers")
  919. ctx.Data["CardsTitle"] = ctx.Tr("repo.watchers")
  920. ctx.Data["PageIsWatchers"] = true
  921. RenderUserCards(ctx, ctx.Repo.Repository.NumWatches, func(opts db.ListOptions) ([]*user_model.User, error) {
  922. return repo_model.GetRepoWatchers(ctx, ctx.Repo.Repository.ID, opts)
  923. }, tplWatchers)
  924. }
  925. // Stars render repository's starred users
  926. func Stars(ctx *context.Context) {
  927. ctx.Data["Title"] = ctx.Tr("repo.stargazers")
  928. ctx.Data["CardsTitle"] = ctx.Tr("repo.stargazers")
  929. ctx.Data["PageIsStargazers"] = true
  930. RenderUserCards(ctx, ctx.Repo.Repository.NumStars, func(opts db.ListOptions) ([]*user_model.User, error) {
  931. return repo_model.GetStargazers(ctx, ctx.Repo.Repository, opts)
  932. }, tplWatchers)
  933. }
  934. // Forks render repository's forked users
  935. func Forks(ctx *context.Context) {
  936. ctx.Data["Title"] = ctx.Tr("repo.forks")
  937. page := ctx.FormInt("page")
  938. if page <= 0 {
  939. page = 1
  940. }
  941. pager := context.NewPagination(ctx.Repo.Repository.NumForks, setting.ItemsPerPage, page, 5)
  942. ctx.Data["Page"] = pager
  943. forks, err := repo_model.GetForks(ctx, ctx.Repo.Repository, db.ListOptions{
  944. Page: pager.Paginater.Current(),
  945. PageSize: setting.ItemsPerPage,
  946. })
  947. if err != nil {
  948. ctx.ServerError("GetForks", err)
  949. return
  950. }
  951. for _, fork := range forks {
  952. if err = fork.LoadOwner(ctx); err != nil {
  953. ctx.ServerError("LoadOwner", err)
  954. return
  955. }
  956. }
  957. ctx.Data["Forks"] = forks
  958. ctx.HTML(http.StatusOK, tplForks)
  959. }