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
9 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
11 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
9 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
9 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
10 years ago
10 years ago
10 years ago
10 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  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/context"
  17. "code.gitea.io/gitea/modules/git"
  18. "code.gitea.io/gitea/modules/highlight"
  19. "code.gitea.io/gitea/modules/lfs"
  20. "code.gitea.io/gitea/modules/log"
  21. "code.gitea.io/gitea/modules/markup"
  22. "code.gitea.io/gitea/modules/setting"
  23. "code.gitea.io/gitea/modules/templates"
  24. "github.com/Unknwon/paginater"
  25. )
  26. const (
  27. tplRepoEMPTY base.TplName = "repo/empty"
  28. tplRepoHome base.TplName = "repo/home"
  29. tplWatchers base.TplName = "repo/watchers"
  30. tplForks base.TplName = "repo/forks"
  31. )
  32. func renderDirectory(ctx *context.Context, treeLink string) {
  33. tree, err := ctx.Repo.Commit.SubTree(ctx.Repo.TreePath)
  34. if err != nil {
  35. ctx.NotFoundOrServerError("Repo.Commit.SubTree", git.IsErrNotExist, err)
  36. return
  37. }
  38. entries, err := tree.ListEntries()
  39. if err != nil {
  40. ctx.ServerError("ListEntries", err)
  41. return
  42. }
  43. entries.CustomSort(base.NaturalSortLess)
  44. var latestCommit *git.Commit
  45. ctx.Data["Files"], latestCommit, err = entries.GetCommitsInfo(ctx.Repo.Commit, ctx.Repo.TreePath, nil)
  46. if err != nil {
  47. ctx.ServerError("GetCommitsInfo", err)
  48. return
  49. }
  50. // 3 for the extensions in exts[] in order
  51. // the last one is for a readme that doesn't
  52. // strictly match an extension
  53. var readmeFiles [4]*git.Blob
  54. var exts = []string{".md", ".txt", ""} // sorted by priority
  55. for _, entry := range entries {
  56. if entry.IsDir() {
  57. continue
  58. }
  59. for i, ext := range exts {
  60. if markup.IsReadmeFile(entry.Name(), ext) {
  61. readmeFiles[i] = entry.Blob()
  62. }
  63. }
  64. if markup.IsReadmeFile(entry.Name()) {
  65. readmeFiles[3] = entry.Blob()
  66. }
  67. }
  68. var readmeFile *git.Blob
  69. for _, f := range readmeFiles {
  70. if f != nil {
  71. readmeFile = f
  72. break
  73. }
  74. }
  75. if readmeFile != nil {
  76. ctx.Data["RawFileLink"] = ""
  77. ctx.Data["ReadmeInList"] = true
  78. ctx.Data["ReadmeExist"] = true
  79. dataRc, err := readmeFile.DataAsync()
  80. if err != nil {
  81. ctx.ServerError("Data", err)
  82. return
  83. }
  84. defer dataRc.Close()
  85. buf := make([]byte, 1024)
  86. n, _ := dataRc.Read(buf)
  87. buf = buf[:n]
  88. isTextFile := base.IsTextFile(buf)
  89. ctx.Data["FileIsText"] = isTextFile
  90. ctx.Data["FileName"] = readmeFile.Name()
  91. fileSize := int64(0)
  92. isLFSFile := false
  93. ctx.Data["IsLFSFile"] = false
  94. // FIXME: what happens when README file is an image?
  95. if isTextFile && setting.LFS.StartServer {
  96. meta := lfs.IsPointerFile(&buf)
  97. if meta != nil {
  98. meta, err = ctx.Repo.Repository.GetLFSMetaObjectByOid(meta.Oid)
  99. if err != nil && err != models.ErrLFSObjectNotExist {
  100. ctx.ServerError("GetLFSMetaObject", err)
  101. return
  102. }
  103. }
  104. if meta != nil {
  105. ctx.Data["IsLFSFile"] = true
  106. isLFSFile = true
  107. // OK read the lfs object
  108. var err error
  109. dataRc, err = lfs.ReadMetaObject(meta)
  110. if err != nil {
  111. ctx.ServerError("ReadMetaObject", err)
  112. return
  113. }
  114. defer dataRc.Close()
  115. buf = make([]byte, 1024)
  116. n, err = dataRc.Read(buf)
  117. if err != nil {
  118. ctx.ServerError("Data", err)
  119. return
  120. }
  121. buf = buf[:n]
  122. isTextFile = base.IsTextFile(buf)
  123. ctx.Data["IsTextFile"] = isTextFile
  124. fileSize = meta.Size
  125. ctx.Data["FileSize"] = meta.Size
  126. filenameBase64 := base64.RawURLEncoding.EncodeToString([]byte(readmeFile.Name()))
  127. ctx.Data["RawFileLink"] = fmt.Sprintf("%s%s.git/info/lfs/objects/%s/%s", setting.AppURL, ctx.Repo.Repository.FullName(), meta.Oid, filenameBase64)
  128. }
  129. }
  130. if !isLFSFile {
  131. fileSize = readmeFile.Size()
  132. }
  133. if isTextFile {
  134. if fileSize >= setting.UI.MaxDisplayFileSize {
  135. // Pretend that this is a normal text file to display 'This file is too large to be shown'
  136. ctx.Data["IsFileTooLarge"] = true
  137. ctx.Data["IsTextFile"] = true
  138. ctx.Data["FileSize"] = fileSize
  139. } else {
  140. d, _ := ioutil.ReadAll(dataRc)
  141. buf = templates.ToUTF8WithFallback(append(buf, d...))
  142. if markup.Type(readmeFile.Name()) != "" {
  143. ctx.Data["IsMarkup"] = true
  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 = templates.ToUTF8WithFallback(append(buf, d...))
  241. readmeExist := markup.IsReadmeFile(blob.Name())
  242. ctx.Data["ReadmeExist"] = readmeExist
  243. if markup.Type(blob.Name()) != "" {
  244. ctx.Data["IsMarkup"] = true
  245. ctx.Data["FileContent"] = string(markup.Render(blob.Name(), buf, path.Dir(treeLink), ctx.Repo.Repository.ComposeMetas()))
  246. } else if readmeExist {
  247. ctx.Data["IsRenderedHTML"] = true
  248. ctx.Data["FileContent"] = strings.Replace(
  249. gotemplate.HTMLEscapeString(string(buf)), "\n", `<br>`, -1,
  250. )
  251. } else {
  252. // Building code view blocks with line number on server side.
  253. var fileContent string
  254. if content, err := templates.ToUTF8WithErr(buf); err != nil {
  255. if err != nil {
  256. log.Error("ToUTF8WithErr: %v", err)
  257. }
  258. fileContent = string(buf)
  259. } else {
  260. fileContent = content
  261. }
  262. var output bytes.Buffer
  263. lines := strings.Split(fileContent, "\n")
  264. //Remove blank line at the end of file
  265. if len(lines) > 0 && lines[len(lines)-1] == "" {
  266. lines = lines[:len(lines)-1]
  267. }
  268. for index, line := range lines {
  269. line = gotemplate.HTMLEscapeString(line)
  270. if index != len(lines)-1 {
  271. line += "\n"
  272. }
  273. output.WriteString(fmt.Sprintf(`<li class="L%d" rel="L%d">%s</li>`, index+1, index+1, line))
  274. }
  275. ctx.Data["FileContent"] = gotemplate.HTML(output.String())
  276. output.Reset()
  277. for i := 0; i < len(lines); i++ {
  278. output.WriteString(fmt.Sprintf(`<span id="L%d">%d</span>`, i+1, i+1))
  279. }
  280. ctx.Data["LineNums"] = gotemplate.HTML(output.String())
  281. }
  282. if !isLFSFile {
  283. if ctx.Repo.CanEnableEditor() {
  284. ctx.Data["CanEditFile"] = true
  285. ctx.Data["EditFileTooltip"] = ctx.Tr("repo.editor.edit_this_file")
  286. } else if !ctx.Repo.IsViewBranch {
  287. ctx.Data["EditFileTooltip"] = ctx.Tr("repo.editor.must_be_on_a_branch")
  288. } else if !ctx.Repo.CanWrite(models.UnitTypeCode) {
  289. ctx.Data["EditFileTooltip"] = ctx.Tr("repo.editor.fork_before_edit")
  290. }
  291. }
  292. case base.IsPDFFile(buf):
  293. ctx.Data["IsPDFFile"] = true
  294. case base.IsVideoFile(buf):
  295. ctx.Data["IsVideoFile"] = true
  296. case base.IsAudioFile(buf):
  297. ctx.Data["IsAudioFile"] = true
  298. case base.IsImageFile(buf):
  299. ctx.Data["IsImageFile"] = true
  300. }
  301. if ctx.Repo.CanEnableEditor() {
  302. ctx.Data["CanDeleteFile"] = true
  303. ctx.Data["DeleteFileTooltip"] = ctx.Tr("repo.editor.delete_this_file")
  304. } else if !ctx.Repo.IsViewBranch {
  305. ctx.Data["DeleteFileTooltip"] = ctx.Tr("repo.editor.must_be_on_a_branch")
  306. } else if !ctx.Repo.CanWrite(models.UnitTypeCode) {
  307. ctx.Data["DeleteFileTooltip"] = ctx.Tr("repo.editor.must_have_write_access")
  308. }
  309. }
  310. // Home render repository home page
  311. func Home(ctx *context.Context) {
  312. if !models.HasOrgVisible(ctx.Repo.Repository.Owner, ctx.User) {
  313. ctx.NotFound("HasOrgVisible", nil)
  314. return
  315. }
  316. if len(ctx.Repo.Units) > 0 {
  317. var firstUnit *models.Unit
  318. for _, repoUnit := range ctx.Repo.Units {
  319. if repoUnit.Type == models.UnitTypeCode {
  320. renderCode(ctx)
  321. return
  322. }
  323. unit, ok := models.Units[repoUnit.Type]
  324. if ok && (firstUnit == nil || !firstUnit.IsLessThan(unit)) {
  325. firstUnit = &unit
  326. }
  327. }
  328. if firstUnit != nil {
  329. ctx.Redirect(fmt.Sprintf("%s/%s%s", setting.AppSubURL, ctx.Repo.Repository.FullName(), firstUnit.URI))
  330. return
  331. }
  332. }
  333. ctx.NotFound("Home", fmt.Errorf(ctx.Tr("units.error.no_unit_allowed_repo")))
  334. }
  335. func renderCode(ctx *context.Context) {
  336. ctx.Data["PageIsViewCode"] = true
  337. if ctx.Repo.Repository.IsEmpty {
  338. ctx.HTML(200, tplRepoEMPTY)
  339. return
  340. }
  341. title := ctx.Repo.Repository.Owner.Name + "/" + ctx.Repo.Repository.Name
  342. if len(ctx.Repo.Repository.Description) > 0 {
  343. title += ": " + ctx.Repo.Repository.Description
  344. }
  345. ctx.Data["Title"] = title
  346. ctx.Data["RequireHighlightJS"] = true
  347. branchLink := ctx.Repo.RepoLink + "/src/" + ctx.Repo.BranchNameSubURL()
  348. treeLink := branchLink
  349. rawLink := ctx.Repo.RepoLink + "/raw/" + ctx.Repo.BranchNameSubURL()
  350. if len(ctx.Repo.TreePath) > 0 {
  351. treeLink += "/" + ctx.Repo.TreePath
  352. }
  353. // Get Topics of this repo
  354. topics, err := models.FindTopics(&models.FindTopicOptions{
  355. RepoID: ctx.Repo.Repository.ID,
  356. })
  357. if err != nil {
  358. ctx.ServerError("models.FindTopics", err)
  359. return
  360. }
  361. ctx.Data["Topics"] = topics
  362. // Get current entry user currently looking at.
  363. entry, err := ctx.Repo.Commit.GetTreeEntryByPath(ctx.Repo.TreePath)
  364. if err != nil {
  365. ctx.NotFoundOrServerError("Repo.Commit.GetTreeEntryByPath", git.IsErrNotExist, err)
  366. return
  367. }
  368. if entry.IsDir() {
  369. renderDirectory(ctx, treeLink)
  370. } else {
  371. renderFile(ctx, entry, treeLink, rawLink)
  372. }
  373. if ctx.Written() {
  374. return
  375. }
  376. var treeNames []string
  377. paths := make([]string, 0, 5)
  378. if len(ctx.Repo.TreePath) > 0 {
  379. treeNames = strings.Split(ctx.Repo.TreePath, "/")
  380. for i := range treeNames {
  381. paths = append(paths, strings.Join(treeNames[:i+1], "/"))
  382. }
  383. ctx.Data["HasParentPath"] = true
  384. if len(paths)-2 >= 0 {
  385. ctx.Data["ParentPath"] = "/" + paths[len(paths)-2]
  386. }
  387. }
  388. ctx.Data["Paths"] = paths
  389. ctx.Data["TreeLink"] = treeLink
  390. ctx.Data["TreeNames"] = treeNames
  391. ctx.Data["BranchLink"] = branchLink
  392. ctx.HTML(200, tplRepoHome)
  393. }
  394. // RenderUserCards render a page show users according the input templaet
  395. func RenderUserCards(ctx *context.Context, total int, getter func(page int) ([]*models.User, error), tpl base.TplName) {
  396. page := ctx.QueryInt("page")
  397. if page <= 0 {
  398. page = 1
  399. }
  400. pager := paginater.New(total, models.ItemsPerPage, page, 5)
  401. ctx.Data["Page"] = pager
  402. items, err := getter(pager.Current())
  403. if err != nil {
  404. ctx.ServerError("getter", err)
  405. return
  406. }
  407. ctx.Data["Cards"] = items
  408. ctx.HTML(200, tpl)
  409. }
  410. // Watchers render repository's watch users
  411. func Watchers(ctx *context.Context) {
  412. ctx.Data["Title"] = ctx.Tr("repo.watchers")
  413. ctx.Data["CardsTitle"] = ctx.Tr("repo.watchers")
  414. ctx.Data["PageIsWatchers"] = true
  415. RenderUserCards(ctx, ctx.Repo.Repository.NumWatches, ctx.Repo.Repository.GetWatchers, tplWatchers)
  416. }
  417. // Stars render repository's starred users
  418. func Stars(ctx *context.Context) {
  419. ctx.Data["Title"] = ctx.Tr("repo.stargazers")
  420. ctx.Data["CardsTitle"] = ctx.Tr("repo.stargazers")
  421. ctx.Data["PageIsStargazers"] = true
  422. RenderUserCards(ctx, ctx.Repo.Repository.NumStars, ctx.Repo.Repository.GetStargazers, tplWatchers)
  423. }
  424. // Forks render repository's forked users
  425. func Forks(ctx *context.Context) {
  426. ctx.Data["Title"] = ctx.Tr("repos.forks")
  427. forks, err := ctx.Repo.Repository.GetForks()
  428. if err != nil {
  429. ctx.ServerError("GetForks", err)
  430. return
  431. }
  432. for _, fork := range forks {
  433. if err = fork.GetOwner(); err != nil {
  434. ctx.ServerError("GetOwner", err)
  435. return
  436. }
  437. }
  438. ctx.Data["Forks"] = forks
  439. ctx.HTML(200, tplForks)
  440. }