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.

520 lines
14 KiB

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
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
5 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
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
5 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
  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. ctx.Data["Files"], 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 = templates.ToUTF8WithFallback(append(buf, d...))
  141. if markup.Type(readmeFile.Name()) != "" {
  142. ctx.Data["IsMarkup"] = true
  143. ctx.Data["FileContent"] = string(markup.Render(readmeFile.Name(), buf, treeLink, ctx.Repo.Repository.ComposeMetas()))
  144. } else {
  145. ctx.Data["IsRenderedHTML"] = true
  146. ctx.Data["FileContent"] = strings.Replace(
  147. gotemplate.HTMLEscapeString(string(buf)), "\n", `<br>`, -1,
  148. )
  149. }
  150. }
  151. }
  152. }
  153. // Show latest commit info of repository in table header,
  154. // or of directory if not in root directory.
  155. latestCommit := ctx.Repo.Commit
  156. if len(ctx.Repo.TreePath) > 0 {
  157. latestCommit, err = ctx.Repo.Commit.GetCommitByPath(ctx.Repo.TreePath)
  158. if err != nil {
  159. ctx.ServerError("GetCommitByPath", err)
  160. return
  161. }
  162. }
  163. ctx.Data["LatestCommit"] = latestCommit
  164. ctx.Data["LatestCommitVerification"] = models.ParseCommitWithSignature(latestCommit)
  165. ctx.Data["LatestCommitUser"] = models.ValidateCommitWithEmail(latestCommit)
  166. statuses, err := models.GetLatestCommitStatus(ctx.Repo.Repository, ctx.Repo.Commit.ID.String(), 0)
  167. if err != nil {
  168. log.Error("GetLatestCommitStatus: %v", err)
  169. }
  170. ctx.Data["LatestCommitStatus"] = models.CalcCommitStatus(statuses)
  171. // Check permission to add or upload new file.
  172. if ctx.Repo.CanWrite(models.UnitTypeCode) && ctx.Repo.IsViewBranch {
  173. ctx.Data["CanAddFile"] = !ctx.Repo.Repository.IsArchived
  174. ctx.Data["CanUploadFile"] = setting.Repository.Upload.Enabled && !ctx.Repo.Repository.IsArchived
  175. }
  176. }
  177. func renderFile(ctx *context.Context, entry *git.TreeEntry, treeLink, rawLink string) {
  178. ctx.Data["IsViewFile"] = true
  179. blob := entry.Blob()
  180. dataRc, err := blob.DataAsync()
  181. if err != nil {
  182. ctx.ServerError("DataAsync", err)
  183. return
  184. }
  185. defer dataRc.Close()
  186. ctx.Data["Title"] = ctx.Data["Title"].(string) + " - " + ctx.Repo.TreePath + " at " + ctx.Repo.BranchName
  187. fileSize := blob.Size()
  188. ctx.Data["FileSize"] = fileSize
  189. ctx.Data["FileName"] = blob.Name()
  190. ctx.Data["HighlightClass"] = highlight.FileNameToHighlightClass(blob.Name())
  191. ctx.Data["RawFileLink"] = rawLink + "/" + ctx.Repo.TreePath
  192. buf := make([]byte, 1024)
  193. n, _ := dataRc.Read(buf)
  194. buf = buf[:n]
  195. isTextFile := base.IsTextFile(buf)
  196. isLFSFile := false
  197. ctx.Data["IsTextFile"] = isTextFile
  198. //Check for LFS meta file
  199. if isTextFile && setting.LFS.StartServer {
  200. meta := lfs.IsPointerFile(&buf)
  201. if meta != nil {
  202. meta, err = ctx.Repo.Repository.GetLFSMetaObjectByOid(meta.Oid)
  203. if err != nil && err != models.ErrLFSObjectNotExist {
  204. ctx.ServerError("GetLFSMetaObject", err)
  205. return
  206. }
  207. }
  208. if meta != nil {
  209. ctx.Data["IsLFSFile"] = true
  210. isLFSFile = true
  211. // OK read the lfs object
  212. var err error
  213. dataRc, err = lfs.ReadMetaObject(meta)
  214. if err != nil {
  215. ctx.ServerError("ReadMetaObject", err)
  216. return
  217. }
  218. defer dataRc.Close()
  219. buf = make([]byte, 1024)
  220. n, err = dataRc.Read(buf)
  221. if err != nil {
  222. ctx.ServerError("Data", err)
  223. return
  224. }
  225. buf = buf[:n]
  226. isTextFile = base.IsTextFile(buf)
  227. ctx.Data["IsTextFile"] = isTextFile
  228. fileSize = meta.Size
  229. ctx.Data["FileSize"] = meta.Size
  230. filenameBase64 := base64.RawURLEncoding.EncodeToString([]byte(blob.Name()))
  231. ctx.Data["RawFileLink"] = fmt.Sprintf("%s%s.git/info/lfs/objects/%s/%s", setting.AppURL, ctx.Repo.Repository.FullName(), meta.Oid, filenameBase64)
  232. }
  233. }
  234. // Assume file is not editable first.
  235. if isLFSFile {
  236. ctx.Data["EditFileTooltip"] = ctx.Tr("repo.editor.cannot_edit_lfs_files")
  237. } else if !isTextFile {
  238. ctx.Data["EditFileTooltip"] = ctx.Tr("repo.editor.cannot_edit_non_text_files")
  239. }
  240. switch {
  241. case isTextFile:
  242. if fileSize >= setting.UI.MaxDisplayFileSize {
  243. ctx.Data["IsFileTooLarge"] = true
  244. break
  245. }
  246. d, _ := ioutil.ReadAll(dataRc)
  247. buf = templates.ToUTF8WithFallback(append(buf, d...))
  248. readmeExist := markup.IsReadmeFile(blob.Name())
  249. ctx.Data["ReadmeExist"] = readmeExist
  250. if markup.Type(blob.Name()) != "" {
  251. ctx.Data["IsMarkup"] = true
  252. ctx.Data["FileContent"] = string(markup.Render(blob.Name(), buf, path.Dir(treeLink), ctx.Repo.Repository.ComposeMetas()))
  253. } else if readmeExist {
  254. ctx.Data["IsRenderedHTML"] = true
  255. ctx.Data["FileContent"] = strings.Replace(
  256. gotemplate.HTMLEscapeString(string(buf)), "\n", `<br>`, -1,
  257. )
  258. } else {
  259. // Building code view blocks with line number on server side.
  260. var fileContent string
  261. if content, err := templates.ToUTF8WithErr(buf); err != nil {
  262. if err != nil {
  263. log.Error("ToUTF8WithErr: %v", err)
  264. }
  265. fileContent = string(buf)
  266. } else {
  267. fileContent = content
  268. }
  269. var output bytes.Buffer
  270. lines := strings.Split(fileContent, "\n")
  271. //Remove blank line at the end of file
  272. if len(lines) > 0 && lines[len(lines)-1] == "" {
  273. lines = lines[:len(lines)-1]
  274. }
  275. for index, line := range lines {
  276. line = gotemplate.HTMLEscapeString(line)
  277. if index != len(lines)-1 {
  278. line += "\n"
  279. }
  280. output.WriteString(fmt.Sprintf(`<li class="L%d" rel="L%d">%s</li>`, index+1, index+1, line))
  281. }
  282. ctx.Data["FileContent"] = gotemplate.HTML(output.String())
  283. output.Reset()
  284. for i := 0; i < len(lines); i++ {
  285. output.WriteString(fmt.Sprintf(`<span id="L%d">%d</span>`, i+1, i+1))
  286. }
  287. ctx.Data["LineNums"] = gotemplate.HTML(output.String())
  288. }
  289. if !isLFSFile {
  290. if ctx.Repo.CanEnableEditor() {
  291. ctx.Data["CanEditFile"] = true
  292. ctx.Data["EditFileTooltip"] = ctx.Tr("repo.editor.edit_this_file")
  293. } else if !ctx.Repo.IsViewBranch {
  294. ctx.Data["EditFileTooltip"] = ctx.Tr("repo.editor.must_be_on_a_branch")
  295. } else if !ctx.Repo.CanWrite(models.UnitTypeCode) {
  296. ctx.Data["EditFileTooltip"] = ctx.Tr("repo.editor.fork_before_edit")
  297. }
  298. }
  299. case base.IsPDFFile(buf):
  300. ctx.Data["IsPDFFile"] = true
  301. case base.IsVideoFile(buf):
  302. ctx.Data["IsVideoFile"] = true
  303. case base.IsAudioFile(buf):
  304. ctx.Data["IsAudioFile"] = true
  305. case base.IsImageFile(buf):
  306. ctx.Data["IsImageFile"] = true
  307. }
  308. if ctx.Repo.CanEnableEditor() {
  309. ctx.Data["CanDeleteFile"] = true
  310. ctx.Data["DeleteFileTooltip"] = ctx.Tr("repo.editor.delete_this_file")
  311. } else if !ctx.Repo.IsViewBranch {
  312. ctx.Data["DeleteFileTooltip"] = ctx.Tr("repo.editor.must_be_on_a_branch")
  313. } else if !ctx.Repo.CanWrite(models.UnitTypeCode) {
  314. ctx.Data["DeleteFileTooltip"] = ctx.Tr("repo.editor.must_have_write_access")
  315. }
  316. }
  317. // Home render repository home page
  318. func Home(ctx *context.Context) {
  319. if !models.HasOrgVisible(ctx.Repo.Repository.Owner, ctx.User) {
  320. ctx.NotFound("HasOrgVisible", nil)
  321. return
  322. }
  323. if len(ctx.Repo.Units) > 0 {
  324. var firstUnit *models.Unit
  325. for _, repoUnit := range ctx.Repo.Units {
  326. if repoUnit.Type == models.UnitTypeCode {
  327. renderCode(ctx)
  328. return
  329. }
  330. unit, ok := models.Units[repoUnit.Type]
  331. if ok && (firstUnit == nil || !firstUnit.IsLessThan(unit)) {
  332. firstUnit = &unit
  333. }
  334. }
  335. if firstUnit != nil {
  336. ctx.Redirect(fmt.Sprintf("%s/%s%s", setting.AppSubURL, ctx.Repo.Repository.FullName(), firstUnit.URI))
  337. return
  338. }
  339. }
  340. ctx.NotFound("Home", fmt.Errorf(ctx.Tr("units.error.no_unit_allowed_repo")))
  341. }
  342. func renderCode(ctx *context.Context) {
  343. ctx.Data["PageIsViewCode"] = true
  344. if ctx.Repo.Repository.IsEmpty {
  345. ctx.HTML(200, tplRepoEMPTY)
  346. return
  347. }
  348. title := ctx.Repo.Repository.Owner.Name + "/" + ctx.Repo.Repository.Name
  349. if len(ctx.Repo.Repository.Description) > 0 {
  350. title += ": " + ctx.Repo.Repository.Description
  351. }
  352. ctx.Data["Title"] = title
  353. ctx.Data["RequireHighlightJS"] = true
  354. branchLink := ctx.Repo.RepoLink + "/src/" + ctx.Repo.BranchNameSubURL()
  355. treeLink := branchLink
  356. rawLink := ctx.Repo.RepoLink + "/raw/" + ctx.Repo.BranchNameSubURL()
  357. if len(ctx.Repo.TreePath) > 0 {
  358. treeLink += "/" + ctx.Repo.TreePath
  359. }
  360. // Get Topics of this repo
  361. topics, err := models.FindTopics(&models.FindTopicOptions{
  362. RepoID: ctx.Repo.Repository.ID,
  363. })
  364. if err != nil {
  365. ctx.ServerError("models.FindTopics", err)
  366. return
  367. }
  368. ctx.Data["Topics"] = topics
  369. // Get current entry user currently looking at.
  370. entry, err := ctx.Repo.Commit.GetTreeEntryByPath(ctx.Repo.TreePath)
  371. if err != nil {
  372. ctx.NotFoundOrServerError("Repo.Commit.GetTreeEntryByPath", git.IsErrNotExist, err)
  373. return
  374. }
  375. if entry.IsDir() {
  376. renderDirectory(ctx, treeLink)
  377. } else {
  378. renderFile(ctx, entry, treeLink, rawLink)
  379. }
  380. if ctx.Written() {
  381. return
  382. }
  383. var treeNames []string
  384. paths := make([]string, 0, 5)
  385. if len(ctx.Repo.TreePath) > 0 {
  386. treeNames = strings.Split(ctx.Repo.TreePath, "/")
  387. for i := range treeNames {
  388. paths = append(paths, strings.Join(treeNames[:i+1], "/"))
  389. }
  390. ctx.Data["HasParentPath"] = true
  391. if len(paths)-2 >= 0 {
  392. ctx.Data["ParentPath"] = "/" + paths[len(paths)-2]
  393. }
  394. }
  395. ctx.Data["Paths"] = paths
  396. ctx.Data["TreeLink"] = treeLink
  397. ctx.Data["TreeNames"] = treeNames
  398. ctx.Data["BranchLink"] = branchLink
  399. ctx.HTML(200, tplRepoHome)
  400. }
  401. // RenderUserCards render a page show users according the input templaet
  402. func RenderUserCards(ctx *context.Context, total int, getter func(page int) ([]*models.User, error), tpl base.TplName) {
  403. page := ctx.QueryInt("page")
  404. if page <= 0 {
  405. page = 1
  406. }
  407. pager := paginater.New(total, models.ItemsPerPage, page, 5)
  408. ctx.Data["Page"] = pager
  409. items, err := getter(pager.Current())
  410. if err != nil {
  411. ctx.ServerError("getter", err)
  412. return
  413. }
  414. ctx.Data["Cards"] = items
  415. ctx.HTML(200, tpl)
  416. }
  417. // Watchers render repository's watch users
  418. func Watchers(ctx *context.Context) {
  419. ctx.Data["Title"] = ctx.Tr("repo.watchers")
  420. ctx.Data["CardsTitle"] = ctx.Tr("repo.watchers")
  421. ctx.Data["PageIsWatchers"] = true
  422. RenderUserCards(ctx, ctx.Repo.Repository.NumWatches, ctx.Repo.Repository.GetWatchers, tplWatchers)
  423. }
  424. // Stars render repository's starred users
  425. func Stars(ctx *context.Context) {
  426. ctx.Data["Title"] = ctx.Tr("repo.stargazers")
  427. ctx.Data["CardsTitle"] = ctx.Tr("repo.stargazers")
  428. ctx.Data["PageIsStargazers"] = true
  429. RenderUserCards(ctx, ctx.Repo.Repository.NumStars, ctx.Repo.Repository.GetStargazers, tplWatchers)
  430. }
  431. // Forks render repository's forked users
  432. func Forks(ctx *context.Context) {
  433. ctx.Data["Title"] = ctx.Tr("repos.forks")
  434. forks, err := ctx.Repo.Repository.GetForks()
  435. if err != nil {
  436. ctx.ServerError("GetForks", err)
  437. return
  438. }
  439. for _, fork := range forks {
  440. if err = fork.GetOwner(); err != nil {
  441. ctx.ServerError("GetOwner", err)
  442. return
  443. }
  444. }
  445. ctx.Data["Forks"] = forks
  446. ctx.HTML(200, tplForks)
  447. }