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