You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

view.go 14 kB

Git LFS support v2 (#122) * Import github.com/git-lfs/lfs-test-server as lfs module base Imported commit is 3968aac269a77b73924649b9412ae03f7ccd3198 Removed: Dockerfile CONTRIBUTING.md mgmt* script/ vendor/ kvlogger.go .dockerignore .gitignore README.md * Remove config, add JWT support from github.com/mgit-at/lfs-test-server Imported commit f0cdcc5a01599c5a955dc1bbf683bb4acecdba83 * Add LFS settings * Add LFS meta object model * Add LFS routes and initialization * Import github.com/dgrijalva/jwt-go into vendor/ * Adapt LFS module: handlers, routing, meta store * Move LFS routes to /user/repo/info/lfs/* * Add request header checks to LFS BatchHandler / PostHandler * Implement LFS basic authentication * Rework JWT secret generation / load * Implement LFS SSH token authentication with JWT Specification: https://github.com/github/git-lfs/tree/master/docs/api * Integrate LFS settings into install process * Remove LFS objects when repository is deleted Only removes objects from content store when deleted repo is the only referencing repository * Make LFS module stateless Fixes bug where LFS would not work after installation without restarting Gitea * Change 500 'Internal Server Error' to 400 'Bad Request' * Change sql query to xorm call * Remove unneeded type from LFS module * Change internal imports to code.gitea.io/gitea/ * Add Gitea authors copyright * Change basic auth realm to "gitea-lfs" * Add unique indexes to LFS model * Use xorm count function in LFS check on repository delete * Return io.ReadCloser from content store and close after usage * Add LFS info to runWeb() * Export LFS content store base path * LFS file download from UI * Work around git-lfs client issue with unauthenticated requests Returning a dummy Authorization header for unauthenticated requests lets git-lfs client skip asking for auth credentials See: https://github.com/github/git-lfs/issues/1088 * Fix unauthenticated UI downloads from public repositories * Authentication check order, Finish LFS file view logic * Ignore LFS hooks if installed for current OS user Fixes Gitea UI actions for repositories tracking LFS files. Checks for minimum needed git version by parsing the semantic version string. * Hide LFS metafile diff from commit view, marking as binary * Show LFS notice if file in commit view is tracked * Add notbefore/nbf JWT claim * Correct lint suggestions - comments for structs and functions - Add comments to LFS model - Function comment for GetRandomBytesAsBase64 - LFS server function comments and lint variable suggestion * Move secret generation code out of conditional Ensures no LFS code may run with an empty secret * Do not hand out JWT tokens if LFS server support is disabled
8 years ago
Improve listing performance by using go-git (#6478) * Use go-git for tree reading and commit info lookup. Signed-off-by: Filip Navara <navara@emclient.com> * Use TreeEntry.IsRegular() instead of ObjectType that was removed. Signed-off-by: Filip Navara <navara@emclient.com> * Use the treePath to optimize commit info search. Signed-off-by: Filip Navara <navara@emclient.com> * Extract the latest commit at treePath along with the other commits. Signed-off-by: Filip Navara <navara@emclient.com> * Fix listing commit info for a directory that was created in one commit and never modified after. Signed-off-by: Filip Navara <navara@emclient.com> * Avoid nearly all external 'git' invocations when doing directory listing (.editorconfig code path is still hit). Signed-off-by: Filip Navara <navara@emclient.com> * Use go-git for reading blobs. Signed-off-by: Filip Navara <navara@emclient.com> * Make SHA1 type alias for plumbing.Hash in go-git. Signed-off-by: Filip Navara <navara@emclient.com> * Make Signature type alias for object.Signature in go-git. Signed-off-by: Filip Navara <navara@emclient.com> * Fix GetCommitsInfo for repository with only one commit. Signed-off-by: Filip Navara <navara@emclient.com> * Fix PGP signature verification. Signed-off-by: Filip Navara <navara@emclient.com> * Fix issues with walking commit graph across merges. Signed-off-by: Filip Navara <navara@emclient.com> * Fix typo in condition. Signed-off-by: Filip Navara <navara@emclient.com> * Speed up loading branch list by keeping the repository reference (and thus all the loaded packfile indexes). Signed-off-by: Filip Navara <navara@emclient.com> * Fix lising submodules. Signed-off-by: Filip Navara <navara@emclient.com> * Fix build Signed-off-by: Filip Navara <navara@emclient.com> * Add back commit cache because of name-rev Signed-off-by: Filip Navara <navara@emclient.com> * Fix tests Signed-off-by: Filip Navara <navara@emclient.com> * Fix code style * Fix spelling * Address PR feedback Signed-off-by: Filip Navara <navara@emclient.com> * Update vendor module list Signed-off-by: Filip Navara <navara@emclient.com> * Fix getting trees by commit id Signed-off-by: Filip Navara <navara@emclient.com> * Fix remaining unit test failures * Fix GetTreeBySHA * Avoid running `git name-rev` if not necessary Signed-off-by: Filip Navara <navara@emclient.com> * Move Branch code to git module * Clean up GPG signature verification and fix it for tagged commits * Address PR feedback (import formatting, copyright headers) * Make blob lookup by SHA working * Update tests to use public API * Allow getting content from any type of object through the blob interface * Change test to actually expect the object content that is in the GIT repository * Change one more test to actually expect the object content that is in the GIT repository * Add comments
6 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
10 years ago
Git LFS support v2 (#122) * Import github.com/git-lfs/lfs-test-server as lfs module base Imported commit is 3968aac269a77b73924649b9412ae03f7ccd3198 Removed: Dockerfile CONTRIBUTING.md mgmt* script/ vendor/ kvlogger.go .dockerignore .gitignore README.md * Remove config, add JWT support from github.com/mgit-at/lfs-test-server Imported commit f0cdcc5a01599c5a955dc1bbf683bb4acecdba83 * Add LFS settings * Add LFS meta object model * Add LFS routes and initialization * Import github.com/dgrijalva/jwt-go into vendor/ * Adapt LFS module: handlers, routing, meta store * Move LFS routes to /user/repo/info/lfs/* * Add request header checks to LFS BatchHandler / PostHandler * Implement LFS basic authentication * Rework JWT secret generation / load * Implement LFS SSH token authentication with JWT Specification: https://github.com/github/git-lfs/tree/master/docs/api * Integrate LFS settings into install process * Remove LFS objects when repository is deleted Only removes objects from content store when deleted repo is the only referencing repository * Make LFS module stateless Fixes bug where LFS would not work after installation without restarting Gitea * Change 500 'Internal Server Error' to 400 'Bad Request' * Change sql query to xorm call * Remove unneeded type from LFS module * Change internal imports to code.gitea.io/gitea/ * Add Gitea authors copyright * Change basic auth realm to "gitea-lfs" * Add unique indexes to LFS model * Use xorm count function in LFS check on repository delete * Return io.ReadCloser from content store and close after usage * Add LFS info to runWeb() * Export LFS content store base path * LFS file download from UI * Work around git-lfs client issue with unauthenticated requests Returning a dummy Authorization header for unauthenticated requests lets git-lfs client skip asking for auth credentials See: https://github.com/github/git-lfs/issues/1088 * Fix unauthenticated UI downloads from public repositories * Authentication check order, Finish LFS file view logic * Ignore LFS hooks if installed for current OS user Fixes Gitea UI actions for repositories tracking LFS files. Checks for minimum needed git version by parsing the semantic version string. * Hide LFS metafile diff from commit view, marking as binary * Show LFS notice if file in commit view is tracked * Add notbefore/nbf JWT claim * Correct lint suggestions - comments for structs and functions - Add comments to LFS model - Function comment for GetRandomBytesAsBase64 - LFS server function comments and lint variable suggestion * Move secret generation code out of conditional Ensures no LFS code may run with an empty secret * Do not hand out JWT tokens if LFS server support is disabled
8 years ago
Git LFS support v2 (#122) * Import github.com/git-lfs/lfs-test-server as lfs module base Imported commit is 3968aac269a77b73924649b9412ae03f7ccd3198 Removed: Dockerfile CONTRIBUTING.md mgmt* script/ vendor/ kvlogger.go .dockerignore .gitignore README.md * Remove config, add JWT support from github.com/mgit-at/lfs-test-server Imported commit f0cdcc5a01599c5a955dc1bbf683bb4acecdba83 * Add LFS settings * Add LFS meta object model * Add LFS routes and initialization * Import github.com/dgrijalva/jwt-go into vendor/ * Adapt LFS module: handlers, routing, meta store * Move LFS routes to /user/repo/info/lfs/* * Add request header checks to LFS BatchHandler / PostHandler * Implement LFS basic authentication * Rework JWT secret generation / load * Implement LFS SSH token authentication with JWT Specification: https://github.com/github/git-lfs/tree/master/docs/api * Integrate LFS settings into install process * Remove LFS objects when repository is deleted Only removes objects from content store when deleted repo is the only referencing repository * Make LFS module stateless Fixes bug where LFS would not work after installation without restarting Gitea * Change 500 'Internal Server Error' to 400 'Bad Request' * Change sql query to xorm call * Remove unneeded type from LFS module * Change internal imports to code.gitea.io/gitea/ * Add Gitea authors copyright * Change basic auth realm to "gitea-lfs" * Add unique indexes to LFS model * Use xorm count function in LFS check on repository delete * Return io.ReadCloser from content store and close after usage * Add LFS info to runWeb() * Export LFS content store base path * LFS file download from UI * Work around git-lfs client issue with unauthenticated requests Returning a dummy Authorization header for unauthenticated requests lets git-lfs client skip asking for auth credentials See: https://github.com/github/git-lfs/issues/1088 * Fix unauthenticated UI downloads from public repositories * Authentication check order, Finish LFS file view logic * Ignore LFS hooks if installed for current OS user Fixes Gitea UI actions for repositories tracking LFS files. Checks for minimum needed git version by parsing the semantic version string. * Hide LFS metafile diff from commit view, marking as binary * Show LFS notice if file in commit view is tracked * Add notbefore/nbf JWT claim * Correct lint suggestions - comments for structs and functions - Add comments to LFS model - Function comment for GetRandomBytesAsBase64 - LFS server function comments and lint variable suggestion * Move secret generation code out of conditional Ensures no LFS code may run with an empty secret * Do not hand out JWT tokens if LFS server support is disabled
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  1. // Copyright 2017 The Gitea Authors. All rights reserved.
  2. // Copyright 2014 The Gogs Authors. All rights reserved.
  3. // Use of this source code is governed by a MIT-style
  4. // license that can be found in the LICENSE file.
  5. package repo
  6. import (
  7. "bytes"
  8. "encoding/base64"
  9. "fmt"
  10. gotemplate "html/template"
  11. "io/ioutil"
  12. "path"
  13. "strings"
  14. "code.gitea.io/gitea/models"
  15. "code.gitea.io/gitea/modules/base"
  16. "code.gitea.io/gitea/modules/charset"
  17. "code.gitea.io/gitea/modules/context"
  18. "code.gitea.io/gitea/modules/git"
  19. "code.gitea.io/gitea/modules/highlight"
  20. "code.gitea.io/gitea/modules/lfs"
  21. "code.gitea.io/gitea/modules/log"
  22. "code.gitea.io/gitea/modules/markup"
  23. "code.gitea.io/gitea/modules/setting"
  24. )
  25. const (
  26. tplRepoEMPTY base.TplName = "repo/empty"
  27. tplRepoHome base.TplName = "repo/home"
  28. tplWatchers base.TplName = "repo/watchers"
  29. tplForks base.TplName = "repo/forks"
  30. )
  31. func renderDirectory(ctx *context.Context, treeLink string) {
  32. tree, err := ctx.Repo.Commit.SubTree(ctx.Repo.TreePath)
  33. if err != nil {
  34. ctx.NotFoundOrServerError("Repo.Commit.SubTree", git.IsErrNotExist, err)
  35. return
  36. }
  37. entries, err := tree.ListEntries()
  38. if err != nil {
  39. ctx.ServerError("ListEntries", err)
  40. return
  41. }
  42. entries.CustomSort(base.NaturalSortLess)
  43. var latestCommit *git.Commit
  44. ctx.Data["Files"], latestCommit, err = entries.GetCommitsInfo(ctx.Repo.Commit, ctx.Repo.TreePath, nil)
  45. if err != nil {
  46. ctx.ServerError("GetCommitsInfo", err)
  47. return
  48. }
  49. // 3 for the extensions in exts[] in order
  50. // the last one is for a readme that doesn't
  51. // strictly match an extension
  52. var readmeFiles [4]*git.Blob
  53. var exts = []string{".md", ".txt", ""} // sorted by priority
  54. for _, entry := range entries {
  55. if entry.IsDir() {
  56. continue
  57. }
  58. for i, ext := range exts {
  59. if markup.IsReadmeFile(entry.Name(), ext) {
  60. readmeFiles[i] = entry.Blob()
  61. }
  62. }
  63. if markup.IsReadmeFile(entry.Name()) {
  64. readmeFiles[3] = entry.Blob()
  65. }
  66. }
  67. var readmeFile *git.Blob
  68. for _, f := range readmeFiles {
  69. if f != nil {
  70. readmeFile = f
  71. break
  72. }
  73. }
  74. if readmeFile != nil {
  75. ctx.Data["RawFileLink"] = ""
  76. ctx.Data["ReadmeInList"] = true
  77. ctx.Data["ReadmeExist"] = true
  78. dataRc, err := readmeFile.DataAsync()
  79. if err != nil {
  80. ctx.ServerError("Data", err)
  81. return
  82. }
  83. defer dataRc.Close()
  84. buf := make([]byte, 1024)
  85. n, _ := dataRc.Read(buf)
  86. buf = buf[:n]
  87. isTextFile := base.IsTextFile(buf)
  88. ctx.Data["FileIsText"] = isTextFile
  89. ctx.Data["FileName"] = readmeFile.Name()
  90. fileSize := int64(0)
  91. isLFSFile := false
  92. ctx.Data["IsLFSFile"] = false
  93. // FIXME: what happens when README file is an image?
  94. if isTextFile && setting.LFS.StartServer {
  95. meta := lfs.IsPointerFile(&buf)
  96. if meta != nil {
  97. meta, err = ctx.Repo.Repository.GetLFSMetaObjectByOid(meta.Oid)
  98. if err != nil && err != models.ErrLFSObjectNotExist {
  99. ctx.ServerError("GetLFSMetaObject", err)
  100. return
  101. }
  102. }
  103. if meta != nil {
  104. ctx.Data["IsLFSFile"] = true
  105. isLFSFile = true
  106. // OK read the lfs object
  107. var err error
  108. dataRc, err = lfs.ReadMetaObject(meta)
  109. if err != nil {
  110. ctx.ServerError("ReadMetaObject", err)
  111. return
  112. }
  113. defer dataRc.Close()
  114. buf = make([]byte, 1024)
  115. n, err = dataRc.Read(buf)
  116. if err != nil {
  117. ctx.ServerError("Data", err)
  118. return
  119. }
  120. buf = buf[:n]
  121. isTextFile = base.IsTextFile(buf)
  122. ctx.Data["IsTextFile"] = isTextFile
  123. fileSize = meta.Size
  124. ctx.Data["FileSize"] = meta.Size
  125. filenameBase64 := base64.RawURLEncoding.EncodeToString([]byte(readmeFile.Name()))
  126. ctx.Data["RawFileLink"] = fmt.Sprintf("%s%s.git/info/lfs/objects/%s/%s", setting.AppURL, ctx.Repo.Repository.FullName(), meta.Oid, filenameBase64)
  127. }
  128. }
  129. if !isLFSFile {
  130. fileSize = readmeFile.Size()
  131. }
  132. if isTextFile {
  133. if fileSize >= setting.UI.MaxDisplayFileSize {
  134. // Pretend that this is a normal text file to display 'This file is too large to be shown'
  135. ctx.Data["IsFileTooLarge"] = true
  136. ctx.Data["IsTextFile"] = true
  137. ctx.Data["FileSize"] = fileSize
  138. } else {
  139. d, _ := ioutil.ReadAll(dataRc)
  140. buf = charset.ToUTF8WithFallback(append(buf, d...))
  141. if markupType := markup.Type(readmeFile.Name()); markupType != "" {
  142. ctx.Data["IsMarkup"] = true
  143. ctx.Data["MarkupType"] = string(markupType)
  144. ctx.Data["FileContent"] = string(markup.Render(readmeFile.Name(), buf, treeLink, ctx.Repo.Repository.ComposeMetas()))
  145. } else {
  146. ctx.Data["IsRenderedHTML"] = true
  147. ctx.Data["FileContent"] = strings.Replace(
  148. gotemplate.HTMLEscapeString(string(buf)), "\n", `<br>`, -1,
  149. )
  150. }
  151. }
  152. }
  153. }
  154. // Show latest commit info of repository in table header,
  155. // or of directory if not in root directory.
  156. ctx.Data["LatestCommit"] = latestCommit
  157. ctx.Data["LatestCommitVerification"] = models.ParseCommitWithSignature(latestCommit)
  158. ctx.Data["LatestCommitUser"] = models.ValidateCommitWithEmail(latestCommit)
  159. statuses, err := models.GetLatestCommitStatus(ctx.Repo.Repository, ctx.Repo.Commit.ID.String(), 0)
  160. if err != nil {
  161. log.Error("GetLatestCommitStatus: %v", err)
  162. }
  163. ctx.Data["LatestCommitStatus"] = models.CalcCommitStatus(statuses)
  164. // Check permission to add or upload new file.
  165. if ctx.Repo.CanWrite(models.UnitTypeCode) && ctx.Repo.IsViewBranch {
  166. ctx.Data["CanAddFile"] = !ctx.Repo.Repository.IsArchived
  167. ctx.Data["CanUploadFile"] = setting.Repository.Upload.Enabled && !ctx.Repo.Repository.IsArchived
  168. }
  169. }
  170. func renderFile(ctx *context.Context, entry *git.TreeEntry, treeLink, rawLink string) {
  171. ctx.Data["IsViewFile"] = true
  172. blob := entry.Blob()
  173. dataRc, err := blob.DataAsync()
  174. if err != nil {
  175. ctx.ServerError("DataAsync", err)
  176. return
  177. }
  178. defer dataRc.Close()
  179. ctx.Data["Title"] = ctx.Data["Title"].(string) + " - " + ctx.Repo.TreePath + " at " + ctx.Repo.BranchName
  180. fileSize := blob.Size()
  181. ctx.Data["FileSize"] = fileSize
  182. ctx.Data["FileName"] = blob.Name()
  183. ctx.Data["HighlightClass"] = highlight.FileNameToHighlightClass(blob.Name())
  184. ctx.Data["RawFileLink"] = rawLink + "/" + ctx.Repo.TreePath
  185. buf := make([]byte, 1024)
  186. n, _ := dataRc.Read(buf)
  187. buf = buf[:n]
  188. isTextFile := base.IsTextFile(buf)
  189. isLFSFile := false
  190. ctx.Data["IsTextFile"] = isTextFile
  191. //Check for LFS meta file
  192. if isTextFile && setting.LFS.StartServer {
  193. meta := lfs.IsPointerFile(&buf)
  194. if meta != nil {
  195. meta, err = ctx.Repo.Repository.GetLFSMetaObjectByOid(meta.Oid)
  196. if err != nil && err != models.ErrLFSObjectNotExist {
  197. ctx.ServerError("GetLFSMetaObject", err)
  198. return
  199. }
  200. }
  201. if meta != nil {
  202. ctx.Data["IsLFSFile"] = true
  203. isLFSFile = true
  204. // OK read the lfs object
  205. var err error
  206. dataRc, err = lfs.ReadMetaObject(meta)
  207. if err != nil {
  208. ctx.ServerError("ReadMetaObject", err)
  209. return
  210. }
  211. defer dataRc.Close()
  212. buf = make([]byte, 1024)
  213. n, err = dataRc.Read(buf)
  214. if err != nil {
  215. ctx.ServerError("Data", err)
  216. return
  217. }
  218. buf = buf[:n]
  219. isTextFile = base.IsTextFile(buf)
  220. ctx.Data["IsTextFile"] = isTextFile
  221. fileSize = meta.Size
  222. ctx.Data["FileSize"] = meta.Size
  223. filenameBase64 := base64.RawURLEncoding.EncodeToString([]byte(blob.Name()))
  224. ctx.Data["RawFileLink"] = fmt.Sprintf("%s%s.git/info/lfs/objects/%s/%s", setting.AppURL, ctx.Repo.Repository.FullName(), meta.Oid, filenameBase64)
  225. }
  226. }
  227. // Assume file is not editable first.
  228. if isLFSFile {
  229. ctx.Data["EditFileTooltip"] = ctx.Tr("repo.editor.cannot_edit_lfs_files")
  230. } else if !isTextFile {
  231. ctx.Data["EditFileTooltip"] = ctx.Tr("repo.editor.cannot_edit_non_text_files")
  232. }
  233. switch {
  234. case isTextFile:
  235. if fileSize >= setting.UI.MaxDisplayFileSize {
  236. ctx.Data["IsFileTooLarge"] = true
  237. break
  238. }
  239. d, _ := ioutil.ReadAll(dataRc)
  240. buf = charset.ToUTF8WithFallback(append(buf, d...))
  241. readmeExist := markup.IsReadmeFile(blob.Name())
  242. ctx.Data["ReadmeExist"] = readmeExist
  243. if markupType := markup.Type(blob.Name()); markupType != "" {
  244. ctx.Data["IsMarkup"] = true
  245. ctx.Data["MarkupType"] = markupType
  246. ctx.Data["FileContent"] = string(markup.Render(blob.Name(), buf, path.Dir(treeLink), ctx.Repo.Repository.ComposeMetas()))
  247. } else if readmeExist {
  248. ctx.Data["IsRenderedHTML"] = true
  249. ctx.Data["FileContent"] = strings.Replace(
  250. gotemplate.HTMLEscapeString(string(buf)), "\n", `<br>`, -1,
  251. )
  252. } else {
  253. // Building code view blocks with line number on server side.
  254. var fileContent string
  255. if content, err := charset.ToUTF8WithErr(buf); err != nil {
  256. log.Error("ToUTF8WithErr: %v", err)
  257. fileContent = string(buf)
  258. } else {
  259. fileContent = content
  260. }
  261. var output bytes.Buffer
  262. lines := strings.Split(fileContent, "\n")
  263. //Remove blank line at the end of file
  264. if len(lines) > 0 && lines[len(lines)-1] == "" {
  265. lines = lines[:len(lines)-1]
  266. }
  267. for index, line := range lines {
  268. line = gotemplate.HTMLEscapeString(line)
  269. if index != len(lines)-1 {
  270. line += "\n"
  271. }
  272. output.WriteString(fmt.Sprintf(`<li class="L%d" rel="L%d">%s</li>`, index+1, index+1, line))
  273. }
  274. ctx.Data["FileContent"] = gotemplate.HTML(output.String())
  275. output.Reset()
  276. for i := 0; i < len(lines); i++ {
  277. output.WriteString(fmt.Sprintf(`<span id="L%[1]d" data-line-number="%[1]d"></span>`, i+1))
  278. }
  279. ctx.Data["LineNums"] = gotemplate.HTML(output.String())
  280. }
  281. if !isLFSFile {
  282. if ctx.Repo.CanEnableEditor() {
  283. ctx.Data["CanEditFile"] = true
  284. ctx.Data["EditFileTooltip"] = ctx.Tr("repo.editor.edit_this_file")
  285. } else if !ctx.Repo.IsViewBranch {
  286. ctx.Data["EditFileTooltip"] = ctx.Tr("repo.editor.must_be_on_a_branch")
  287. } else if !ctx.Repo.CanWrite(models.UnitTypeCode) {
  288. ctx.Data["EditFileTooltip"] = ctx.Tr("repo.editor.fork_before_edit")
  289. }
  290. }
  291. case base.IsPDFFile(buf):
  292. ctx.Data["IsPDFFile"] = true
  293. case base.IsVideoFile(buf):
  294. ctx.Data["IsVideoFile"] = true
  295. case base.IsAudioFile(buf):
  296. ctx.Data["IsAudioFile"] = true
  297. case base.IsImageFile(buf):
  298. ctx.Data["IsImageFile"] = true
  299. }
  300. if ctx.Repo.CanEnableEditor() {
  301. ctx.Data["CanDeleteFile"] = true
  302. ctx.Data["DeleteFileTooltip"] = ctx.Tr("repo.editor.delete_this_file")
  303. } else if !ctx.Repo.IsViewBranch {
  304. ctx.Data["DeleteFileTooltip"] = ctx.Tr("repo.editor.must_be_on_a_branch")
  305. } else if !ctx.Repo.CanWrite(models.UnitTypeCode) {
  306. ctx.Data["DeleteFileTooltip"] = ctx.Tr("repo.editor.must_have_write_access")
  307. }
  308. }
  309. // Home render repository home page
  310. func Home(ctx *context.Context) {
  311. if len(ctx.Repo.Units) > 0 {
  312. var firstUnit *models.Unit
  313. for _, repoUnit := range ctx.Repo.Units {
  314. if repoUnit.Type == models.UnitTypeCode {
  315. renderCode(ctx)
  316. return
  317. }
  318. unit, ok := models.Units[repoUnit.Type]
  319. if ok && (firstUnit == nil || !firstUnit.IsLessThan(unit)) {
  320. firstUnit = &unit
  321. }
  322. }
  323. if firstUnit != nil {
  324. ctx.Redirect(fmt.Sprintf("%s/%s%s", setting.AppSubURL, ctx.Repo.Repository.FullName(), firstUnit.URI))
  325. return
  326. }
  327. }
  328. ctx.NotFound("Home", fmt.Errorf(ctx.Tr("units.error.no_unit_allowed_repo")))
  329. }
  330. func renderCode(ctx *context.Context) {
  331. ctx.Data["PageIsViewCode"] = true
  332. if ctx.Repo.Repository.IsEmpty {
  333. ctx.HTML(200, tplRepoEMPTY)
  334. return
  335. }
  336. title := ctx.Repo.Repository.Owner.Name + "/" + ctx.Repo.Repository.Name
  337. if len(ctx.Repo.Repository.Description) > 0 {
  338. title += ": " + ctx.Repo.Repository.Description
  339. }
  340. ctx.Data["Title"] = title
  341. ctx.Data["RequireHighlightJS"] = true
  342. branchLink := ctx.Repo.RepoLink + "/src/" + ctx.Repo.BranchNameSubURL()
  343. treeLink := branchLink
  344. rawLink := ctx.Repo.RepoLink + "/raw/" + ctx.Repo.BranchNameSubURL()
  345. if len(ctx.Repo.TreePath) > 0 {
  346. treeLink += "/" + ctx.Repo.TreePath
  347. }
  348. // Get Topics of this repo
  349. topics, err := models.FindTopics(&models.FindTopicOptions{
  350. RepoID: ctx.Repo.Repository.ID,
  351. })
  352. if err != nil {
  353. ctx.ServerError("models.FindTopics", err)
  354. return
  355. }
  356. ctx.Data["Topics"] = topics
  357. // Get current entry user currently looking at.
  358. entry, err := ctx.Repo.Commit.GetTreeEntryByPath(ctx.Repo.TreePath)
  359. if err != nil {
  360. ctx.NotFoundOrServerError("Repo.Commit.GetTreeEntryByPath", git.IsErrNotExist, err)
  361. return
  362. }
  363. if entry.IsDir() {
  364. renderDirectory(ctx, treeLink)
  365. } else {
  366. renderFile(ctx, entry, treeLink, rawLink)
  367. }
  368. if ctx.Written() {
  369. return
  370. }
  371. var treeNames []string
  372. paths := make([]string, 0, 5)
  373. if len(ctx.Repo.TreePath) > 0 {
  374. treeNames = strings.Split(ctx.Repo.TreePath, "/")
  375. for i := range treeNames {
  376. paths = append(paths, strings.Join(treeNames[:i+1], "/"))
  377. }
  378. ctx.Data["HasParentPath"] = true
  379. if len(paths)-2 >= 0 {
  380. ctx.Data["ParentPath"] = "/" + paths[len(paths)-2]
  381. }
  382. }
  383. ctx.Data["Paths"] = paths
  384. ctx.Data["TreeLink"] = treeLink
  385. ctx.Data["TreeNames"] = treeNames
  386. ctx.Data["BranchLink"] = branchLink
  387. ctx.HTML(200, tplRepoHome)
  388. }
  389. // RenderUserCards render a page show users according the input templaet
  390. func RenderUserCards(ctx *context.Context, total int, getter func(page int) ([]*models.User, error), tpl base.TplName) {
  391. page := ctx.QueryInt("page")
  392. if page <= 0 {
  393. page = 1
  394. }
  395. pager := context.NewPagination(total, models.ItemsPerPage, page, 5)
  396. ctx.Data["Page"] = pager
  397. items, err := getter(pager.Paginater.Current())
  398. if err != nil {
  399. ctx.ServerError("getter", err)
  400. return
  401. }
  402. ctx.Data["Cards"] = items
  403. ctx.HTML(200, tpl)
  404. }
  405. // Watchers render repository's watch users
  406. func Watchers(ctx *context.Context) {
  407. ctx.Data["Title"] = ctx.Tr("repo.watchers")
  408. ctx.Data["CardsTitle"] = ctx.Tr("repo.watchers")
  409. ctx.Data["PageIsWatchers"] = true
  410. RenderUserCards(ctx, ctx.Repo.Repository.NumWatches, ctx.Repo.Repository.GetWatchers, tplWatchers)
  411. }
  412. // Stars render repository's starred users
  413. func Stars(ctx *context.Context) {
  414. ctx.Data["Title"] = ctx.Tr("repo.stargazers")
  415. ctx.Data["CardsTitle"] = ctx.Tr("repo.stargazers")
  416. ctx.Data["PageIsStargazers"] = true
  417. RenderUserCards(ctx, ctx.Repo.Repository.NumStars, ctx.Repo.Repository.GetStargazers, tplWatchers)
  418. }
  419. // Forks render repository's forked users
  420. func Forks(ctx *context.Context) {
  421. ctx.Data["Title"] = ctx.Tr("repos.forks")
  422. forks, err := ctx.Repo.Repository.GetForks()
  423. if err != nil {
  424. ctx.ServerError("GetForks", err)
  425. return
  426. }
  427. for _, fork := range forks {
  428. if err = fork.GetOwner(); err != nil {
  429. ctx.ServerError("GetOwner", err)
  430. return
  431. }
  432. }
  433. ctx.Data["Forks"] = forks
  434. ctx.HTML(200, tplForks)
  435. }