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