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 28 kB

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