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 17 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
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
API add/generalize pagination (#9452) * paginate results * fixed deadlock * prevented breaking change * updated swagger * go fmt * fixed find topic * go mod tidy * go mod vendor with go1.13.5 * fixed repo find topics * fixed unit test * added Limit method to Engine struct; use engine variable when provided; fixed gitignore * use ItemsPerPage for default pagesize; fix GetWatchers, getOrgUsersByOrgID and GetStargazers; fix GetAllCommits headers; reverted some changed behaviors * set Page value on Home route * improved memory allocations * fixed response headers * removed logfiles * fixed import order * import order * improved swagger * added function to get models.ListOptions from context * removed pagesize diff on unit test * fixed imports * removed unnecessary struct field * fixed go fmt * scoped PR * code improvements * code improvements * go mod tidy * fixed import order * fixed commit statuses session * fixed files headers * fixed headers; added pagination for notifications * go mod tidy * go fmt * removed Private from user search options; added setting.UI.IssuePagingNum as default valeu on repo's issues list * Apply suggestions from code review Co-Authored-By: 6543 <6543@obermui.de> Co-Authored-By: zeripath <art27@cantab.net> * fixed build error * CI.restart() * fixed merge conflicts resolve * fixed conflicts resolve * improved FindTrackedTimesOptions.ToOptions() method * added backwards compatibility on ListReleases request; fixed issue tracked time ToSession * fixed build error; fixed swagger template * fixed swagger template * fixed ListReleases backwards compatibility * added page to user search route Co-authored-by: techknowlogick <matti@mdranta.net> Co-authored-by: 6543 <6543@obermui.de> Co-authored-by: zeripath <art27@cantab.net>
5 years ago
API add/generalize pagination (#9452) * paginate results * fixed deadlock * prevented breaking change * updated swagger * go fmt * fixed find topic * go mod tidy * go mod vendor with go1.13.5 * fixed repo find topics * fixed unit test * added Limit method to Engine struct; use engine variable when provided; fixed gitignore * use ItemsPerPage for default pagesize; fix GetWatchers, getOrgUsersByOrgID and GetStargazers; fix GetAllCommits headers; reverted some changed behaviors * set Page value on Home route * improved memory allocations * fixed response headers * removed logfiles * fixed import order * import order * improved swagger * added function to get models.ListOptions from context * removed pagesize diff on unit test * fixed imports * removed unnecessary struct field * fixed go fmt * scoped PR * code improvements * code improvements * go mod tidy * fixed import order * fixed commit statuses session * fixed files headers * fixed headers; added pagination for notifications * go mod tidy * go fmt * removed Private from user search options; added setting.UI.IssuePagingNum as default valeu on repo's issues list * Apply suggestions from code review Co-Authored-By: 6543 <6543@obermui.de> Co-Authored-By: zeripath <art27@cantab.net> * fixed build error * CI.restart() * fixed merge conflicts resolve * fixed conflicts resolve * improved FindTrackedTimesOptions.ToOptions() method * added backwards compatibility on ListReleases request; fixed issue tracked time ToSession * fixed build error; fixed swagger template * fixed swagger template * fixed ListReleases backwards compatibility * added page to user search route Co-authored-by: techknowlogick <matti@mdranta.net> Co-authored-by: 6543 <6543@obermui.de> Co-authored-by: zeripath <art27@cantab.net>
5 years ago
10 years ago
10 years ago
API add/generalize pagination (#9452) * paginate results * fixed deadlock * prevented breaking change * updated swagger * go fmt * fixed find topic * go mod tidy * go mod vendor with go1.13.5 * fixed repo find topics * fixed unit test * added Limit method to Engine struct; use engine variable when provided; fixed gitignore * use ItemsPerPage for default pagesize; fix GetWatchers, getOrgUsersByOrgID and GetStargazers; fix GetAllCommits headers; reverted some changed behaviors * set Page value on Home route * improved memory allocations * fixed response headers * removed logfiles * fixed import order * import order * improved swagger * added function to get models.ListOptions from context * removed pagesize diff on unit test * fixed imports * removed unnecessary struct field * fixed go fmt * scoped PR * code improvements * code improvements * go mod tidy * fixed import order * fixed commit statuses session * fixed files headers * fixed headers; added pagination for notifications * go mod tidy * go fmt * removed Private from user search options; added setting.UI.IssuePagingNum as default valeu on repo's issues list * Apply suggestions from code review Co-Authored-By: 6543 <6543@obermui.de> Co-Authored-By: zeripath <art27@cantab.net> * fixed build error * CI.restart() * fixed merge conflicts resolve * fixed conflicts resolve * improved FindTrackedTimesOptions.ToOptions() method * added backwards compatibility on ListReleases request; fixed issue tracked time ToSession * fixed build error; fixed swagger template * fixed swagger template * fixed ListReleases backwards compatibility * added page to user search route Co-authored-by: techknowlogick <matti@mdranta.net> Co-authored-by: 6543 <6543@obermui.de> Co-authored-by: zeripath <art27@cantab.net>
5 years ago
10 years ago
10 years ago
10 years ago
10 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600
  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. "net/url"
  13. "path"
  14. "strings"
  15. "code.gitea.io/gitea/models"
  16. "code.gitea.io/gitea/modules/base"
  17. "code.gitea.io/gitea/modules/cache"
  18. "code.gitea.io/gitea/modules/charset"
  19. "code.gitea.io/gitea/modules/context"
  20. "code.gitea.io/gitea/modules/git"
  21. "code.gitea.io/gitea/modules/highlight"
  22. "code.gitea.io/gitea/modules/lfs"
  23. "code.gitea.io/gitea/modules/log"
  24. "code.gitea.io/gitea/modules/markup"
  25. "code.gitea.io/gitea/modules/setting"
  26. )
  27. const (
  28. tplRepoEMPTY base.TplName = "repo/empty"
  29. tplRepoHome base.TplName = "repo/home"
  30. tplWatchers base.TplName = "repo/watchers"
  31. tplForks base.TplName = "repo/forks"
  32. tplMigrating base.TplName = "repo/migrating"
  33. )
  34. func renderDirectory(ctx *context.Context, treeLink string) {
  35. tree, err := ctx.Repo.Commit.SubTree(ctx.Repo.TreePath)
  36. if err != nil {
  37. ctx.NotFoundOrServerError("Repo.Commit.SubTree", git.IsErrNotExist, err)
  38. return
  39. }
  40. entries, err := tree.ListEntries()
  41. if err != nil {
  42. ctx.ServerError("ListEntries", err)
  43. return
  44. }
  45. entries.CustomSort(base.NaturalSortLess)
  46. var c git.LastCommitCache
  47. if setting.CacheService.LastCommit.Enabled && ctx.Repo.CommitsCount >= setting.CacheService.LastCommit.CommitsCount {
  48. c = cache.NewLastCommitCache(ctx.Repo.Repository.FullName(), ctx.Repo.GitRepo, int64(setting.CacheService.LastCommit.TTL.Seconds()))
  49. }
  50. var latestCommit *git.Commit
  51. ctx.Data["Files"], latestCommit, err = entries.GetCommitsInfo(ctx.Repo.Commit, ctx.Repo.TreePath, c)
  52. if err != nil {
  53. ctx.ServerError("GetCommitsInfo", err)
  54. return
  55. }
  56. // 3 for the extensions in exts[] in order
  57. // the last one is for a readme that doesn't
  58. // strictly match an extension
  59. var readmeFiles [4]*git.Blob
  60. var exts = []string{".md", ".txt", ""} // sorted by priority
  61. for _, entry := range entries {
  62. if entry.IsDir() {
  63. continue
  64. }
  65. for i, ext := range exts {
  66. if markup.IsReadmeFile(entry.Name(), ext) {
  67. readmeFiles[i] = entry.Blob()
  68. }
  69. }
  70. if markup.IsReadmeFile(entry.Name()) {
  71. readmeFiles[3] = entry.Blob()
  72. }
  73. }
  74. var readmeFile *git.Blob
  75. for _, f := range readmeFiles {
  76. if f != nil {
  77. readmeFile = f
  78. break
  79. }
  80. }
  81. if readmeFile != nil {
  82. ctx.Data["RawFileLink"] = ""
  83. ctx.Data["ReadmeInList"] = true
  84. ctx.Data["ReadmeExist"] = true
  85. dataRc, err := readmeFile.DataAsync()
  86. if err != nil {
  87. ctx.ServerError("Data", err)
  88. return
  89. }
  90. defer dataRc.Close()
  91. buf := make([]byte, 1024)
  92. n, _ := dataRc.Read(buf)
  93. buf = buf[:n]
  94. isTextFile := base.IsTextFile(buf)
  95. ctx.Data["FileIsText"] = isTextFile
  96. ctx.Data["FileName"] = readmeFile.Name()
  97. fileSize := int64(0)
  98. isLFSFile := false
  99. ctx.Data["IsLFSFile"] = false
  100. // FIXME: what happens when README file is an image?
  101. if isTextFile && setting.LFS.StartServer {
  102. meta := lfs.IsPointerFile(&buf)
  103. if meta != nil {
  104. meta, err = ctx.Repo.Repository.GetLFSMetaObjectByOid(meta.Oid)
  105. if err != nil && err != models.ErrLFSObjectNotExist {
  106. ctx.ServerError("GetLFSMetaObject", err)
  107. return
  108. }
  109. }
  110. if meta != nil {
  111. ctx.Data["IsLFSFile"] = true
  112. isLFSFile = true
  113. // OK read the lfs object
  114. var err error
  115. dataRc, err = lfs.ReadMetaObject(meta)
  116. if err != nil {
  117. ctx.ServerError("ReadMetaObject", err)
  118. return
  119. }
  120. defer dataRc.Close()
  121. buf = make([]byte, 1024)
  122. n, err = dataRc.Read(buf)
  123. if err != nil {
  124. ctx.ServerError("Data", err)
  125. return
  126. }
  127. buf = buf[:n]
  128. isTextFile = base.IsTextFile(buf)
  129. ctx.Data["IsTextFile"] = isTextFile
  130. fileSize = meta.Size
  131. ctx.Data["FileSize"] = meta.Size
  132. filenameBase64 := base64.RawURLEncoding.EncodeToString([]byte(readmeFile.Name()))
  133. ctx.Data["RawFileLink"] = fmt.Sprintf("%s%s.git/info/lfs/objects/%s/%s", setting.AppURL, ctx.Repo.Repository.FullName(), meta.Oid, filenameBase64)
  134. }
  135. }
  136. if !isLFSFile {
  137. fileSize = readmeFile.Size()
  138. }
  139. if isTextFile {
  140. if fileSize >= setting.UI.MaxDisplayFileSize {
  141. // Pretend that this is a normal text file to display 'This file is too large to be shown'
  142. ctx.Data["IsFileTooLarge"] = true
  143. ctx.Data["IsTextFile"] = true
  144. ctx.Data["FileSize"] = fileSize
  145. } else {
  146. d, _ := ioutil.ReadAll(dataRc)
  147. buf = charset.ToUTF8WithFallback(append(buf, d...))
  148. if markupType := markup.Type(readmeFile.Name()); markupType != "" {
  149. ctx.Data["IsMarkup"] = true
  150. ctx.Data["MarkupType"] = string(markupType)
  151. ctx.Data["FileContent"] = string(markup.Render(readmeFile.Name(), buf, treeLink, ctx.Repo.Repository.ComposeMetas()))
  152. } else {
  153. ctx.Data["IsRenderedHTML"] = true
  154. ctx.Data["FileContent"] = strings.Replace(
  155. gotemplate.HTMLEscapeString(string(buf)), "\n", `<br>`, -1,
  156. )
  157. }
  158. }
  159. }
  160. }
  161. // Show latest commit info of repository in table header,
  162. // or of directory if not in root directory.
  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. // Check LFS Lock
  235. lfsLock, err := ctx.Repo.Repository.GetTreePathLock(ctx.Repo.TreePath)
  236. ctx.Data["LFSLock"] = lfsLock
  237. if err != nil {
  238. ctx.ServerError("GetTreePathLock", err)
  239. return
  240. }
  241. if lfsLock != nil {
  242. ctx.Data["LFSLockOwner"] = lfsLock.Owner.DisplayName()
  243. ctx.Data["LFSLockHint"] = ctx.Tr("repo.editor.this_file_locked")
  244. }
  245. // Assume file is not editable first.
  246. if isLFSFile {
  247. ctx.Data["EditFileTooltip"] = ctx.Tr("repo.editor.cannot_edit_lfs_files")
  248. } else if !isTextFile {
  249. ctx.Data["EditFileTooltip"] = ctx.Tr("repo.editor.cannot_edit_non_text_files")
  250. }
  251. switch {
  252. case isTextFile:
  253. if fileSize >= setting.UI.MaxDisplayFileSize {
  254. ctx.Data["IsFileTooLarge"] = true
  255. break
  256. }
  257. d, _ := ioutil.ReadAll(dataRc)
  258. buf = charset.ToUTF8WithFallback(append(buf, d...))
  259. readmeExist := markup.IsReadmeFile(blob.Name())
  260. ctx.Data["ReadmeExist"] = readmeExist
  261. if markupType := markup.Type(blob.Name()); markupType != "" {
  262. ctx.Data["IsMarkup"] = true
  263. ctx.Data["MarkupType"] = markupType
  264. ctx.Data["FileContent"] = string(markup.Render(blob.Name(), buf, path.Dir(treeLink), ctx.Repo.Repository.ComposeMetas()))
  265. } else if readmeExist {
  266. ctx.Data["IsRenderedHTML"] = true
  267. ctx.Data["FileContent"] = strings.Replace(
  268. gotemplate.HTMLEscapeString(string(buf)), "\n", `<br>`, -1,
  269. )
  270. } else {
  271. // Building code view blocks with line number on server side.
  272. var fileContent string
  273. if content, err := charset.ToUTF8WithErr(buf); err != nil {
  274. log.Error("ToUTF8WithErr: %v", err)
  275. fileContent = string(buf)
  276. } else {
  277. fileContent = content
  278. }
  279. var output bytes.Buffer
  280. lines := strings.Split(fileContent, "\n")
  281. ctx.Data["NumLines"] = len(lines)
  282. if len(lines) == 1 && lines[0] == "" {
  283. // If the file is completely empty, we show zero lines at the line counter
  284. ctx.Data["NumLines"] = 0
  285. }
  286. ctx.Data["NumLinesSet"] = true
  287. //Remove blank line at the end of file
  288. if len(lines) > 0 && lines[len(lines)-1] == "" {
  289. lines = lines[:len(lines)-1]
  290. }
  291. for index, line := range lines {
  292. line = gotemplate.HTMLEscapeString(line)
  293. if index != len(lines)-1 {
  294. line += "\n"
  295. }
  296. output.WriteString(fmt.Sprintf(`<li class="L%d" rel="L%d">%s</li>`, index+1, index+1, line))
  297. }
  298. ctx.Data["FileContent"] = gotemplate.HTML(output.String())
  299. output.Reset()
  300. for i := 0; i < len(lines); i++ {
  301. output.WriteString(fmt.Sprintf(`<span id="L%[1]d" data-line-number="%[1]d"></span>`, i+1))
  302. }
  303. ctx.Data["LineNums"] = gotemplate.HTML(output.String())
  304. }
  305. if !isLFSFile {
  306. if ctx.Repo.CanEnableEditor() {
  307. if lfsLock != nil && lfsLock.OwnerID != ctx.User.ID {
  308. ctx.Data["CanEditFile"] = false
  309. ctx.Data["EditFileTooltip"] = ctx.Tr("repo.editor.this_file_locked")
  310. } else {
  311. ctx.Data["CanEditFile"] = true
  312. ctx.Data["EditFileTooltip"] = ctx.Tr("repo.editor.edit_this_file")
  313. }
  314. } else if !ctx.Repo.IsViewBranch {
  315. ctx.Data["EditFileTooltip"] = ctx.Tr("repo.editor.must_be_on_a_branch")
  316. } else if !ctx.Repo.CanWrite(models.UnitTypeCode) {
  317. ctx.Data["EditFileTooltip"] = ctx.Tr("repo.editor.fork_before_edit")
  318. }
  319. }
  320. case base.IsPDFFile(buf):
  321. ctx.Data["IsPDFFile"] = true
  322. case base.IsVideoFile(buf):
  323. ctx.Data["IsVideoFile"] = true
  324. case base.IsAudioFile(buf):
  325. ctx.Data["IsAudioFile"] = true
  326. case base.IsImageFile(buf):
  327. ctx.Data["IsImageFile"] = true
  328. default:
  329. if fileSize >= setting.UI.MaxDisplayFileSize {
  330. ctx.Data["IsFileTooLarge"] = true
  331. break
  332. }
  333. if markupType := markup.Type(blob.Name()); markupType != "" {
  334. d, _ := ioutil.ReadAll(dataRc)
  335. buf = append(buf, d...)
  336. ctx.Data["IsMarkup"] = true
  337. ctx.Data["MarkupType"] = markupType
  338. ctx.Data["FileContent"] = string(markup.Render(blob.Name(), buf, path.Dir(treeLink), ctx.Repo.Repository.ComposeMetas()))
  339. }
  340. }
  341. if ctx.Repo.CanEnableEditor() {
  342. if lfsLock != nil && lfsLock.OwnerID != ctx.User.ID {
  343. ctx.Data["CanDeleteFile"] = false
  344. ctx.Data["DeleteFileTooltip"] = ctx.Tr("repo.editor.this_file_locked")
  345. } else {
  346. ctx.Data["CanDeleteFile"] = true
  347. ctx.Data["DeleteFileTooltip"] = ctx.Tr("repo.editor.delete_this_file")
  348. }
  349. } else if !ctx.Repo.IsViewBranch {
  350. ctx.Data["DeleteFileTooltip"] = ctx.Tr("repo.editor.must_be_on_a_branch")
  351. } else if !ctx.Repo.CanWrite(models.UnitTypeCode) {
  352. ctx.Data["DeleteFileTooltip"] = ctx.Tr("repo.editor.must_have_write_access")
  353. }
  354. }
  355. func safeURL(address string) string {
  356. u, err := url.Parse(address)
  357. if err != nil {
  358. return address
  359. }
  360. u.User = nil
  361. return u.String()
  362. }
  363. // Home render repository home page
  364. func Home(ctx *context.Context) {
  365. if len(ctx.Repo.Units) > 0 {
  366. if ctx.Repo.Repository.IsBeingCreated() {
  367. task, err := models.GetMigratingTask(ctx.Repo.Repository.ID)
  368. if err != nil {
  369. ctx.ServerError("models.GetMigratingTask", err)
  370. return
  371. }
  372. cfg, err := task.MigrateConfig()
  373. if err != nil {
  374. ctx.ServerError("task.MigrateConfig", err)
  375. return
  376. }
  377. ctx.Data["Repo"] = ctx.Repo
  378. ctx.Data["MigrateTask"] = task
  379. ctx.Data["CloneAddr"] = safeURL(cfg.CloneAddr)
  380. ctx.HTML(200, tplMigrating)
  381. return
  382. }
  383. var firstUnit *models.Unit
  384. for _, repoUnit := range ctx.Repo.Units {
  385. if repoUnit.Type == models.UnitTypeCode {
  386. renderCode(ctx)
  387. return
  388. }
  389. unit, ok := models.Units[repoUnit.Type]
  390. if ok && (firstUnit == nil || !firstUnit.IsLessThan(unit)) {
  391. firstUnit = &unit
  392. }
  393. }
  394. if firstUnit != nil {
  395. ctx.Redirect(fmt.Sprintf("%s/%s%s", setting.AppSubURL, ctx.Repo.Repository.FullName(), firstUnit.URI))
  396. return
  397. }
  398. }
  399. ctx.NotFound("Home", fmt.Errorf(ctx.Tr("units.error.no_unit_allowed_repo")))
  400. }
  401. func renderLanguageStats(ctx *context.Context) {
  402. langs, err := ctx.Repo.Repository.GetTopLanguageStats(5)
  403. if err != nil {
  404. ctx.ServerError("Repo.GetTopLanguageStats", err)
  405. return
  406. }
  407. ctx.Data["LanguageStats"] = langs
  408. }
  409. func renderCode(ctx *context.Context) {
  410. ctx.Data["PageIsViewCode"] = true
  411. if ctx.Repo.Repository.IsEmpty {
  412. ctx.HTML(200, tplRepoEMPTY)
  413. return
  414. }
  415. title := ctx.Repo.Repository.Owner.Name + "/" + ctx.Repo.Repository.Name
  416. if len(ctx.Repo.Repository.Description) > 0 {
  417. title += ": " + ctx.Repo.Repository.Description
  418. }
  419. ctx.Data["Title"] = title
  420. ctx.Data["RequireHighlightJS"] = true
  421. branchLink := ctx.Repo.RepoLink + "/src/" + ctx.Repo.BranchNameSubURL()
  422. treeLink := branchLink
  423. rawLink := ctx.Repo.RepoLink + "/raw/" + ctx.Repo.BranchNameSubURL()
  424. if len(ctx.Repo.TreePath) > 0 {
  425. treeLink += "/" + ctx.Repo.TreePath
  426. }
  427. // Get Topics of this repo
  428. topics, err := models.FindTopics(&models.FindTopicOptions{
  429. RepoID: ctx.Repo.Repository.ID,
  430. })
  431. if err != nil {
  432. ctx.ServerError("models.FindTopics", err)
  433. return
  434. }
  435. ctx.Data["Topics"] = topics
  436. // Get current entry user currently looking at.
  437. entry, err := ctx.Repo.Commit.GetTreeEntryByPath(ctx.Repo.TreePath)
  438. if err != nil {
  439. ctx.NotFoundOrServerError("Repo.Commit.GetTreeEntryByPath", git.IsErrNotExist, err)
  440. return
  441. }
  442. renderLanguageStats(ctx)
  443. if ctx.Written() {
  444. return
  445. }
  446. if entry.IsDir() {
  447. renderDirectory(ctx, treeLink)
  448. } else {
  449. renderFile(ctx, entry, treeLink, rawLink)
  450. }
  451. if ctx.Written() {
  452. return
  453. }
  454. var treeNames []string
  455. paths := make([]string, 0, 5)
  456. if len(ctx.Repo.TreePath) > 0 {
  457. treeNames = strings.Split(ctx.Repo.TreePath, "/")
  458. for i := range treeNames {
  459. paths = append(paths, strings.Join(treeNames[:i+1], "/"))
  460. }
  461. ctx.Data["HasParentPath"] = true
  462. if len(paths)-2 >= 0 {
  463. ctx.Data["ParentPath"] = "/" + paths[len(paths)-2]
  464. }
  465. }
  466. ctx.Data["Paths"] = paths
  467. ctx.Data["TreeLink"] = treeLink
  468. ctx.Data["TreeNames"] = treeNames
  469. ctx.Data["BranchLink"] = branchLink
  470. ctx.HTML(200, tplRepoHome)
  471. }
  472. // RenderUserCards render a page show users according the input templaet
  473. func RenderUserCards(ctx *context.Context, total int, getter func(opts models.ListOptions) ([]*models.User, error), tpl base.TplName) {
  474. page := ctx.QueryInt("page")
  475. if page <= 0 {
  476. page = 1
  477. }
  478. pager := context.NewPagination(total, models.ItemsPerPage, page, 5)
  479. ctx.Data["Page"] = pager
  480. items, err := getter(models.ListOptions{Page: pager.Paginater.Current()})
  481. if err != nil {
  482. ctx.ServerError("getter", err)
  483. return
  484. }
  485. ctx.Data["Cards"] = items
  486. ctx.HTML(200, tpl)
  487. }
  488. // Watchers render repository's watch users
  489. func Watchers(ctx *context.Context) {
  490. ctx.Data["Title"] = ctx.Tr("repo.watchers")
  491. ctx.Data["CardsTitle"] = ctx.Tr("repo.watchers")
  492. ctx.Data["PageIsWatchers"] = true
  493. RenderUserCards(ctx, ctx.Repo.Repository.NumWatches, ctx.Repo.Repository.GetWatchers, tplWatchers)
  494. }
  495. // Stars render repository's starred users
  496. func Stars(ctx *context.Context) {
  497. ctx.Data["Title"] = ctx.Tr("repo.stargazers")
  498. ctx.Data["CardsTitle"] = ctx.Tr("repo.stargazers")
  499. ctx.Data["PageIsStargazers"] = true
  500. RenderUserCards(ctx, ctx.Repo.Repository.NumStars, ctx.Repo.Repository.GetStargazers, tplWatchers)
  501. }
  502. // Forks render repository's forked users
  503. func Forks(ctx *context.Context) {
  504. ctx.Data["Title"] = ctx.Tr("repos.forks")
  505. forks, err := ctx.Repo.Repository.GetForks(models.ListOptions{})
  506. if err != nil {
  507. ctx.ServerError("GetForks", err)
  508. return
  509. }
  510. for _, fork := range forks {
  511. if err = fork.GetOwner(); err != nil {
  512. ctx.ServerError("GetOwner", err)
  513. return
  514. }
  515. }
  516. ctx.Data["Forks"] = forks
  517. ctx.HTML(200, tplForks)
  518. }