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

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