Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104
  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) {
  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)
  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) {
  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), charset.ConvertOpts{})
  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. Links: markup.Links{
  274. Base: ctx.Repo.RepoLink,
  275. BranchPath: ctx.Repo.BranchNameSubURL(),
  276. TreePath: path.Join(ctx.Repo.TreePath, subfolder),
  277. },
  278. Metas: ctx.Repo.Repository.ComposeDocumentMetas(),
  279. GitRepo: ctx.Repo.GitRepo,
  280. }, rd)
  281. if err != nil {
  282. log.Error("Render failed for %s in %-v: %v Falling back to rendering source", readmeFile.Name(), ctx.Repo.Repository, err)
  283. delete(ctx.Data, "IsMarkup")
  284. }
  285. }
  286. if ctx.Data["IsMarkup"] != true {
  287. ctx.Data["IsPlainText"] = true
  288. content, err := io.ReadAll(rd)
  289. if err != nil {
  290. log.Error("Read readme content failed: %v", err)
  291. }
  292. contentEscaped := template.HTMLEscapeString(util.UnsafeBytesToString(content))
  293. ctx.Data["EscapeStatus"], ctx.Data["FileContent"] = charset.EscapeControlHTML(template.HTML(contentEscaped), ctx.Locale)
  294. }
  295. }
  296. func renderFile(ctx *context.Context, entry *git.TreeEntry) {
  297. ctx.Data["IsViewFile"] = true
  298. ctx.Data["HideRepoInfo"] = true
  299. blob := entry.Blob()
  300. buf, dataRc, fInfo, err := getFileReader(ctx, ctx.Repo.Repository.ID, blob)
  301. if err != nil {
  302. ctx.ServerError("getFileReader", err)
  303. return
  304. }
  305. defer dataRc.Close()
  306. ctx.Data["Title"] = ctx.Tr("repo.file.title", ctx.Repo.Repository.Name+"/"+path.Base(ctx.Repo.TreePath), ctx.Repo.RefName)
  307. ctx.Data["FileIsSymlink"] = entry.IsLink()
  308. ctx.Data["FileName"] = blob.Name()
  309. ctx.Data["RawFileLink"] = ctx.Repo.RepoLink + "/raw/" + ctx.Repo.BranchNameSubURL() + "/" + util.PathEscapeSegments(ctx.Repo.TreePath)
  310. if ctx.Repo.TreePath == ".editorconfig" {
  311. _, editorconfigWarning, editorconfigErr := ctx.Repo.GetEditorconfig(ctx.Repo.Commit)
  312. if editorconfigWarning != nil {
  313. ctx.Data["FileWarning"] = strings.TrimSpace(editorconfigWarning.Error())
  314. }
  315. if editorconfigErr != nil {
  316. ctx.Data["FileError"] = strings.TrimSpace(editorconfigErr.Error())
  317. }
  318. } else if issue_service.IsTemplateConfig(ctx.Repo.TreePath) {
  319. _, issueConfigErr := issue_service.GetTemplateConfig(ctx.Repo.GitRepo, ctx.Repo.TreePath, ctx.Repo.Commit)
  320. if issueConfigErr != nil {
  321. ctx.Data["FileError"] = strings.TrimSpace(issueConfigErr.Error())
  322. }
  323. } else if actions.IsWorkflow(ctx.Repo.TreePath) {
  324. content, err := actions.GetContentFromEntry(entry)
  325. if err != nil {
  326. log.Error("actions.GetContentFromEntry: %v", err)
  327. }
  328. _, workFlowErr := model.ReadWorkflow(bytes.NewReader(content))
  329. if workFlowErr != nil {
  330. ctx.Data["FileError"] = ctx.Locale.Tr("actions.runs.invalid_workflow_helper", workFlowErr.Error())
  331. }
  332. } else if slices.Contains([]string{"CODEOWNERS", "docs/CODEOWNERS", ".gitea/CODEOWNERS"}, ctx.Repo.TreePath) {
  333. if data, err := blob.GetBlobContent(setting.UI.MaxDisplayFileSize); err == nil {
  334. _, warnings := issue_model.GetCodeOwnersFromContent(ctx, data)
  335. if len(warnings) > 0 {
  336. ctx.Data["FileWarning"] = strings.Join(warnings, "\n")
  337. }
  338. }
  339. }
  340. isDisplayingSource := ctx.FormString("display") == "source"
  341. isDisplayingRendered := !isDisplayingSource
  342. if fInfo.isLFSFile {
  343. ctx.Data["RawFileLink"] = ctx.Repo.RepoLink + "/media/" + ctx.Repo.BranchNameSubURL() + "/" + util.PathEscapeSegments(ctx.Repo.TreePath)
  344. }
  345. isRepresentableAsText := fInfo.st.IsRepresentableAsText()
  346. if !isRepresentableAsText {
  347. // If we can't show plain text, always try to render.
  348. isDisplayingSource = false
  349. isDisplayingRendered = true
  350. }
  351. ctx.Data["IsLFSFile"] = fInfo.isLFSFile
  352. ctx.Data["FileSize"] = fInfo.fileSize
  353. ctx.Data["IsTextFile"] = fInfo.isTextFile
  354. ctx.Data["IsRepresentableAsText"] = isRepresentableAsText
  355. ctx.Data["IsDisplayingSource"] = isDisplayingSource
  356. ctx.Data["IsDisplayingRendered"] = isDisplayingRendered
  357. ctx.Data["IsExecutable"] = entry.IsExecutable()
  358. isTextSource := fInfo.isTextFile || isDisplayingSource
  359. ctx.Data["IsTextSource"] = isTextSource
  360. if isTextSource {
  361. ctx.Data["CanCopyContent"] = true
  362. }
  363. // Check LFS Lock
  364. lfsLock, err := git_model.GetTreePathLock(ctx, ctx.Repo.Repository.ID, ctx.Repo.TreePath)
  365. ctx.Data["LFSLock"] = lfsLock
  366. if err != nil {
  367. ctx.ServerError("GetTreePathLock", err)
  368. return
  369. }
  370. if lfsLock != nil {
  371. u, err := user_model.GetUserByID(ctx, lfsLock.OwnerID)
  372. if err != nil {
  373. ctx.ServerError("GetTreePathLock", err)
  374. return
  375. }
  376. ctx.Data["LFSLockOwner"] = u.Name
  377. ctx.Data["LFSLockOwnerHomeLink"] = u.HomeLink()
  378. ctx.Data["LFSLockHint"] = ctx.Tr("repo.editor.this_file_locked")
  379. }
  380. // Assume file is not editable first.
  381. if fInfo.isLFSFile {
  382. ctx.Data["EditFileTooltip"] = ctx.Tr("repo.editor.cannot_edit_lfs_files")
  383. } else if !isRepresentableAsText {
  384. ctx.Data["EditFileTooltip"] = ctx.Tr("repo.editor.cannot_edit_non_text_files")
  385. }
  386. switch {
  387. case isRepresentableAsText:
  388. if fInfo.st.IsSvgImage() {
  389. ctx.Data["IsImageFile"] = true
  390. ctx.Data["CanCopyContent"] = true
  391. ctx.Data["HasSourceRenderedToggle"] = true
  392. }
  393. if fInfo.fileSize >= setting.UI.MaxDisplayFileSize {
  394. ctx.Data["IsFileTooLarge"] = true
  395. break
  396. }
  397. rd := charset.ToUTF8WithFallbackReader(io.MultiReader(bytes.NewReader(buf), dataRc), charset.ConvertOpts{})
  398. shouldRenderSource := ctx.FormString("display") == "source"
  399. readmeExist := util.IsReadmeFileName(blob.Name())
  400. ctx.Data["ReadmeExist"] = readmeExist
  401. markupType := markup.Type(blob.Name())
  402. // If the markup is detected by custom markup renderer it should not be reset later on
  403. // to not pass it down to the render context.
  404. detected := false
  405. if markupType == "" {
  406. detected = true
  407. markupType = markup.DetectRendererType(blob.Name(), bytes.NewReader(buf))
  408. }
  409. if markupType != "" {
  410. ctx.Data["HasSourceRenderedToggle"] = true
  411. }
  412. if markupType != "" && !shouldRenderSource {
  413. ctx.Data["IsMarkup"] = true
  414. ctx.Data["MarkupType"] = markupType
  415. if !detected {
  416. markupType = ""
  417. }
  418. metas := ctx.Repo.Repository.ComposeDocumentMetas()
  419. metas["BranchNameSubURL"] = ctx.Repo.BranchNameSubURL()
  420. ctx.Data["EscapeStatus"], ctx.Data["FileContent"], err = markupRender(ctx, &markup.RenderContext{
  421. Ctx: ctx,
  422. Type: markupType,
  423. RelativePath: ctx.Repo.TreePath,
  424. Links: markup.Links{
  425. Base: ctx.Repo.RepoLink,
  426. BranchPath: ctx.Repo.BranchNameSubURL(),
  427. TreePath: path.Dir(ctx.Repo.TreePath),
  428. },
  429. Metas: metas,
  430. GitRepo: ctx.Repo.GitRepo,
  431. }, rd)
  432. if err != nil {
  433. ctx.ServerError("Render", err)
  434. return
  435. }
  436. // to prevent iframe load third-party url
  437. ctx.Resp.Header().Add("Content-Security-Policy", "frame-src 'self'")
  438. } else {
  439. buf, _ := io.ReadAll(rd)
  440. // empty: 0 lines; "a": one line; "a\n": two lines; "a\nb": two lines;
  441. // the NumLines is only used for the display on the UI: "xxx lines"
  442. if len(buf) == 0 {
  443. ctx.Data["NumLines"] = 0
  444. } else {
  445. ctx.Data["NumLines"] = bytes.Count(buf, []byte{'\n'}) + 1
  446. }
  447. ctx.Data["NumLinesSet"] = true
  448. language := ""
  449. indexFilename, worktree, deleteTemporaryFile, err := ctx.Repo.GitRepo.ReadTreeToTemporaryIndex(ctx.Repo.CommitID)
  450. if err == nil {
  451. defer deleteTemporaryFile()
  452. filename2attribute2info, err := ctx.Repo.GitRepo.CheckAttribute(git.CheckAttributeOpts{
  453. CachedOnly: true,
  454. Attributes: []string{"linguist-language", "gitlab-language"},
  455. Filenames: []string{ctx.Repo.TreePath},
  456. IndexFile: indexFilename,
  457. WorkTree: worktree,
  458. })
  459. if err != nil {
  460. log.Error("Unable to load attributes for %-v:%s. Error: %v", ctx.Repo.Repository, ctx.Repo.TreePath, err)
  461. }
  462. language = filename2attribute2info[ctx.Repo.TreePath]["linguist-language"]
  463. if language == "" || language == "unspecified" {
  464. language = filename2attribute2info[ctx.Repo.TreePath]["gitlab-language"]
  465. }
  466. if language == "unspecified" {
  467. language = ""
  468. }
  469. }
  470. fileContent, lexerName, err := highlight.File(blob.Name(), language, buf)
  471. ctx.Data["LexerName"] = lexerName
  472. if err != nil {
  473. log.Error("highlight.File failed, fallback to plain text: %v", err)
  474. fileContent = highlight.PlainText(buf)
  475. }
  476. status := &charset.EscapeStatus{}
  477. statuses := make([]*charset.EscapeStatus, len(fileContent))
  478. for i, line := range fileContent {
  479. statuses[i], fileContent[i] = charset.EscapeControlHTML(line, ctx.Locale)
  480. status = status.Or(statuses[i])
  481. }
  482. ctx.Data["EscapeStatus"] = status
  483. ctx.Data["FileContent"] = fileContent
  484. ctx.Data["LineEscapeStatus"] = statuses
  485. }
  486. if !fInfo.isLFSFile {
  487. if ctx.Repo.CanEnableEditor(ctx, ctx.Doer) {
  488. if lfsLock != nil && lfsLock.OwnerID != ctx.Doer.ID {
  489. ctx.Data["CanEditFile"] = false
  490. ctx.Data["EditFileTooltip"] = ctx.Tr("repo.editor.this_file_locked")
  491. } else {
  492. ctx.Data["CanEditFile"] = true
  493. ctx.Data["EditFileTooltip"] = ctx.Tr("repo.editor.edit_this_file")
  494. }
  495. } else if !ctx.Repo.IsViewBranch {
  496. ctx.Data["EditFileTooltip"] = ctx.Tr("repo.editor.must_be_on_a_branch")
  497. } else if !ctx.Repo.CanWriteToBranch(ctx, ctx.Doer, ctx.Repo.BranchName) {
  498. ctx.Data["EditFileTooltip"] = ctx.Tr("repo.editor.fork_before_edit")
  499. }
  500. }
  501. case fInfo.st.IsPDF():
  502. ctx.Data["IsPDFFile"] = true
  503. case fInfo.st.IsVideo():
  504. ctx.Data["IsVideoFile"] = true
  505. case fInfo.st.IsAudio():
  506. ctx.Data["IsAudioFile"] = true
  507. case fInfo.st.IsImage() && (setting.UI.SVG.Enabled || !fInfo.st.IsSvgImage()):
  508. ctx.Data["IsImageFile"] = true
  509. ctx.Data["CanCopyContent"] = true
  510. default:
  511. if fInfo.fileSize >= setting.UI.MaxDisplayFileSize {
  512. ctx.Data["IsFileTooLarge"] = true
  513. break
  514. }
  515. if markupType := markup.Type(blob.Name()); markupType != "" {
  516. rd := io.MultiReader(bytes.NewReader(buf), dataRc)
  517. ctx.Data["IsMarkup"] = true
  518. ctx.Data["MarkupType"] = markupType
  519. ctx.Data["EscapeStatus"], ctx.Data["FileContent"], err = markupRender(ctx, &markup.RenderContext{
  520. Ctx: ctx,
  521. RelativePath: ctx.Repo.TreePath,
  522. Links: markup.Links{
  523. Base: ctx.Repo.RepoLink,
  524. BranchPath: ctx.Repo.BranchNameSubURL(),
  525. TreePath: path.Dir(ctx.Repo.TreePath),
  526. },
  527. Metas: ctx.Repo.Repository.ComposeDocumentMetas(),
  528. GitRepo: ctx.Repo.GitRepo,
  529. }, rd)
  530. if err != nil {
  531. ctx.ServerError("Render", err)
  532. return
  533. }
  534. }
  535. }
  536. if fInfo.st.IsImage() && !fInfo.st.IsSvgImage() {
  537. img, _, err := image.DecodeConfig(bytes.NewReader(buf))
  538. if err == nil {
  539. // There are Image formats go can't decode
  540. // Instead of throwing an error in that case, we show the size only when we can decode
  541. ctx.Data["ImageSize"] = fmt.Sprintf("%dx%dpx", img.Width, img.Height)
  542. }
  543. }
  544. if ctx.Repo.CanEnableEditor(ctx, ctx.Doer) {
  545. if lfsLock != nil && lfsLock.OwnerID != ctx.Doer.ID {
  546. ctx.Data["CanDeleteFile"] = false
  547. ctx.Data["DeleteFileTooltip"] = ctx.Tr("repo.editor.this_file_locked")
  548. } else {
  549. ctx.Data["CanDeleteFile"] = true
  550. ctx.Data["DeleteFileTooltip"] = ctx.Tr("repo.editor.delete_this_file")
  551. }
  552. } else if !ctx.Repo.IsViewBranch {
  553. ctx.Data["DeleteFileTooltip"] = ctx.Tr("repo.editor.must_be_on_a_branch")
  554. } else if !ctx.Repo.CanWriteToBranch(ctx, ctx.Doer, ctx.Repo.BranchName) {
  555. ctx.Data["DeleteFileTooltip"] = ctx.Tr("repo.editor.must_have_write_access")
  556. }
  557. }
  558. func markupRender(ctx *context.Context, renderCtx *markup.RenderContext, input io.Reader) (escaped *charset.EscapeStatus, output template.HTML, err error) {
  559. markupRd, markupWr := io.Pipe()
  560. defer markupWr.Close()
  561. done := make(chan struct{})
  562. go func() {
  563. sb := &strings.Builder{}
  564. // We allow NBSP here this is rendered
  565. escaped, _ = charset.EscapeControlReader(markupRd, sb, ctx.Locale, charset.RuneNBSP)
  566. output = template.HTML(sb.String())
  567. close(done)
  568. }()
  569. err = markup.Render(renderCtx, input, markupWr)
  570. _ = markupWr.CloseWithError(err)
  571. <-done
  572. return escaped, output, err
  573. }
  574. func checkHomeCodeViewable(ctx *context.Context) {
  575. if len(ctx.Repo.Units) > 0 {
  576. if ctx.Repo.Repository.IsBeingCreated() {
  577. task, err := admin_model.GetMigratingTask(ctx, ctx.Repo.Repository.ID)
  578. if err != nil {
  579. if admin_model.IsErrTaskDoesNotExist(err) {
  580. ctx.Data["Repo"] = ctx.Repo
  581. ctx.Data["CloneAddr"] = ""
  582. ctx.Data["Failed"] = true
  583. ctx.HTML(http.StatusOK, tplMigrating)
  584. return
  585. }
  586. ctx.ServerError("models.GetMigratingTask", err)
  587. return
  588. }
  589. cfg, err := task.MigrateConfig()
  590. if err != nil {
  591. ctx.ServerError("task.MigrateConfig", err)
  592. return
  593. }
  594. ctx.Data["Repo"] = ctx.Repo
  595. ctx.Data["MigrateTask"] = task
  596. ctx.Data["CloneAddr"], _ = util.SanitizeURL(cfg.CloneAddr)
  597. ctx.Data["Failed"] = task.Status == structs.TaskStatusFailed
  598. ctx.HTML(http.StatusOK, tplMigrating)
  599. return
  600. }
  601. if ctx.IsSigned {
  602. // Set repo notification-status read if unread
  603. if err := activities_model.SetRepoReadBy(ctx, ctx.Repo.Repository.ID, ctx.Doer.ID); err != nil {
  604. ctx.ServerError("ReadBy", err)
  605. return
  606. }
  607. }
  608. var firstUnit *unit_model.Unit
  609. for _, repoUnit := range ctx.Repo.Units {
  610. if repoUnit.Type == unit_model.TypeCode {
  611. return
  612. }
  613. unit, ok := unit_model.Units[repoUnit.Type]
  614. if ok && (firstUnit == nil || !firstUnit.IsLessThan(unit)) {
  615. firstUnit = &unit
  616. }
  617. }
  618. if firstUnit != nil {
  619. ctx.Redirect(fmt.Sprintf("%s%s", ctx.Repo.Repository.Link(), firstUnit.URI))
  620. return
  621. }
  622. }
  623. ctx.NotFound("Home", fmt.Errorf(ctx.Tr("units.error.no_unit_allowed_repo")))
  624. }
  625. func checkCitationFile(ctx *context.Context, entry *git.TreeEntry) {
  626. if entry.Name() != "" {
  627. return
  628. }
  629. tree, err := ctx.Repo.Commit.SubTree(ctx.Repo.TreePath)
  630. if err != nil {
  631. HandleGitError(ctx, "Repo.Commit.SubTree", err)
  632. return
  633. }
  634. allEntries, err := tree.ListEntries()
  635. if err != nil {
  636. ctx.ServerError("ListEntries", err)
  637. return
  638. }
  639. for _, entry := range allEntries {
  640. if entry.Name() == "CITATION.cff" || entry.Name() == "CITATION.bib" {
  641. // Read Citation file contents
  642. if content, err := entry.Blob().GetBlobContent(setting.UI.MaxDisplayFileSize); err != nil {
  643. log.Error("checkCitationFile: GetBlobContent: %v", err)
  644. } else {
  645. ctx.Data["CitiationExist"] = true
  646. ctx.PageData["citationFileContent"] = content
  647. break
  648. }
  649. }
  650. }
  651. }
  652. // Home render repository home page
  653. func Home(ctx *context.Context) {
  654. if setting.Other.EnableFeed {
  655. isFeed, _, showFeedType := feed.GetFeedType(ctx.Params(":reponame"), ctx.Req)
  656. if isFeed {
  657. switch {
  658. case ctx.Link == fmt.Sprintf("%s.%s", ctx.Repo.RepoLink, showFeedType):
  659. feed.ShowRepoFeed(ctx, ctx.Repo.Repository, showFeedType)
  660. case ctx.Repo.TreePath == "":
  661. feed.ShowBranchFeed(ctx, ctx.Repo.Repository, showFeedType)
  662. case ctx.Repo.TreePath != "":
  663. feed.ShowFileFeed(ctx, ctx.Repo.Repository, showFeedType)
  664. }
  665. return
  666. }
  667. }
  668. checkHomeCodeViewable(ctx)
  669. if ctx.Written() {
  670. return
  671. }
  672. renderCode(ctx)
  673. }
  674. // LastCommit returns lastCommit data for the provided branch/tag/commit and directory (in url) and filenames in body
  675. func LastCommit(ctx *context.Context) {
  676. checkHomeCodeViewable(ctx)
  677. if ctx.Written() {
  678. return
  679. }
  680. renderDirectoryFiles(ctx, 0)
  681. if ctx.Written() {
  682. return
  683. }
  684. var treeNames []string
  685. paths := make([]string, 0, 5)
  686. if len(ctx.Repo.TreePath) > 0 {
  687. treeNames = strings.Split(ctx.Repo.TreePath, "/")
  688. for i := range treeNames {
  689. paths = append(paths, strings.Join(treeNames[:i+1], "/"))
  690. }
  691. ctx.Data["HasParentPath"] = true
  692. if len(paths)-2 >= 0 {
  693. ctx.Data["ParentPath"] = "/" + paths[len(paths)-2]
  694. }
  695. }
  696. branchLink := ctx.Repo.RepoLink + "/src/" + ctx.Repo.BranchNameSubURL()
  697. ctx.Data["BranchLink"] = branchLink
  698. ctx.HTML(http.StatusOK, tplRepoViewList)
  699. }
  700. func renderDirectoryFiles(ctx *context.Context, timeout time.Duration) git.Entries {
  701. tree, err := ctx.Repo.Commit.SubTree(ctx.Repo.TreePath)
  702. if err != nil {
  703. HandleGitError(ctx, "Repo.Commit.SubTree", err)
  704. return nil
  705. }
  706. ctx.Data["LastCommitLoaderURL"] = ctx.Repo.RepoLink + "/lastcommit/" + url.PathEscape(ctx.Repo.CommitID) + "/" + util.PathEscapeSegments(ctx.Repo.TreePath)
  707. // Get current entry user currently looking at.
  708. entry, err := ctx.Repo.Commit.GetTreeEntryByPath(ctx.Repo.TreePath)
  709. if err != nil {
  710. HandleGitError(ctx, "Repo.Commit.GetTreeEntryByPath", err)
  711. return nil
  712. }
  713. if !entry.IsDir() {
  714. HandleGitError(ctx, "Repo.Commit.GetTreeEntryByPath", err)
  715. return nil
  716. }
  717. allEntries, err := tree.ListEntries()
  718. if err != nil {
  719. ctx.ServerError("ListEntries", err)
  720. return nil
  721. }
  722. allEntries.CustomSort(base.NaturalSortLess)
  723. commitInfoCtx := gocontext.Context(ctx)
  724. if timeout > 0 {
  725. var cancel gocontext.CancelFunc
  726. commitInfoCtx, cancel = gocontext.WithTimeout(ctx, timeout)
  727. defer cancel()
  728. }
  729. selected := make(container.Set[string])
  730. selected.AddMultiple(ctx.FormStrings("f[]")...)
  731. entries := allEntries
  732. if len(selected) > 0 {
  733. entries = make(git.Entries, 0, len(selected))
  734. for _, entry := range allEntries {
  735. if selected.Contains(entry.Name()) {
  736. entries = append(entries, entry)
  737. }
  738. }
  739. }
  740. var latestCommit *git.Commit
  741. ctx.Data["Files"], latestCommit, err = entries.GetCommitsInfo(commitInfoCtx, ctx.Repo.Commit, ctx.Repo.TreePath)
  742. if err != nil {
  743. ctx.ServerError("GetCommitsInfo", err)
  744. return nil
  745. }
  746. // Show latest commit info of repository in table header,
  747. // or of directory if not in root directory.
  748. ctx.Data["LatestCommit"] = latestCommit
  749. if latestCommit != nil {
  750. verification := asymkey_model.ParseCommitWithSignature(ctx, latestCommit)
  751. if err := asymkey_model.CalculateTrustStatus(verification, ctx.Repo.Repository.GetTrustModel(), func(user *user_model.User) (bool, error) {
  752. return repo_model.IsOwnerMemberCollaborator(ctx, ctx.Repo.Repository, user.ID)
  753. }, nil); err != nil {
  754. ctx.ServerError("CalculateTrustStatus", err)
  755. return nil
  756. }
  757. ctx.Data["LatestCommitVerification"] = verification
  758. ctx.Data["LatestCommitUser"] = user_model.ValidateCommitWithEmail(ctx, latestCommit)
  759. statuses, _, err := git_model.GetLatestCommitStatus(ctx, ctx.Repo.Repository.ID, latestCommit.ID.String(), db.ListOptions{ListAll: true})
  760. if err != nil {
  761. log.Error("GetLatestCommitStatus: %v", err)
  762. }
  763. ctx.Data["LatestCommitStatus"] = git_model.CalcCommitStatus(statuses)
  764. ctx.Data["LatestCommitStatuses"] = statuses
  765. }
  766. branchLink := ctx.Repo.RepoLink + "/src/" + ctx.Repo.BranchNameSubURL()
  767. treeLink := branchLink
  768. if len(ctx.Repo.TreePath) > 0 {
  769. treeLink += "/" + util.PathEscapeSegments(ctx.Repo.TreePath)
  770. }
  771. ctx.Data["TreeLink"] = treeLink
  772. ctx.Data["SSHDomain"] = setting.SSH.Domain
  773. return allEntries
  774. }
  775. func renderLanguageStats(ctx *context.Context) {
  776. langs, err := repo_model.GetTopLanguageStats(ctx.Repo.Repository, 5)
  777. if err != nil {
  778. ctx.ServerError("Repo.GetTopLanguageStats", err)
  779. return
  780. }
  781. ctx.Data["LanguageStats"] = langs
  782. }
  783. func renderRepoTopics(ctx *context.Context) {
  784. topics, _, err := repo_model.FindTopics(ctx, &repo_model.FindTopicOptions{
  785. RepoID: ctx.Repo.Repository.ID,
  786. })
  787. if err != nil {
  788. ctx.ServerError("models.FindTopics", err)
  789. return
  790. }
  791. ctx.Data["Topics"] = topics
  792. }
  793. func renderCode(ctx *context.Context) {
  794. ctx.Data["PageIsViewCode"] = true
  795. ctx.Data["RepositoryUploadEnabled"] = setting.Repository.Upload.Enabled
  796. if ctx.Repo.Commit == nil || ctx.Repo.Repository.IsEmpty || ctx.Repo.Repository.IsBroken() {
  797. showEmpty := true
  798. var err error
  799. if ctx.Repo.GitRepo != nil {
  800. showEmpty, err = ctx.Repo.GitRepo.IsEmpty()
  801. if err != nil {
  802. log.Error("GitRepo.IsEmpty: %v", err)
  803. ctx.Repo.Repository.Status = repo_model.RepositoryBroken
  804. showEmpty = true
  805. ctx.Flash.Error(ctx.Tr("error.occurred"), true)
  806. }
  807. }
  808. if showEmpty {
  809. ctx.HTML(http.StatusOK, tplRepoEMPTY)
  810. return
  811. }
  812. // the repo is not really empty, so we should update the modal in database
  813. // such problem may be caused by:
  814. // 1) an error occurs during pushing/receiving. 2) the user replaces an empty git repo manually
  815. // and even more: the IsEmpty flag is deeply broken and should be removed with the UI changed to manage to cope with empty repos.
  816. // it's possible for a repository to be non-empty by that flag but still 500
  817. // because there are no branches - only tags -or the default branch is non-extant as it has been 0-pushed.
  818. ctx.Repo.Repository.IsEmpty = false
  819. if err = repo_model.UpdateRepositoryCols(ctx, ctx.Repo.Repository, "is_empty"); err != nil {
  820. ctx.ServerError("UpdateRepositoryCols", err)
  821. return
  822. }
  823. if err = repo_module.UpdateRepoSize(ctx, ctx.Repo.Repository); err != nil {
  824. ctx.ServerError("UpdateRepoSize", err)
  825. return
  826. }
  827. // the repo's IsEmpty has been updated, redirect to this page to make sure middlewares can get the correct values
  828. link := ctx.Link
  829. if ctx.Req.URL.RawQuery != "" {
  830. link += "?" + ctx.Req.URL.RawQuery
  831. }
  832. ctx.Redirect(link)
  833. return
  834. }
  835. title := ctx.Repo.Repository.Owner.Name + "/" + ctx.Repo.Repository.Name
  836. if len(ctx.Repo.Repository.Description) > 0 {
  837. title += ": " + ctx.Repo.Repository.Description
  838. }
  839. ctx.Data["Title"] = title
  840. // Get Topics of this repo
  841. renderRepoTopics(ctx)
  842. if ctx.Written() {
  843. return
  844. }
  845. // Get current entry user currently looking at.
  846. entry, err := ctx.Repo.Commit.GetTreeEntryByPath(ctx.Repo.TreePath)
  847. if err != nil {
  848. HandleGitError(ctx, "Repo.Commit.GetTreeEntryByPath", err)
  849. return
  850. }
  851. checkCitationFile(ctx, entry)
  852. if ctx.Written() {
  853. return
  854. }
  855. renderLanguageStats(ctx)
  856. if ctx.Written() {
  857. return
  858. }
  859. if entry.IsDir() {
  860. renderDirectory(ctx)
  861. } else {
  862. renderFile(ctx, entry)
  863. }
  864. if ctx.Written() {
  865. return
  866. }
  867. if ctx.Doer != nil {
  868. if err := ctx.Repo.Repository.GetBaseRepo(ctx); err != nil {
  869. ctx.ServerError("GetBaseRepo", err)
  870. return
  871. }
  872. showRecentlyPushedNewBranches := true
  873. if ctx.Repo.Repository.IsMirror ||
  874. !ctx.Repo.Repository.UnitEnabled(ctx, unit_model.TypePullRequests) {
  875. showRecentlyPushedNewBranches = false
  876. }
  877. if showRecentlyPushedNewBranches {
  878. ctx.Data["RecentlyPushedNewBranches"], err = git_model.FindRecentlyPushedNewBranches(ctx, ctx.Repo.Repository.ID, ctx.Doer.ID, ctx.Repo.Repository.DefaultBranch)
  879. if err != nil {
  880. ctx.ServerError("GetRecentlyPushedBranches", err)
  881. return
  882. }
  883. }
  884. }
  885. var treeNames []string
  886. paths := make([]string, 0, 5)
  887. if len(ctx.Repo.TreePath) > 0 {
  888. treeNames = strings.Split(ctx.Repo.TreePath, "/")
  889. for i := range treeNames {
  890. paths = append(paths, strings.Join(treeNames[:i+1], "/"))
  891. }
  892. ctx.Data["HasParentPath"] = true
  893. if len(paths)-2 >= 0 {
  894. ctx.Data["ParentPath"] = "/" + paths[len(paths)-2]
  895. }
  896. }
  897. ctx.Data["Paths"] = paths
  898. branchLink := ctx.Repo.RepoLink + "/src/" + ctx.Repo.BranchNameSubURL()
  899. treeLink := branchLink
  900. if len(ctx.Repo.TreePath) > 0 {
  901. treeLink += "/" + util.PathEscapeSegments(ctx.Repo.TreePath)
  902. }
  903. ctx.Data["TreeLink"] = treeLink
  904. ctx.Data["TreeNames"] = treeNames
  905. ctx.Data["BranchLink"] = branchLink
  906. ctx.HTML(http.StatusOK, tplRepoHome)
  907. }
  908. // RenderUserCards render a page show users according the input template
  909. func RenderUserCards(ctx *context.Context, total int, getter func(opts db.ListOptions) ([]*user_model.User, error), tpl base.TplName) {
  910. page := ctx.FormInt("page")
  911. if page <= 0 {
  912. page = 1
  913. }
  914. pager := context.NewPagination(total, setting.ItemsPerPage, page, 5)
  915. ctx.Data["Page"] = pager
  916. items, err := getter(db.ListOptions{
  917. Page: pager.Paginater.Current(),
  918. PageSize: setting.ItemsPerPage,
  919. })
  920. if err != nil {
  921. ctx.ServerError("getter", err)
  922. return
  923. }
  924. ctx.Data["Cards"] = items
  925. ctx.HTML(http.StatusOK, tpl)
  926. }
  927. // Watchers render repository's watch users
  928. func Watchers(ctx *context.Context) {
  929. ctx.Data["Title"] = ctx.Tr("repo.watchers")
  930. ctx.Data["CardsTitle"] = ctx.Tr("repo.watchers")
  931. ctx.Data["PageIsWatchers"] = true
  932. RenderUserCards(ctx, ctx.Repo.Repository.NumWatches, func(opts db.ListOptions) ([]*user_model.User, error) {
  933. return repo_model.GetRepoWatchers(ctx, ctx.Repo.Repository.ID, opts)
  934. }, tplWatchers)
  935. }
  936. // Stars render repository's starred users
  937. func Stars(ctx *context.Context) {
  938. ctx.Data["Title"] = ctx.Tr("repo.stargazers")
  939. ctx.Data["CardsTitle"] = ctx.Tr("repo.stargazers")
  940. ctx.Data["PageIsStargazers"] = true
  941. RenderUserCards(ctx, ctx.Repo.Repository.NumStars, func(opts db.ListOptions) ([]*user_model.User, error) {
  942. return repo_model.GetStargazers(ctx, ctx.Repo.Repository, opts)
  943. }, tplWatchers)
  944. }
  945. // Forks render repository's forked users
  946. func Forks(ctx *context.Context) {
  947. ctx.Data["Title"] = ctx.Tr("repo.forks")
  948. page := ctx.FormInt("page")
  949. if page <= 0 {
  950. page = 1
  951. }
  952. pager := context.NewPagination(ctx.Repo.Repository.NumForks, setting.ItemsPerPage, page, 5)
  953. ctx.Data["Page"] = pager
  954. forks, err := repo_model.GetForks(ctx, ctx.Repo.Repository, db.ListOptions{
  955. Page: pager.Paginater.Current(),
  956. PageSize: setting.ItemsPerPage,
  957. })
  958. if err != nil {
  959. ctx.ServerError("GetForks", err)
  960. return
  961. }
  962. for _, fork := range forks {
  963. if err = fork.LoadOwner(ctx); err != nil {
  964. ctx.ServerError("LoadOwner", err)
  965. return
  966. }
  967. }
  968. ctx.Data["Forks"] = forks
  969. ctx.HTML(http.StatusOK, tplForks)
  970. }