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.

360 lines
10 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
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
9 years ago
9 years ago
9 years ago
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package repo
  5. import (
  6. "bytes"
  7. "encoding/base64"
  8. "fmt"
  9. gotemplate "html/template"
  10. "io/ioutil"
  11. "path"
  12. "strconv"
  13. "strings"
  14. "code.gitea.io/git"
  15. "code.gitea.io/gitea/models"
  16. "code.gitea.io/gitea/modules/base"
  17. "code.gitea.io/gitea/modules/context"
  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/markdown"
  22. "code.gitea.io/gitea/modules/setting"
  23. "code.gitea.io/gitea/modules/templates"
  24. "github.com/Unknwon/paginater"
  25. )
  26. const (
  27. tplRepoBARE base.TplName = "repo/bare"
  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.Handle(500, "ListEntries", err)
  41. return
  42. }
  43. entries.Sort()
  44. ctx.Data["Files"], err = entries.GetCommitsInfo(ctx.Repo.Commit, ctx.Repo.TreePath)
  45. if err != nil {
  46. ctx.Handle(500, "GetCommitsInfo", err)
  47. return
  48. }
  49. var readmeFile *git.Blob
  50. for _, entry := range entries {
  51. if entry.IsDir() || !markdown.IsReadmeFile(entry.Name()) {
  52. continue
  53. }
  54. // TODO: collect all possible README files and show with priority.
  55. readmeFile = entry.Blob()
  56. break
  57. }
  58. if readmeFile != nil {
  59. ctx.Data["RawFileLink"] = ""
  60. ctx.Data["ReadmeInList"] = true
  61. ctx.Data["ReadmeExist"] = true
  62. dataRc, err := readmeFile.Data()
  63. if err != nil {
  64. ctx.Handle(500, "Data", err)
  65. return
  66. }
  67. buf := make([]byte, 1024)
  68. n, _ := dataRc.Read(buf)
  69. buf = buf[:n]
  70. isTextFile := base.IsTextFile(buf)
  71. ctx.Data["FileIsText"] = isTextFile
  72. ctx.Data["FileName"] = readmeFile.Name()
  73. // FIXME: what happens when README file is an image?
  74. if isTextFile {
  75. d, _ := ioutil.ReadAll(dataRc)
  76. buf = append(buf, d...)
  77. switch {
  78. case markdown.IsMarkdownFile(readmeFile.Name()):
  79. ctx.Data["IsMarkdown"] = true
  80. buf = markdown.Render(buf, treeLink, ctx.Repo.Repository.ComposeMetas())
  81. default:
  82. // FIXME This is the only way to show non-markdown files
  83. // instead of a broken "View Raw" link
  84. ctx.Data["IsMarkdown"] = true
  85. buf = bytes.Replace(buf, []byte("\n"), []byte(`<br>`), -1)
  86. }
  87. ctx.Data["FileContent"] = string(buf)
  88. }
  89. }
  90. // Show latest commit info of repository in table header,
  91. // or of directory if not in root directory.
  92. latestCommit := ctx.Repo.Commit
  93. if len(ctx.Repo.TreePath) > 0 {
  94. latestCommit, err = ctx.Repo.Commit.GetCommitByPath(ctx.Repo.TreePath)
  95. if err != nil {
  96. ctx.Handle(500, "GetCommitByPath", err)
  97. return
  98. }
  99. }
  100. ctx.Data["LatestCommit"] = latestCommit
  101. ctx.Data["LatestCommitUser"] = models.ValidateCommitWithEmail(latestCommit)
  102. // Check permission to add or upload new file.
  103. if ctx.Repo.IsWriter() && ctx.Repo.IsViewBranch {
  104. ctx.Data["CanAddFile"] = true
  105. ctx.Data["CanUploadFile"] = setting.Repository.Upload.Enabled
  106. }
  107. }
  108. func renderFile(ctx *context.Context, entry *git.TreeEntry, treeLink, rawLink string) {
  109. ctx.Data["IsViewFile"] = true
  110. blob := entry.Blob()
  111. dataRc, err := blob.Data()
  112. if err != nil {
  113. ctx.Handle(500, "Data", err)
  114. return
  115. }
  116. ctx.Data["FileSize"] = blob.Size()
  117. ctx.Data["FileName"] = blob.Name()
  118. ctx.Data["HighlightClass"] = highlight.FileNameToHighlightClass(blob.Name())
  119. ctx.Data["RawFileLink"] = rawLink + "/" + ctx.Repo.TreePath
  120. buf := make([]byte, 1024)
  121. n, _ := dataRc.Read(buf)
  122. buf = buf[:n]
  123. isTextFile := base.IsTextFile(buf)
  124. ctx.Data["IsTextFile"] = isTextFile
  125. //Check for LFS meta file
  126. if isTextFile && setting.LFS.StartServer {
  127. headString := string(buf)
  128. if strings.HasPrefix(headString, models.LFSMetaFileIdentifier) {
  129. splitLines := strings.Split(headString, "\n")
  130. if len(splitLines) >= 3 {
  131. oid := strings.TrimPrefix(splitLines[1], models.LFSMetaFileOidPrefix)
  132. size, err := strconv.ParseInt(strings.TrimPrefix(splitLines[2], "size "), 10, 64)
  133. if len(oid) == 64 && err == nil {
  134. contentStore := &lfs.ContentStore{BasePath: setting.LFS.ContentPath}
  135. meta := &models.LFSMetaObject{Oid: oid}
  136. if contentStore.Exists(meta) {
  137. ctx.Data["IsTextFile"] = false
  138. isTextFile = false
  139. ctx.Data["IsLFSFile"] = true
  140. ctx.Data["FileSize"] = size
  141. filenameBase64 := base64.RawURLEncoding.EncodeToString([]byte(blob.Name()))
  142. ctx.Data["RawFileLink"] = fmt.Sprintf("%s%s/info/lfs/objects/%s/%s", setting.AppURL, ctx.Repo.Repository.FullName(), oid, filenameBase64)
  143. }
  144. }
  145. }
  146. }
  147. }
  148. // Assume file is not editable first.
  149. if !isTextFile {
  150. ctx.Data["EditFileTooltip"] = ctx.Tr("repo.editor.cannot_edit_non_text_files")
  151. }
  152. switch {
  153. case isTextFile:
  154. if blob.Size() >= setting.UI.MaxDisplayFileSize {
  155. ctx.Data["IsFileTooLarge"] = true
  156. break
  157. }
  158. d, _ := ioutil.ReadAll(dataRc)
  159. buf = append(buf, d...)
  160. isMarkdown := markdown.IsMarkdownFile(blob.Name())
  161. ctx.Data["IsMarkdown"] = isMarkdown
  162. readmeExist := isMarkdown || markdown.IsReadmeFile(blob.Name())
  163. ctx.Data["ReadmeExist"] = readmeExist
  164. if readmeExist && isMarkdown {
  165. ctx.Data["FileContent"] = string(markdown.Render(buf, path.Dir(treeLink), ctx.Repo.Repository.ComposeMetas()))
  166. } else {
  167. // Building code view blocks with line number on server side.
  168. var fileContent string
  169. if content, err := templates.ToUTF8WithErr(buf); err != nil {
  170. if err != nil {
  171. log.Error(4, "ToUTF8WithErr: %v", err)
  172. }
  173. fileContent = string(buf)
  174. } else {
  175. fileContent = content
  176. }
  177. var output bytes.Buffer
  178. lines := strings.Split(fileContent, "\n")
  179. for index, line := range lines {
  180. output.WriteString(fmt.Sprintf(`<li class="L%d" rel="L%d">%s</li>`, index+1, index+1, gotemplate.HTMLEscapeString(line)) + "\n")
  181. }
  182. ctx.Data["FileContent"] = gotemplate.HTML(output.String())
  183. output.Reset()
  184. for i := 0; i < len(lines); i++ {
  185. output.WriteString(fmt.Sprintf(`<span id="L%d">%d</span>`, i+1, i+1))
  186. }
  187. ctx.Data["LineNums"] = gotemplate.HTML(output.String())
  188. }
  189. if ctx.Repo.CanEnableEditor() {
  190. ctx.Data["CanEditFile"] = true
  191. ctx.Data["EditFileTooltip"] = ctx.Tr("repo.editor.edit_this_file")
  192. } else if !ctx.Repo.IsViewBranch {
  193. ctx.Data["EditFileTooltip"] = ctx.Tr("repo.editor.must_be_on_a_branch")
  194. } else if !ctx.Repo.IsWriter() {
  195. ctx.Data["EditFileTooltip"] = ctx.Tr("repo.editor.fork_before_edit")
  196. }
  197. case base.IsPDFFile(buf):
  198. ctx.Data["IsPDFFile"] = true
  199. case base.IsVideoFile(buf):
  200. ctx.Data["IsVideoFile"] = true
  201. case base.IsImageFile(buf):
  202. ctx.Data["IsImageFile"] = true
  203. }
  204. if ctx.Repo.CanEnableEditor() {
  205. ctx.Data["CanDeleteFile"] = true
  206. ctx.Data["DeleteFileTooltip"] = ctx.Tr("repo.editor.delete_this_file")
  207. } else if !ctx.Repo.IsViewBranch {
  208. ctx.Data["DeleteFileTooltip"] = ctx.Tr("repo.editor.must_be_on_a_branch")
  209. } else if !ctx.Repo.IsWriter() {
  210. ctx.Data["DeleteFileTooltip"] = ctx.Tr("repo.editor.must_have_write_access")
  211. }
  212. }
  213. // Home render repository home page
  214. func Home(ctx *context.Context) {
  215. ctx.Data["PageIsViewCode"] = true
  216. if ctx.Repo.Repository.IsBare {
  217. ctx.HTML(200, tplRepoBARE)
  218. return
  219. }
  220. title := ctx.Repo.Repository.Owner.Name + "/" + ctx.Repo.Repository.Name
  221. if len(ctx.Repo.Repository.Description) > 0 {
  222. title += ": " + ctx.Repo.Repository.Description
  223. }
  224. ctx.Data["Title"] = title
  225. ctx.Data["RequireHighlightJS"] = true
  226. branchLink := ctx.Repo.RepoLink + "/src/" + ctx.Repo.BranchName
  227. treeLink := branchLink
  228. rawLink := ctx.Repo.RepoLink + "/raw/" + ctx.Repo.BranchName
  229. if len(ctx.Repo.TreePath) > 0 {
  230. treeLink += "/" + ctx.Repo.TreePath
  231. }
  232. // Get current entry user currently looking at.
  233. entry, err := ctx.Repo.Commit.GetTreeEntryByPath(ctx.Repo.TreePath)
  234. if err != nil {
  235. ctx.NotFoundOrServerError("Repo.Commit.GetTreeEntryByPath", git.IsErrNotExist, err)
  236. return
  237. }
  238. if entry.IsDir() {
  239. renderDirectory(ctx, treeLink)
  240. } else {
  241. renderFile(ctx, entry, treeLink, rawLink)
  242. }
  243. if ctx.Written() {
  244. return
  245. }
  246. var treeNames []string
  247. paths := make([]string, 0, 5)
  248. if len(ctx.Repo.TreePath) > 0 {
  249. treeNames = strings.Split(ctx.Repo.TreePath, "/")
  250. for i := range treeNames {
  251. paths = append(paths, strings.Join(treeNames[:i+1], "/"))
  252. }
  253. ctx.Data["HasParentPath"] = true
  254. if len(paths)-2 >= 0 {
  255. ctx.Data["ParentPath"] = "/" + paths[len(paths)-2]
  256. }
  257. }
  258. ctx.Data["Paths"] = paths
  259. ctx.Data["TreeLink"] = treeLink
  260. ctx.Data["TreeNames"] = treeNames
  261. ctx.Data["BranchLink"] = branchLink
  262. ctx.HTML(200, tplRepoHome)
  263. }
  264. // RenderUserCards render a page show users according the input templaet
  265. func RenderUserCards(ctx *context.Context, total int, getter func(page int) ([]*models.User, error), tpl base.TplName) {
  266. page := ctx.QueryInt("page")
  267. if page <= 0 {
  268. page = 1
  269. }
  270. pager := paginater.New(total, models.ItemsPerPage, page, 5)
  271. ctx.Data["Page"] = pager
  272. items, err := getter(pager.Current())
  273. if err != nil {
  274. ctx.Handle(500, "getter", err)
  275. return
  276. }
  277. ctx.Data["Cards"] = items
  278. ctx.HTML(200, tpl)
  279. }
  280. // Watchers render repository's watch users
  281. func Watchers(ctx *context.Context) {
  282. ctx.Data["Title"] = ctx.Tr("repo.watchers")
  283. ctx.Data["CardsTitle"] = ctx.Tr("repo.watchers")
  284. ctx.Data["PageIsWatchers"] = true
  285. RenderUserCards(ctx, ctx.Repo.Repository.NumWatches, ctx.Repo.Repository.GetWatchers, tplWatchers)
  286. }
  287. // Stars render repository's starred users
  288. func Stars(ctx *context.Context) {
  289. ctx.Data["Title"] = ctx.Tr("repo.stargazers")
  290. ctx.Data["CardsTitle"] = ctx.Tr("repo.stargazers")
  291. ctx.Data["PageIsStargazers"] = true
  292. RenderUserCards(ctx, ctx.Repo.Repository.NumStars, ctx.Repo.Repository.GetStargazers, tplWatchers)
  293. }
  294. // Forks render repository's forked users
  295. func Forks(ctx *context.Context) {
  296. ctx.Data["Title"] = ctx.Tr("repos.forks")
  297. forks, err := ctx.Repo.Repository.GetForks()
  298. if err != nil {
  299. ctx.Handle(500, "GetForks", err)
  300. return
  301. }
  302. for _, fork := range forks {
  303. if err = fork.GetOwner(); err != nil {
  304. ctx.Handle(500, "GetOwner", err)
  305. return
  306. }
  307. }
  308. ctx.Data["Forks"] = forks
  309. ctx.HTML(200, tplForks)
  310. }