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 26 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
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
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
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
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
9 years ago
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
9 years ago
9 years ago
9 years ago
9 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890
  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. "code.gitea.io/gitea/modules/options"
  9. "encoding/base64"
  10. "fmt"
  11. gotemplate "html/template"
  12. "io/ioutil"
  13. "net/url"
  14. "path"
  15. "strings"
  16. "time"
  17. "code.gitea.io/gitea/models"
  18. "code.gitea.io/gitea/modules/base"
  19. "code.gitea.io/gitea/modules/cache"
  20. "code.gitea.io/gitea/modules/charset"
  21. "code.gitea.io/gitea/modules/context"
  22. "code.gitea.io/gitea/modules/git"
  23. "code.gitea.io/gitea/modules/highlight"
  24. "code.gitea.io/gitea/modules/lfs"
  25. "code.gitea.io/gitea/modules/log"
  26. "code.gitea.io/gitea/modules/markup"
  27. "code.gitea.io/gitea/modules/setting"
  28. )
  29. const (
  30. tplRepoEMPTY base.TplName = "repo/empty"
  31. tplRepoHome base.TplName = "repo/home"
  32. tplWatchers base.TplName = "repo/watchers"
  33. tplForks base.TplName = "repo/forks"
  34. tplMigrating base.TplName = "repo/migrating"
  35. )
  36. type namedBlob struct {
  37. name string
  38. isSymlink bool
  39. blob *git.Blob
  40. }
  41. // FIXME: There has to be a more efficient way of doing this
  42. func getReadmeFileFromPath(commit *git.Commit, treePath string) (*namedBlob, error) {
  43. tree, err := commit.SubTree(treePath)
  44. if err != nil {
  45. return nil, err
  46. }
  47. entries, err := tree.ListEntries()
  48. if err != nil {
  49. return nil, err
  50. }
  51. var readmeFiles [4]*namedBlob
  52. var exts = []string{".md", ".txt", ""} // sorted by priority
  53. for _, entry := range entries {
  54. if entry.IsDir() {
  55. continue
  56. }
  57. for i, ext := range exts {
  58. if markup.IsReadmeFile(entry.Name(), ext) {
  59. if readmeFiles[i] == nil || base.NaturalSortLess(readmeFiles[i].name, entry.Blob().Name()) {
  60. name := entry.Name()
  61. isSymlink := entry.IsLink()
  62. target := entry
  63. if isSymlink {
  64. target, err = entry.FollowLinks()
  65. if err != nil && !git.IsErrBadLink(err) {
  66. return nil, err
  67. }
  68. }
  69. if target != nil && (target.IsExecutable() || target.IsRegular()) {
  70. readmeFiles[i] = &namedBlob{
  71. name,
  72. isSymlink,
  73. target.Blob(),
  74. }
  75. }
  76. }
  77. }
  78. }
  79. if markup.IsReadmeFile(entry.Name()) {
  80. if readmeFiles[3] == nil || base.NaturalSortLess(readmeFiles[3].name, entry.Blob().Name()) {
  81. name := entry.Name()
  82. isSymlink := entry.IsLink()
  83. if isSymlink {
  84. entry, err = entry.FollowLinks()
  85. if err != nil && !git.IsErrBadLink(err) {
  86. return nil, err
  87. }
  88. }
  89. if entry != nil && (entry.IsExecutable() || entry.IsRegular()) {
  90. readmeFiles[3] = &namedBlob{
  91. name,
  92. isSymlink,
  93. entry.Blob(),
  94. }
  95. }
  96. }
  97. }
  98. }
  99. var readmeFile *namedBlob
  100. for _, f := range readmeFiles {
  101. if f != nil {
  102. readmeFile = f
  103. break
  104. }
  105. }
  106. return readmeFile, nil
  107. }
  108. func renderDirectory(ctx *context.Context, treeLink string) {
  109. tree, err := ctx.Repo.Commit.SubTree(ctx.Repo.TreePath)
  110. if err != nil {
  111. ctx.NotFoundOrServerError("Repo.Commit.SubTree", git.IsErrNotExist, err)
  112. return
  113. }
  114. entries, err := tree.ListEntries()
  115. if err != nil {
  116. ctx.ServerError("ListEntries", err)
  117. return
  118. }
  119. entries.CustomSort(base.NaturalSortLess)
  120. var c git.LastCommitCache
  121. if setting.CacheService.LastCommit.Enabled && ctx.Repo.CommitsCount >= setting.CacheService.LastCommit.CommitsCount {
  122. c = cache.NewLastCommitCache(ctx.Repo.Repository.FullName(), ctx.Repo.GitRepo, int64(setting.CacheService.LastCommit.TTL.Seconds()))
  123. }
  124. var latestCommit *git.Commit
  125. ctx.Data["Files"], latestCommit, err = entries.GetCommitsInfo(ctx.Repo.Commit, ctx.Repo.TreePath, c)
  126. if err != nil {
  127. ctx.ServerError("GetCommitsInfo", err)
  128. return
  129. }
  130. // 3 for the extensions in exts[] in order
  131. // the last one is for a readme that doesn't
  132. // strictly match an extension
  133. var readmeFiles [4]*namedBlob
  134. var docsEntries [3]*git.TreeEntry
  135. var exts = []string{".md", ".txt", ""} // sorted by priority
  136. for _, entry := range entries {
  137. if entry.IsDir() {
  138. lowerName := strings.ToLower(entry.Name())
  139. switch lowerName {
  140. case "docs":
  141. if entry.Name() == "docs" || docsEntries[0] == nil {
  142. docsEntries[0] = entry
  143. }
  144. case ".gitea":
  145. if entry.Name() == ".gitea" || docsEntries[1] == nil {
  146. docsEntries[1] = entry
  147. }
  148. case ".github":
  149. if entry.Name() == ".github" || docsEntries[2] == nil {
  150. docsEntries[2] = entry
  151. }
  152. }
  153. continue
  154. }
  155. for i, ext := range exts {
  156. if markup.IsReadmeFile(entry.Name(), ext) {
  157. log.Debug("%s", entry.Name())
  158. name := entry.Name()
  159. isSymlink := entry.IsLink()
  160. target := entry
  161. if isSymlink {
  162. target, err = entry.FollowLinks()
  163. if err != nil && !git.IsErrBadLink(err) {
  164. ctx.ServerError("FollowLinks", err)
  165. return
  166. }
  167. }
  168. log.Debug("%t", target == nil)
  169. if target != nil && (target.IsExecutable() || target.IsRegular()) {
  170. readmeFiles[i] = &namedBlob{
  171. name,
  172. isSymlink,
  173. target.Blob(),
  174. }
  175. }
  176. }
  177. }
  178. if markup.IsReadmeFile(entry.Name()) {
  179. name := entry.Name()
  180. isSymlink := entry.IsLink()
  181. if isSymlink {
  182. entry, err = entry.FollowLinks()
  183. if err != nil && !git.IsErrBadLink(err) {
  184. ctx.ServerError("FollowLinks", err)
  185. return
  186. }
  187. }
  188. if entry != nil && (entry.IsExecutable() || entry.IsRegular()) {
  189. readmeFiles[3] = &namedBlob{
  190. name,
  191. isSymlink,
  192. entry.Blob(),
  193. }
  194. }
  195. }
  196. }
  197. var readmeFile *namedBlob
  198. readmeTreelink := treeLink
  199. for _, f := range readmeFiles {
  200. if f != nil {
  201. readmeFile = f
  202. break
  203. }
  204. }
  205. if ctx.Repo.TreePath == "" && readmeFile == nil {
  206. for _, entry := range docsEntries {
  207. if entry == nil {
  208. continue
  209. }
  210. readmeFile, err = getReadmeFileFromPath(ctx.Repo.Commit, entry.GetSubJumpablePathName())
  211. if err != nil {
  212. ctx.ServerError("getReadmeFileFromPath", err)
  213. return
  214. }
  215. if readmeFile != nil {
  216. readmeFile.name = entry.Name() + "/" + readmeFile.name
  217. readmeTreelink = treeLink + "/" + entry.GetSubJumpablePathName()
  218. break
  219. }
  220. }
  221. }
  222. if readmeFile != nil {
  223. ctx.Data["RawFileLink"] = ""
  224. ctx.Data["ReadmeInList"] = true
  225. ctx.Data["ReadmeExist"] = true
  226. ctx.Data["FileIsSymlink"] = readmeFile.isSymlink
  227. dataRc, err := readmeFile.blob.DataAsync()
  228. if err != nil {
  229. ctx.ServerError("Data", err)
  230. return
  231. }
  232. defer dataRc.Close()
  233. buf := make([]byte, 1024)
  234. n, _ := dataRc.Read(buf)
  235. buf = buf[:n]
  236. isTextFile := base.IsTextFile(buf)
  237. ctx.Data["FileIsText"] = isTextFile
  238. ctx.Data["FileName"] = readmeFile.name
  239. fileSize := int64(0)
  240. isLFSFile := false
  241. ctx.Data["IsLFSFile"] = false
  242. // FIXME: what happens when README file is an image?
  243. if isTextFile && setting.LFS.StartServer {
  244. meta := lfs.IsPointerFile(&buf)
  245. if meta != nil {
  246. meta, err = ctx.Repo.Repository.GetLFSMetaObjectByOid(meta.Oid)
  247. if err != nil && err != models.ErrLFSObjectNotExist {
  248. ctx.ServerError("GetLFSMetaObject", err)
  249. return
  250. }
  251. }
  252. if meta != nil {
  253. ctx.Data["IsLFSFile"] = true
  254. isLFSFile = true
  255. // OK read the lfs object
  256. var err error
  257. dataRc, err = lfs.ReadMetaObject(meta)
  258. if err != nil {
  259. ctx.ServerError("ReadMetaObject", err)
  260. return
  261. }
  262. defer dataRc.Close()
  263. buf = make([]byte, 1024)
  264. n, err = dataRc.Read(buf)
  265. if err != nil {
  266. ctx.ServerError("Data", err)
  267. return
  268. }
  269. buf = buf[:n]
  270. isTextFile = base.IsTextFile(buf)
  271. ctx.Data["IsTextFile"] = isTextFile
  272. fileSize = meta.Size
  273. ctx.Data["FileSize"] = meta.Size
  274. filenameBase64 := base64.RawURLEncoding.EncodeToString([]byte(readmeFile.name))
  275. ctx.Data["RawFileLink"] = fmt.Sprintf("%s%s.git/info/lfs/objects/%s/%s", setting.AppURL, ctx.Repo.Repository.FullName(), meta.Oid, filenameBase64)
  276. }
  277. }
  278. if !isLFSFile {
  279. fileSize = readmeFile.blob.Size()
  280. }
  281. if isTextFile {
  282. if fileSize >= setting.UI.MaxDisplayFileSize {
  283. // Pretend that this is a normal text file to display 'This file is too large to be shown'
  284. ctx.Data["IsFileTooLarge"] = true
  285. ctx.Data["IsTextFile"] = true
  286. ctx.Data["FileSize"] = fileSize
  287. } else {
  288. d, _ := ioutil.ReadAll(dataRc)
  289. buf = charset.ToUTF8WithFallback(append(buf, d...))
  290. if markupType := markup.Type(readmeFile.name); markupType != "" {
  291. ctx.Data["IsMarkup"] = true
  292. ctx.Data["MarkupType"] = string(markupType)
  293. ctx.Data["FileContent"] = string(markup.Render(readmeFile.name, buf, readmeTreelink, ctx.Repo.Repository.ComposeMetas()))
  294. } else {
  295. ctx.Data["IsRenderedHTML"] = true
  296. ctx.Data["FileContent"] = strings.Replace(
  297. gotemplate.HTMLEscapeString(string(buf)), "\n", `<br>`, -1,
  298. )
  299. }
  300. }
  301. }
  302. }
  303. // Show latest commit info of repository in table header,
  304. // or of directory if not in root directory.
  305. ctx.Data["LatestCommit"] = latestCommit
  306. verification := models.ParseCommitWithSignature(latestCommit)
  307. if err := models.CalculateTrustStatus(verification, ctx.Repo.Repository, nil); err != nil {
  308. ctx.ServerError("CalculateTrustStatus", err)
  309. return
  310. }
  311. ctx.Data["LatestCommitVerification"] = verification
  312. ctx.Data["LatestCommitUser"] = models.ValidateCommitWithEmail(latestCommit)
  313. statuses, err := models.GetLatestCommitStatus(ctx.Repo.Repository, ctx.Repo.Commit.ID.String(), 0)
  314. if err != nil {
  315. log.Error("GetLatestCommitStatus: %v", err)
  316. }
  317. ctx.Data["LatestCommitStatus"] = models.CalcCommitStatus(statuses)
  318. // Check permission to add or upload new file.
  319. if ctx.Repo.CanWrite(models.UnitTypeCode) && ctx.Repo.IsViewBranch {
  320. ctx.Data["CanAddFile"] = !ctx.Repo.Repository.IsArchived
  321. ctx.Data["CanUploadFile"] = setting.Repository.Upload.Enabled && !ctx.Repo.Repository.IsArchived
  322. }
  323. }
  324. func renderFile(ctx *context.Context, entry *git.TreeEntry, treeLink, rawLink string) {
  325. ctx.Data["IsViewFile"] = true
  326. blob := entry.Blob()
  327. dataRc, err := blob.DataAsync()
  328. if err != nil {
  329. ctx.ServerError("DataAsync", err)
  330. return
  331. }
  332. defer dataRc.Close()
  333. ctx.Data["Title"] = ctx.Data["Title"].(string) + " - " + ctx.Repo.TreePath + " at " + ctx.Repo.BranchName
  334. fileSize := blob.Size()
  335. ctx.Data["FileIsSymlink"] = entry.IsLink()
  336. ctx.Data["FileSize"] = fileSize
  337. ctx.Data["FileName"] = blob.Name()
  338. ctx.Data["HighlightClass"] = highlight.FileNameToHighlightClass(blob.Name())
  339. ctx.Data["RawFileLink"] = rawLink + "/" + ctx.Repo.TreePath
  340. buf := make([]byte, 1024)
  341. n, _ := dataRc.Read(buf)
  342. buf = buf[:n]
  343. isTextFile := base.IsTextFile(buf)
  344. isLFSFile := false
  345. ctx.Data["IsTextFile"] = isTextFile
  346. //Check for LFS meta file
  347. if isTextFile && setting.LFS.StartServer {
  348. meta := lfs.IsPointerFile(&buf)
  349. if meta != nil {
  350. meta, err = ctx.Repo.Repository.GetLFSMetaObjectByOid(meta.Oid)
  351. if err != nil && err != models.ErrLFSObjectNotExist {
  352. ctx.ServerError("GetLFSMetaObject", err)
  353. return
  354. }
  355. }
  356. if meta != nil {
  357. ctx.Data["IsLFSFile"] = true
  358. isLFSFile = true
  359. // OK read the lfs object
  360. var err error
  361. dataRc, err = lfs.ReadMetaObject(meta)
  362. if err != nil {
  363. ctx.ServerError("ReadMetaObject", err)
  364. return
  365. }
  366. defer dataRc.Close()
  367. buf = make([]byte, 1024)
  368. n, err = dataRc.Read(buf)
  369. if err != nil {
  370. ctx.ServerError("Data", err)
  371. return
  372. }
  373. buf = buf[:n]
  374. isTextFile = base.IsTextFile(buf)
  375. ctx.Data["IsTextFile"] = isTextFile
  376. fileSize = meta.Size
  377. ctx.Data["FileSize"] = meta.Size
  378. filenameBase64 := base64.RawURLEncoding.EncodeToString([]byte(blob.Name()))
  379. ctx.Data["RawFileLink"] = fmt.Sprintf("%s%s.git/info/lfs/objects/%s/%s", setting.AppURL, ctx.Repo.Repository.FullName(), meta.Oid, filenameBase64)
  380. }
  381. }
  382. // Check LFS Lock
  383. lfsLock, err := ctx.Repo.Repository.GetTreePathLock(ctx.Repo.TreePath)
  384. ctx.Data["LFSLock"] = lfsLock
  385. if err != nil {
  386. ctx.ServerError("GetTreePathLock", err)
  387. return
  388. }
  389. if lfsLock != nil {
  390. ctx.Data["LFSLockOwner"] = lfsLock.Owner.DisplayName()
  391. ctx.Data["LFSLockHint"] = ctx.Tr("repo.editor.this_file_locked")
  392. }
  393. // Assume file is not editable first.
  394. if isLFSFile {
  395. ctx.Data["EditFileTooltip"] = ctx.Tr("repo.editor.cannot_edit_lfs_files")
  396. } else if !isTextFile {
  397. ctx.Data["EditFileTooltip"] = ctx.Tr("repo.editor.cannot_edit_non_text_files")
  398. }
  399. switch {
  400. case isTextFile:
  401. if fileSize >= setting.UI.MaxDisplayFileSize {
  402. ctx.Data["IsFileTooLarge"] = true
  403. break
  404. }
  405. d, _ := ioutil.ReadAll(dataRc)
  406. buf = charset.ToUTF8WithFallback(append(buf, d...))
  407. readmeExist := markup.IsReadmeFile(blob.Name())
  408. ctx.Data["ReadmeExist"] = readmeExist
  409. if markupType := markup.Type(blob.Name()); markupType != "" {
  410. ctx.Data["IsMarkup"] = true
  411. ctx.Data["MarkupType"] = markupType
  412. ctx.Data["FileContent"] = string(markup.Render(blob.Name(), buf, path.Dir(treeLink), ctx.Repo.Repository.ComposeMetas()))
  413. } else if readmeExist {
  414. ctx.Data["IsRenderedHTML"] = true
  415. ctx.Data["FileContent"] = strings.Replace(
  416. gotemplate.HTMLEscapeString(string(buf)), "\n", `<br>`, -1,
  417. )
  418. } else {
  419. // Building code view blocks with line number on server side.
  420. var fileContent string
  421. if content, err := charset.ToUTF8WithErr(buf); err != nil {
  422. log.Error("ToUTF8WithErr: %v", err)
  423. fileContent = string(buf)
  424. } else {
  425. fileContent = content
  426. }
  427. var output bytes.Buffer
  428. lines := strings.Split(fileContent, "\n")
  429. ctx.Data["NumLines"] = len(lines)
  430. if len(lines) == 1 && lines[0] == "" {
  431. // If the file is completely empty, we show zero lines at the line counter
  432. ctx.Data["NumLines"] = 0
  433. }
  434. ctx.Data["NumLinesSet"] = true
  435. //Remove blank line at the end of file
  436. if len(lines) > 0 && lines[len(lines)-1] == "" {
  437. lines = lines[:len(lines)-1]
  438. }
  439. for index, line := range lines {
  440. line = gotemplate.HTMLEscapeString(line)
  441. if index != len(lines)-1 {
  442. line += "\n"
  443. }
  444. output.WriteString(fmt.Sprintf(`<li class="L%d" rel="L%d">%s</li>`, index+1, index+1, line))
  445. }
  446. ctx.Data["FileContent"] = gotemplate.HTML(output.String())
  447. output.Reset()
  448. for i := 0; i < len(lines); i++ {
  449. output.WriteString(fmt.Sprintf(`<span id="L%[1]d" data-line-number="%[1]d"></span>`, i+1))
  450. }
  451. ctx.Data["LineNums"] = gotemplate.HTML(output.String())
  452. }
  453. if !isLFSFile {
  454. if ctx.Repo.CanEnableEditor() {
  455. if lfsLock != nil && lfsLock.OwnerID != ctx.User.ID {
  456. ctx.Data["CanEditFile"] = false
  457. ctx.Data["EditFileTooltip"] = ctx.Tr("repo.editor.this_file_locked")
  458. } else {
  459. ctx.Data["CanEditFile"] = true
  460. ctx.Data["EditFileTooltip"] = ctx.Tr("repo.editor.edit_this_file")
  461. }
  462. } else if !ctx.Repo.IsViewBranch {
  463. ctx.Data["EditFileTooltip"] = ctx.Tr("repo.editor.must_be_on_a_branch")
  464. } else if !ctx.Repo.CanWrite(models.UnitTypeCode) {
  465. ctx.Data["EditFileTooltip"] = ctx.Tr("repo.editor.fork_before_edit")
  466. }
  467. }
  468. case base.IsPDFFile(buf):
  469. ctx.Data["IsPDFFile"] = true
  470. case base.IsVideoFile(buf):
  471. ctx.Data["IsVideoFile"] = true
  472. case base.IsAudioFile(buf):
  473. ctx.Data["IsAudioFile"] = true
  474. case base.IsImageFile(buf):
  475. ctx.Data["IsImageFile"] = true
  476. default:
  477. if fileSize >= setting.UI.MaxDisplayFileSize {
  478. ctx.Data["IsFileTooLarge"] = true
  479. break
  480. }
  481. if markupType := markup.Type(blob.Name()); markupType != "" {
  482. d, _ := ioutil.ReadAll(dataRc)
  483. buf = append(buf, d...)
  484. ctx.Data["IsMarkup"] = true
  485. ctx.Data["MarkupType"] = markupType
  486. ctx.Data["FileContent"] = string(markup.Render(blob.Name(), buf, path.Dir(treeLink), ctx.Repo.Repository.ComposeMetas()))
  487. }
  488. }
  489. if ctx.Repo.CanEnableEditor() {
  490. if lfsLock != nil && lfsLock.OwnerID != ctx.User.ID {
  491. ctx.Data["CanDeleteFile"] = false
  492. ctx.Data["DeleteFileTooltip"] = ctx.Tr("repo.editor.this_file_locked")
  493. } else {
  494. ctx.Data["CanDeleteFile"] = true
  495. ctx.Data["DeleteFileTooltip"] = ctx.Tr("repo.editor.delete_this_file")
  496. }
  497. } else if !ctx.Repo.IsViewBranch {
  498. ctx.Data["DeleteFileTooltip"] = ctx.Tr("repo.editor.must_be_on_a_branch")
  499. } else if !ctx.Repo.CanWrite(models.UnitTypeCode) {
  500. ctx.Data["DeleteFileTooltip"] = ctx.Tr("repo.editor.must_have_write_access")
  501. }
  502. }
  503. func safeURL(address string) string {
  504. u, err := url.Parse(address)
  505. if err != nil {
  506. return address
  507. }
  508. u.User = nil
  509. return u.String()
  510. }
  511. type ContributorInfo struct {
  512. UserInfo *models.User // nil for contributor who is not a registered user
  513. Email string
  514. CommitCnt int
  515. }
  516. func getContributorInfo(contributorInfos []*ContributorInfo, email string) *ContributorInfo{
  517. for _, c := range contributorInfos {
  518. if strings.Compare(c.Email,email) == 0 {
  519. return c
  520. }
  521. }
  522. return nil
  523. }
  524. // Home render repository home page
  525. func Home(ctx *context.Context) {
  526. if len(ctx.Repo.Units) > 0 {
  527. //get repo contributors info
  528. contributors, err := git.GetContributors(ctx.Repo.Repository.RepoPath())
  529. if err == nil && contributors != nil {
  530. startTime := time.Now()
  531. var contributorInfos []*ContributorInfo
  532. contributorInfoHash:= make(map[string]*ContributorInfo)
  533. for _, c := range contributors {
  534. if strings.Compare(c.Email,"") == 0 {
  535. continue
  536. }
  537. // get user info from committer email
  538. user, err := models.GetUserByActivateEmail(c.Email)
  539. if err == nil {
  540. // committer is system user, get info through user's primary email
  541. if existedContributorInfo,ok:=contributorInfoHash[user.Email];ok {
  542. // existed: same primary email, different committer name
  543. existedContributorInfo.CommitCnt += c.CommitCnt
  544. }else{
  545. // new committer info
  546. var newContributor = &ContributorInfo{
  547. user, user.Email,c.CommitCnt,
  548. }
  549. contributorInfos = append(contributorInfos, newContributor )
  550. contributorInfoHash[user.Email] = newContributor
  551. }
  552. } else {
  553. // committer is not system user
  554. if existedContributorInfo,ok:=contributorInfoHash[c.Email];ok {
  555. // existed: same primary email, different committer name
  556. existedContributorInfo.CommitCnt += c.CommitCnt
  557. }else{
  558. var newContributor = &ContributorInfo{
  559. user, c.Email,c.CommitCnt,
  560. }
  561. contributorInfos = append(contributorInfos, newContributor)
  562. contributorInfoHash[c.Email] = newContributor
  563. }
  564. }
  565. }
  566. ctx.Data["ContributorInfo"] = contributorInfos
  567. var duration = time.Since(startTime)
  568. log.Info("getContributorInfo cost: %v seconds",duration.Seconds())
  569. }
  570. if ctx.Repo.Repository.IsBeingCreated() {
  571. task, err := models.GetMigratingTask(ctx.Repo.Repository.ID)
  572. if err != nil {
  573. ctx.ServerError("models.GetMigratingTask", err)
  574. return
  575. }
  576. cfg, err := task.MigrateConfig()
  577. if err != nil {
  578. ctx.ServerError("task.MigrateConfig", err)
  579. return
  580. }
  581. ctx.Data["Repo"] = ctx.Repo
  582. ctx.Data["MigrateTask"] = task
  583. ctx.Data["CloneAddr"] = safeURL(cfg.CloneAddr)
  584. ctx.HTML(200, tplMigrating)
  585. return
  586. }
  587. var firstUnit *models.Unit
  588. for _, repoUnit := range ctx.Repo.Units {
  589. if repoUnit.Type == models.UnitTypeCode {
  590. renderCode(ctx)
  591. return
  592. }
  593. unit, ok := models.Units[repoUnit.Type]
  594. if ok && (firstUnit == nil || !firstUnit.IsLessThan(unit)) {
  595. firstUnit = &unit
  596. }
  597. }
  598. if firstUnit != nil {
  599. ctx.Redirect(fmt.Sprintf("%s/%s%s", setting.AppSubURL, ctx.Repo.Repository.FullName(), firstUnit.URI))
  600. return
  601. }
  602. }
  603. ctx.NotFound("Home", fmt.Errorf(ctx.Tr("units.error.no_unit_allowed_repo")))
  604. }
  605. func renderLicense(ctx *context.Context) {
  606. entry, err := ctx.Repo.Commit.GetTreeEntryByPath("LICENSE")
  607. if err != nil {
  608. log.Error(err.Error())
  609. return
  610. }
  611. blob := entry.Blob()
  612. dataRc, err := blob.DataAsync()
  613. if err != nil {
  614. log.Error("DataAsync", err)
  615. return
  616. }
  617. defer dataRc.Close()
  618. buf, err := ioutil.ReadAll(dataRc)
  619. if err != nil {
  620. log.Error("DataAsync", err)
  621. return
  622. }
  623. for _, f := range models.Licenses {
  624. license, err := options.License(f)
  625. if err != nil {
  626. log.Error("failed to get license content: %v, err:%v", f, err)
  627. continue
  628. }
  629. if bytes.Compare(buf,license) == 0 {
  630. log.Info("got matched license:%v",f)
  631. ctx.Data["LICENSE"] = f
  632. return
  633. }
  634. }
  635. log.Info("not found matched license,repo:%v",ctx.Repo.Repository.Name)
  636. }
  637. func renderLanguageStats(ctx *context.Context) {
  638. langs, err := ctx.Repo.Repository.GetTopLanguageStats(5)
  639. if err != nil {
  640. ctx.ServerError("Repo.GetTopLanguageStats", err)
  641. return
  642. }
  643. ctx.Data["LanguageStats"] = langs
  644. }
  645. func renderRepoTopics(ctx *context.Context) {
  646. topics, err := models.FindTopics(&models.FindTopicOptions{
  647. RepoID: ctx.Repo.Repository.ID,
  648. })
  649. if err != nil {
  650. ctx.ServerError("models.FindTopics", err)
  651. return
  652. }
  653. ctx.Data["Topics"] = topics
  654. }
  655. func renderCode(ctx *context.Context) {
  656. ctx.Data["PageIsViewCode"] = true
  657. if ctx.Repo.Repository.IsEmpty {
  658. ctx.HTML(200, tplRepoEMPTY)
  659. return
  660. }
  661. title := ctx.Repo.Repository.Owner.Name + "/" + ctx.Repo.Repository.Name
  662. if len(ctx.Repo.Repository.Description) > 0 {
  663. title += ": " + ctx.Repo.Repository.Description
  664. }
  665. ctx.Data["Title"] = title
  666. ctx.Data["RequireHighlightJS"] = true
  667. branchLink := ctx.Repo.RepoLink + "/src/" + ctx.Repo.BranchNameSubURL()
  668. treeLink := branchLink
  669. rawLink := ctx.Repo.RepoLink + "/raw/" + ctx.Repo.BranchNameSubURL()
  670. if len(ctx.Repo.TreePath) > 0 {
  671. treeLink += "/" + ctx.Repo.TreePath
  672. }
  673. // Get Topics of this repo
  674. renderRepoTopics(ctx)
  675. // Get license of this repo
  676. renderLicense(ctx)
  677. if ctx.Written() {
  678. return
  679. }
  680. // Get current entry user currently looking at.
  681. entry, err := ctx.Repo.Commit.GetTreeEntryByPath(ctx.Repo.TreePath)
  682. if err != nil {
  683. ctx.NotFoundOrServerError("Repo.Commit.GetTreeEntryByPath", git.IsErrNotExist, err)
  684. return
  685. }
  686. renderLanguageStats(ctx)
  687. if ctx.Written() {
  688. return
  689. }
  690. if entry.IsDir() {
  691. renderDirectory(ctx, treeLink)
  692. } else {
  693. renderFile(ctx, entry, treeLink, rawLink)
  694. }
  695. if ctx.Written() {
  696. return
  697. }
  698. var treeNames []string
  699. paths := make([]string, 0, 5)
  700. if len(ctx.Repo.TreePath) > 0 {
  701. treeNames = strings.Split(ctx.Repo.TreePath, "/")
  702. for i := range treeNames {
  703. paths = append(paths, strings.Join(treeNames[:i+1], "/"))
  704. }
  705. ctx.Data["HasParentPath"] = true
  706. if len(paths)-2 >= 0 {
  707. ctx.Data["ParentPath"] = "/" + paths[len(paths)-2]
  708. }
  709. }
  710. //如果是fork的仓库
  711. if ctx.Repo.Repository.IsFork {
  712. //获得fetchUpstream对应的分支参数
  713. /*
  714. // 1. /{:baseOwner}/{:baseRepoName}/compare/{:baseBranch}...{:headBranch}
  715. // 2. /{:baseOwner}/{:baseRepoName}/compare/{:baseBranch}...{:headOwner}:{:headBranch}
  716. // 3. /{:baseOwner}/{:baseRepoName}/compare/{:baseBranch}...{:headOwner}/{:headRepoName}:{:headBranch}
  717. */
  718. baseGitRepo, err := git.OpenRepository(ctx.Repo.Repository.BaseRepo.RepoPath())
  719. if err != nil {
  720. log.Error("error open baseRepo:%s",ctx.Repo.Repository.BaseRepo.RepoPath())
  721. }
  722. defer baseGitRepo.Close()
  723. if _,error:= baseGitRepo.GetBranch(ctx.Repo.BranchName);error==nil{
  724. //base repo has the same branch, then compare between current repo branch and base repo's branch
  725. compareUrl := ctx.Repo.BranchName + "..." + ctx.Repo.Repository.BaseRepo.OwnerName + "/" + ctx.Repo.Repository.BaseRepo.Name + ":" + ctx.Repo.BranchName
  726. ctx.SetParams("*",compareUrl)
  727. }else{
  728. //else, compare between current repo branch and base repo's default branch
  729. compareUrl := ctx.Repo.BranchName + "..." + ctx.Repo.Repository.BaseRepo.OwnerName + "/" + ctx.Repo.Repository.BaseRepo.Name + ":" + ctx.Repo.Repository.BaseRepo.DefaultBranch
  730. ctx.SetParams("*",compareUrl)
  731. }
  732. _, _, headGitRepo, compareInfo, _, _ := ParseCompareInfo(ctx)
  733. defer headGitRepo.Close()
  734. if compareInfo!= nil {
  735. if compareInfo.Commits!=nil {
  736. log.Info("compareInfoCommits数量:%d",compareInfo.Commits.Len())
  737. ctx.Data["FetchUpstreamCnt"] = compareInfo.Commits.Len()
  738. }else{
  739. log.Info("compareInfo nothing different")
  740. ctx.Data["FetchUpstreamCnt"] = 0
  741. }
  742. }
  743. }
  744. ctx.Data["Paths"] = paths
  745. ctx.Data["TreeLink"] = treeLink
  746. ctx.Data["TreeNames"] = treeNames
  747. ctx.Data["BranchLink"] = branchLink
  748. ctx.HTML(200, tplRepoHome)
  749. }
  750. // RenderUserCards render a page show users according the input templaet
  751. func RenderUserCards(ctx *context.Context, total int, getter func(opts models.ListOptions) ([]*models.User, error), tpl base.TplName) {
  752. page := ctx.QueryInt("page")
  753. if page <= 0 {
  754. page = 1
  755. }
  756. pager := context.NewPagination(total, models.ItemsPerPage, page, 5)
  757. ctx.Data["Page"] = pager
  758. items, err := getter(models.ListOptions{Page: pager.Paginater.Current()})
  759. if err != nil {
  760. ctx.ServerError("getter", err)
  761. return
  762. }
  763. ctx.Data["Cards"] = items
  764. ctx.HTML(200, tpl)
  765. }
  766. // Watchers render repository's watch users
  767. func Watchers(ctx *context.Context) {
  768. ctx.Data["Title"] = ctx.Tr("repo.watchers")
  769. ctx.Data["CardsTitle"] = ctx.Tr("repo.watchers")
  770. ctx.Data["PageIsWatchers"] = true
  771. RenderUserCards(ctx, ctx.Repo.Repository.NumWatches, ctx.Repo.Repository.GetWatchers, tplWatchers)
  772. }
  773. // Stars render repository's starred users
  774. func Stars(ctx *context.Context) {
  775. ctx.Data["Title"] = ctx.Tr("repo.stargazers")
  776. ctx.Data["CardsTitle"] = ctx.Tr("repo.stargazers")
  777. ctx.Data["PageIsStargazers"] = true
  778. RenderUserCards(ctx, ctx.Repo.Repository.NumStars, ctx.Repo.Repository.GetStargazers, tplWatchers)
  779. }
  780. // Forks render repository's forked users
  781. func Forks(ctx *context.Context) {
  782. ctx.Data["Title"] = ctx.Tr("repos.forks")
  783. forks, err := ctx.Repo.Repository.GetForks(models.ListOptions{})
  784. if err != nil {
  785. ctx.ServerError("GetForks", err)
  786. return
  787. }
  788. for _, fork := range forks {
  789. if err = fork.GetOwner(); err != nil {
  790. ctx.ServerError("GetOwner", err)
  791. return
  792. }
  793. }
  794. ctx.Data["Forks"] = forks
  795. ctx.HTML(200, tplForks)
  796. }