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.

repo.go 88 kB

11 years ago
11 years ago
11 years ago
Repository avatars (#6986) * Repository avatars - first variant of code from old work for gogs - add migration 87 - add new option in app.ini - add en-US locale string - add new class in repository.less * Add changed index.css, remove unused template name * Update en-us doc about configuration options * Add comments to new functions, add new option to docker app.ini * Add comment for lint * Remove variable, not needed * Fix formatting * Update swagger api template * Check if avatar exists * Fix avatar link/path checks * Typo * TEXT column can't have a default value * Fixes: - remove old avatar file on upload - use ID in name of avatar file - users may upload same files - add simple tests * Fix fmt check * Generate PNG instead of "static" GIF * More informative comment * Fix error message * Update avatar upload checks: - add file size check - add new option - update config docs - add new string to en-us locale * Fixes: - use FileHEader field for check file size - add new test - upload big image * Fix formatting * Update comments * Update log message * Removed wrong style - not needed * Use Sync2 to migrate * Update repos list view - bigger avatar - fix html blocks alignment * A little adjust avatar size * Use small icons for explore/repo list * Use new cool avatar preparation func by @lafriks * Missing changes for new function * Remove unused import, move imports * Missed new option definition in app.ini Add file size check in user/profile avatar upload * Use smaller field length for Avatar * Use session to update repo DB data, update DeleteAvatar - use session too * Fix err variable definition * As suggested @lafriks - return as soon as possible, code readability
6 years ago
Repository avatars (#6986) * Repository avatars - first variant of code from old work for gogs - add migration 87 - add new option in app.ini - add en-US locale string - add new class in repository.less * Add changed index.css, remove unused template name * Update en-us doc about configuration options * Add comments to new functions, add new option to docker app.ini * Add comment for lint * Remove variable, not needed * Fix formatting * Update swagger api template * Check if avatar exists * Fix avatar link/path checks * Typo * TEXT column can't have a default value * Fixes: - remove old avatar file on upload - use ID in name of avatar file - users may upload same files - add simple tests * Fix fmt check * Generate PNG instead of "static" GIF * More informative comment * Fix error message * Update avatar upload checks: - add file size check - add new option - update config docs - add new string to en-us locale * Fixes: - use FileHEader field for check file size - add new test - upload big image * Fix formatting * Update comments * Update log message * Removed wrong style - not needed * Use Sync2 to migrate * Update repos list view - bigger avatar - fix html blocks alignment * A little adjust avatar size * Use small icons for explore/repo list * Use new cool avatar preparation func by @lafriks * Missing changes for new function * Remove unused import, move imports * Missed new option definition in app.ini Add file size check in user/profile avatar upload * Use smaller field length for Avatar * Use session to update repo DB data, update DeleteAvatar - use session too * Fix err variable definition * As suggested @lafriks - return as soon as possible, code readability
6 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
Repository avatars (#6986) * Repository avatars - first variant of code from old work for gogs - add migration 87 - add new option in app.ini - add en-US locale string - add new class in repository.less * Add changed index.css, remove unused template name * Update en-us doc about configuration options * Add comments to new functions, add new option to docker app.ini * Add comment for lint * Remove variable, not needed * Fix formatting * Update swagger api template * Check if avatar exists * Fix avatar link/path checks * Typo * TEXT column can't have a default value * Fixes: - remove old avatar file on upload - use ID in name of avatar file - users may upload same files - add simple tests * Fix fmt check * Generate PNG instead of "static" GIF * More informative comment * Fix error message * Update avatar upload checks: - add file size check - add new option - update config docs - add new string to en-us locale * Fixes: - use FileHEader field for check file size - add new test - upload big image * Fix formatting * Update comments * Update log message * Removed wrong style - not needed * Use Sync2 to migrate * Update repos list view - bigger avatar - fix html blocks alignment * A little adjust avatar size * Use small icons for explore/repo list * Use new cool avatar preparation func by @lafriks * Missing changes for new function * Remove unused import, move imports * Missed new option definition in app.ini Add file size check in user/profile avatar upload * Use smaller field length for Avatar * Use session to update repo DB data, update DeleteAvatar - use session too * Fix err variable definition * As suggested @lafriks - return as soon as possible, code readability
6 years ago
Sign merges, CRUD, Wiki and Repository initialisation with gpg key (#7631) This PR fixes #7598 by providing a configurable way of signing commits across the Gitea instance. Per repository configurability and import/generation of trusted secure keys is not provided by this PR - from a security PoV that's probably impossible to do properly. Similarly web-signing, that is asking the user to sign something, is not implemented - this could be done at a later stage however. ## Features - [x] If commit.gpgsign is set in .gitconfig sign commits and files created through repofiles. (merges should already have been signed.) - [x] Verify commits signed with the default gpg as valid - [x] Signer, Committer and Author can all be different - [x] Allow signer to be arbitrarily different - We still require the key to have an activated email on Gitea. A more complete implementation would be to use a keyserver and mark external-or-unactivated with an "unknown" trust level icon. - [x] Add a signing-key.gpg endpoint to get the default gpg pub key if available - Rather than add a fake web-flow user I've added this as an endpoint on /api/v1/signing-key.gpg - [x] Try to match the default key with a user on gitea - this is done at verification time - [x] Make things configurable? - app.ini configuration done - [x] when checking commits are signed need to check if they're actually verifiable too - [x] Add documentation I have decided that adjusting the docker to create a default gpg key is not the correct thing to do and therefore have not implemented this.
5 years ago
11 years ago
11 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
11 years ago
11 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
11 years ago
11 years ago
11 years ago
Template Repositories (#8768) * Start work on templates Signed-off-by: jolheiser <john.olheiser@gmail.com> * Continue work Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix IsTemplate vs IsGenerated Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix tabs vs spaces * Tabs vs Spaces * Add templates to API & start adding tests Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix integration tests Signed-off-by: jolheiser <john.olheiser@gmail.com> * Remove unused User Signed-off-by: jolheiser <john.olheiser@gmail.com> * Move template tests to existing repos Signed-off-by: jolheiser <john.olheiser@gmail.com> * Minor re-check updates and cleanup Signed-off-by: jolheiser <john.olheiser@gmail.com> * make fmt Signed-off-by: jolheiser <john.olheiser@gmail.com> * Test cleanup Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix optionalbool Signed-off-by: jolheiser <john.olheiser@gmail.com> * make fmt Signed-off-by: jolheiser <john.olheiser@gmail.com> * Test fixes and icon change Signed-off-by: jolheiser <john.olheiser@gmail.com> * Add new user and repo for tests Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix tests (finally) Signed-off-by: jolheiser <john.olheiser@gmail.com> * Update meta repo with env variables Signed-off-by: jolheiser <john.olheiser@gmail.com> * Move generation to create page Combine with repo create template Modify API search to prioritize owner for repo Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix tests and coverage Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix swagger and JS lint Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix API searching for own private repos Signed-off-by: jolheiser <john.olheiser@gmail.com> * Change wording Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix repo search test. User had a private repo that didn't show up Signed-off-by: jolheiser <john.olheiser@gmail.com> * Another search test fix Signed-off-by: jolheiser <john.olheiser@gmail.com> * Clarify git content Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> * Feedback updates Signed-off-by: jolheiser <john.olheiser@gmail.com> * Add topics WIP Signed-off-by: jolheiser <john.olheiser@gmail.com> * Finish adding topics Signed-off-by: jolheiser <john.olheiser@gmail.com> * Update locale Signed-off-by: jolheiser <john.olheiser@gmail.com>
5 years ago
Repository avatars (#6986) * Repository avatars - first variant of code from old work for gogs - add migration 87 - add new option in app.ini - add en-US locale string - add new class in repository.less * Add changed index.css, remove unused template name * Update en-us doc about configuration options * Add comments to new functions, add new option to docker app.ini * Add comment for lint * Remove variable, not needed * Fix formatting * Update swagger api template * Check if avatar exists * Fix avatar link/path checks * Typo * TEXT column can't have a default value * Fixes: - remove old avatar file on upload - use ID in name of avatar file - users may upload same files - add simple tests * Fix fmt check * Generate PNG instead of "static" GIF * More informative comment * Fix error message * Update avatar upload checks: - add file size check - add new option - update config docs - add new string to en-us locale * Fixes: - use FileHEader field for check file size - add new test - upload big image * Fix formatting * Update comments * Update log message * Removed wrong style - not needed * Use Sync2 to migrate * Update repos list view - bigger avatar - fix html blocks alignment * A little adjust avatar size * Use small icons for explore/repo list * Use new cool avatar preparation func by @lafriks * Missing changes for new function * Remove unused import, move imports * Missed new option definition in app.ini Add file size check in user/profile avatar upload * Use smaller field length for Avatar * Use session to update repo DB data, update DeleteAvatar - use session too * Fix err variable definition * As suggested @lafriks - return as soon as possible, code readability
6 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
Template Repositories (#8768) * Start work on templates Signed-off-by: jolheiser <john.olheiser@gmail.com> * Continue work Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix IsTemplate vs IsGenerated Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix tabs vs spaces * Tabs vs Spaces * Add templates to API & start adding tests Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix integration tests Signed-off-by: jolheiser <john.olheiser@gmail.com> * Remove unused User Signed-off-by: jolheiser <john.olheiser@gmail.com> * Move template tests to existing repos Signed-off-by: jolheiser <john.olheiser@gmail.com> * Minor re-check updates and cleanup Signed-off-by: jolheiser <john.olheiser@gmail.com> * make fmt Signed-off-by: jolheiser <john.olheiser@gmail.com> * Test cleanup Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix optionalbool Signed-off-by: jolheiser <john.olheiser@gmail.com> * make fmt Signed-off-by: jolheiser <john.olheiser@gmail.com> * Test fixes and icon change Signed-off-by: jolheiser <john.olheiser@gmail.com> * Add new user and repo for tests Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix tests (finally) Signed-off-by: jolheiser <john.olheiser@gmail.com> * Update meta repo with env variables Signed-off-by: jolheiser <john.olheiser@gmail.com> * Move generation to create page Combine with repo create template Modify API search to prioritize owner for repo Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix tests and coverage Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix swagger and JS lint Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix API searching for own private repos Signed-off-by: jolheiser <john.olheiser@gmail.com> * Change wording Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix repo search test. User had a private repo that didn't show up Signed-off-by: jolheiser <john.olheiser@gmail.com> * Another search test fix Signed-off-by: jolheiser <john.olheiser@gmail.com> * Clarify git content Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> * Feedback updates Signed-off-by: jolheiser <john.olheiser@gmail.com> * Add topics WIP Signed-off-by: jolheiser <john.olheiser@gmail.com> * Finish adding topics Signed-off-by: jolheiser <john.olheiser@gmail.com> * Update locale Signed-off-by: jolheiser <john.olheiser@gmail.com>
5 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
Check commit message hashes before making links (#7713) * Check commit message hashes before making links Previously, when formatting commit messages, anything that looked like SHA1 hashes was turned into a link using regex. This meant that certain phrases or numbers such as `777777` or `deadbeef` could be recognized as a commit even if the repository has no commit with those hashes. This change will make it so that anything that looks like a SHA1 hash using regex will then also be checked to ensure that there is a commit in the repository with that hash before making a link. Signed-off-by: Gary Kim <gary@garykim.dev> * Use gogit to check if commit exists This commit modifies the commit hash check in the render for commit messages to use gogit for better performance. Signed-off-by: Gary Kim <gary@garykim.dev> * Make code cleaner Signed-off-by: Gary Kim <gary@garykim.dev> * Use rev-parse to check if commit exists Signed-off-by: Gary Kim <gary@garykim.dev> * Add and modify tests for checking hashes in html link rendering Signed-off-by: Gary Kim <gary@garykim.dev> * Return error in sha1CurrentPatternProcessor Co-Authored-By: mrsdizzie <info@mrsdizzie.com> * Import Gitea log module Signed-off-by: Gary Kim <gary@garykim.dev> * Revert "Return error in sha1CurrentPatternProcessor" This reverts commit 28f561cac46ef7e51aa26aefcbe9aca4671366a6. Signed-off-by: Gary Kim <gary@garykim.dev> * Add debug logging to sha1CurrentPatternProcessor This will log errors by the git command run in sha1CurrentPatternProcessor if the error is one that was unexpected. Signed-off-by: Gary Kim <gary@garykim.dev>
5 years ago
Template Repositories (#8768) * Start work on templates Signed-off-by: jolheiser <john.olheiser@gmail.com> * Continue work Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix IsTemplate vs IsGenerated Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix tabs vs spaces * Tabs vs Spaces * Add templates to API & start adding tests Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix integration tests Signed-off-by: jolheiser <john.olheiser@gmail.com> * Remove unused User Signed-off-by: jolheiser <john.olheiser@gmail.com> * Move template tests to existing repos Signed-off-by: jolheiser <john.olheiser@gmail.com> * Minor re-check updates and cleanup Signed-off-by: jolheiser <john.olheiser@gmail.com> * make fmt Signed-off-by: jolheiser <john.olheiser@gmail.com> * Test cleanup Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix optionalbool Signed-off-by: jolheiser <john.olheiser@gmail.com> * make fmt Signed-off-by: jolheiser <john.olheiser@gmail.com> * Test fixes and icon change Signed-off-by: jolheiser <john.olheiser@gmail.com> * Add new user and repo for tests Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix tests (finally) Signed-off-by: jolheiser <john.olheiser@gmail.com> * Update meta repo with env variables Signed-off-by: jolheiser <john.olheiser@gmail.com> * Move generation to create page Combine with repo create template Modify API search to prioritize owner for repo Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix tests and coverage Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix swagger and JS lint Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix API searching for own private repos Signed-off-by: jolheiser <john.olheiser@gmail.com> * Change wording Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix repo search test. User had a private repo that didn't show up Signed-off-by: jolheiser <john.olheiser@gmail.com> * Another search test fix Signed-off-by: jolheiser <john.olheiser@gmail.com> * Clarify git content Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> * Feedback updates Signed-off-by: jolheiser <john.olheiser@gmail.com> * Add topics WIP Signed-off-by: jolheiser <john.olheiser@gmail.com> * Finish adding topics Signed-off-by: jolheiser <john.olheiser@gmail.com> * Update locale Signed-off-by: jolheiser <john.olheiser@gmail.com>
5 years ago
9 years ago
10 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
11 years ago
9 years ago
9 years ago
9 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
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
9 years ago
9 years ago
Sign merges, CRUD, Wiki and Repository initialisation with gpg key (#7631) This PR fixes #7598 by providing a configurable way of signing commits across the Gitea instance. Per repository configurability and import/generation of trusted secure keys is not provided by this PR - from a security PoV that's probably impossible to do properly. Similarly web-signing, that is asking the user to sign something, is not implemented - this could be done at a later stage however. ## Features - [x] If commit.gpgsign is set in .gitconfig sign commits and files created through repofiles. (merges should already have been signed.) - [x] Verify commits signed with the default gpg as valid - [x] Signer, Committer and Author can all be different - [x] Allow signer to be arbitrarily different - We still require the key to have an activated email on Gitea. A more complete implementation would be to use a keyserver and mark external-or-unactivated with an "unknown" trust level icon. - [x] Add a signing-key.gpg endpoint to get the default gpg pub key if available - Rather than add a fake web-flow user I've added this as an endpoint on /api/v1/signing-key.gpg - [x] Try to match the default key with a user on gitea - this is done at verification time - [x] Make things configurable? - app.ini configuration done - [x] when checking commits are signed need to check if they're actually verifiable too - [x] Add documentation I have decided that adjusting the docker to create a default gpg key is not the correct thing to do and therefore have not implemented this.
5 years ago
Sign merges, CRUD, Wiki and Repository initialisation with gpg key (#7631) This PR fixes #7598 by providing a configurable way of signing commits across the Gitea instance. Per repository configurability and import/generation of trusted secure keys is not provided by this PR - from a security PoV that's probably impossible to do properly. Similarly web-signing, that is asking the user to sign something, is not implemented - this could be done at a later stage however. ## Features - [x] If commit.gpgsign is set in .gitconfig sign commits and files created through repofiles. (merges should already have been signed.) - [x] Verify commits signed with the default gpg as valid - [x] Signer, Committer and Author can all be different - [x] Allow signer to be arbitrarily different - We still require the key to have an activated email on Gitea. A more complete implementation would be to use a keyserver and mark external-or-unactivated with an "unknown" trust level icon. - [x] Add a signing-key.gpg endpoint to get the default gpg pub key if available - Rather than add a fake web-flow user I've added this as an endpoint on /api/v1/signing-key.gpg - [x] Try to match the default key with a user on gitea - this is done at verification time - [x] Make things configurable? - app.ini configuration done - [x] when checking commits are signed need to check if they're actually verifiable too - [x] Add documentation I have decided that adjusting the docker to create a default gpg key is not the correct thing to do and therefore have not implemented this.
5 years ago
11 years ago
Sign merges, CRUD, Wiki and Repository initialisation with gpg key (#7631) This PR fixes #7598 by providing a configurable way of signing commits across the Gitea instance. Per repository configurability and import/generation of trusted secure keys is not provided by this PR - from a security PoV that's probably impossible to do properly. Similarly web-signing, that is asking the user to sign something, is not implemented - this could be done at a later stage however. ## Features - [x] If commit.gpgsign is set in .gitconfig sign commits and files created through repofiles. (merges should already have been signed.) - [x] Verify commits signed with the default gpg as valid - [x] Signer, Committer and Author can all be different - [x] Allow signer to be arbitrarily different - We still require the key to have an activated email on Gitea. A more complete implementation would be to use a keyserver and mark external-or-unactivated with an "unknown" trust level icon. - [x] Add a signing-key.gpg endpoint to get the default gpg pub key if available - Rather than add a fake web-flow user I've added this as an endpoint on /api/v1/signing-key.gpg - [x] Try to match the default key with a user on gitea - this is done at verification time - [x] Make things configurable? - app.ini configuration done - [x] when checking commits are signed need to check if they're actually verifiable too - [x] Add documentation I have decided that adjusting the docker to create a default gpg key is not the correct thing to do and therefore have not implemented this.
5 years ago
Template Repositories (#8768) * Start work on templates Signed-off-by: jolheiser <john.olheiser@gmail.com> * Continue work Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix IsTemplate vs IsGenerated Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix tabs vs spaces * Tabs vs Spaces * Add templates to API & start adding tests Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix integration tests Signed-off-by: jolheiser <john.olheiser@gmail.com> * Remove unused User Signed-off-by: jolheiser <john.olheiser@gmail.com> * Move template tests to existing repos Signed-off-by: jolheiser <john.olheiser@gmail.com> * Minor re-check updates and cleanup Signed-off-by: jolheiser <john.olheiser@gmail.com> * make fmt Signed-off-by: jolheiser <john.olheiser@gmail.com> * Test cleanup Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix optionalbool Signed-off-by: jolheiser <john.olheiser@gmail.com> * make fmt Signed-off-by: jolheiser <john.olheiser@gmail.com> * Test fixes and icon change Signed-off-by: jolheiser <john.olheiser@gmail.com> * Add new user and repo for tests Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix tests (finally) Signed-off-by: jolheiser <john.olheiser@gmail.com> * Update meta repo with env variables Signed-off-by: jolheiser <john.olheiser@gmail.com> * Move generation to create page Combine with repo create template Modify API search to prioritize owner for repo Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix tests and coverage Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix swagger and JS lint Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix API searching for own private repos Signed-off-by: jolheiser <john.olheiser@gmail.com> * Change wording Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix repo search test. User had a private repo that didn't show up Signed-off-by: jolheiser <john.olheiser@gmail.com> * Another search test fix Signed-off-by: jolheiser <john.olheiser@gmail.com> * Clarify git content Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> * Feedback updates Signed-off-by: jolheiser <john.olheiser@gmail.com> * Add topics WIP Signed-off-by: jolheiser <john.olheiser@gmail.com> * Finish adding topics Signed-off-by: jolheiser <john.olheiser@gmail.com> * Update locale Signed-off-by: jolheiser <john.olheiser@gmail.com>
5 years ago
11 years ago
Template Repositories (#8768) * Start work on templates Signed-off-by: jolheiser <john.olheiser@gmail.com> * Continue work Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix IsTemplate vs IsGenerated Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix tabs vs spaces * Tabs vs Spaces * Add templates to API & start adding tests Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix integration tests Signed-off-by: jolheiser <john.olheiser@gmail.com> * Remove unused User Signed-off-by: jolheiser <john.olheiser@gmail.com> * Move template tests to existing repos Signed-off-by: jolheiser <john.olheiser@gmail.com> * Minor re-check updates and cleanup Signed-off-by: jolheiser <john.olheiser@gmail.com> * make fmt Signed-off-by: jolheiser <john.olheiser@gmail.com> * Test cleanup Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix optionalbool Signed-off-by: jolheiser <john.olheiser@gmail.com> * make fmt Signed-off-by: jolheiser <john.olheiser@gmail.com> * Test fixes and icon change Signed-off-by: jolheiser <john.olheiser@gmail.com> * Add new user and repo for tests Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix tests (finally) Signed-off-by: jolheiser <john.olheiser@gmail.com> * Update meta repo with env variables Signed-off-by: jolheiser <john.olheiser@gmail.com> * Move generation to create page Combine with repo create template Modify API search to prioritize owner for repo Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix tests and coverage Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix swagger and JS lint Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix API searching for own private repos Signed-off-by: jolheiser <john.olheiser@gmail.com> * Change wording Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix repo search test. User had a private repo that didn't show up Signed-off-by: jolheiser <john.olheiser@gmail.com> * Another search test fix Signed-off-by: jolheiser <john.olheiser@gmail.com> * Clarify git content Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> * Feedback updates Signed-off-by: jolheiser <john.olheiser@gmail.com> * Add topics WIP Signed-off-by: jolheiser <john.olheiser@gmail.com> * Finish adding topics Signed-off-by: jolheiser <john.olheiser@gmail.com> * Update locale Signed-off-by: jolheiser <john.olheiser@gmail.com>
5 years ago
11 years ago
9 years ago
Sign merges, CRUD, Wiki and Repository initialisation with gpg key (#7631) This PR fixes #7598 by providing a configurable way of signing commits across the Gitea instance. Per repository configurability and import/generation of trusted secure keys is not provided by this PR - from a security PoV that's probably impossible to do properly. Similarly web-signing, that is asking the user to sign something, is not implemented - this could be done at a later stage however. ## Features - [x] If commit.gpgsign is set in .gitconfig sign commits and files created through repofiles. (merges should already have been signed.) - [x] Verify commits signed with the default gpg as valid - [x] Signer, Committer and Author can all be different - [x] Allow signer to be arbitrarily different - We still require the key to have an activated email on Gitea. A more complete implementation would be to use a keyserver and mark external-or-unactivated with an "unknown" trust level icon. - [x] Add a signing-key.gpg endpoint to get the default gpg pub key if available - Rather than add a fake web-flow user I've added this as an endpoint on /api/v1/signing-key.gpg - [x] Try to match the default key with a user on gitea - this is done at verification time - [x] Make things configurable? - app.ini configuration done - [x] when checking commits are signed need to check if they're actually verifiable too - [x] Add documentation I have decided that adjusting the docker to create a default gpg key is not the correct thing to do and therefore have not implemented this.
5 years ago
9 years ago
9 years ago
Feature: Timetracking (#2211) * Added comment's hashtag to url for mail notifications. * Added explanation to return statement + documentation. * Replacing in-line link generation with HTMLURL. (+gofmt) * Replaced action-based model with nil-based model. (+gofmt) * Replaced mailIssueActionToParticipants with mailIssueCommentToParticipants. * Updating comment for mailIssueCommentToParticipants * Added link to comment in "Dashboard" * Deleting feed entry if a comment is going to be deleted * Added migration * Added improved migration to add a CommentID column to action. * Added improved links to comments in feed entries. * Fixes #1956 by filtering for deleted comments that are referenced in actions. * Introducing "IsDeleted" column to action. * Adding design draft (not functional) * Adding database models for stopwatches and trackedtimes * See go-gitea/gitea#967 * Adding design draft (not functional) * Adding translations and improving design * Implementing stopwatch (for timetracking) * Make UI functional * Add hints in timeline for time tracking events * Implementing timetracking feature * Adding "Add time manual" option * Improved stopwatch * Created report of total spent time by user * Only showing total time spent if theire is something to show. * Adding license headers. * Improved error handling for "Add Time Manual" * Adding @sapks 's changes, refactoring * Adding API for feature tracking * Adding unit test * Adding DISABLE/ENABLE option to Repository settings page * Improving translations * Applying @sapk 's changes * Removing repo_unit and using IssuesSetting for disabling/enabling timetracker * Adding DEFAULT_ENABLE_TIMETRACKER to config, installation and admin menu * Improving documentation * Fixing vendor/ folder * Changing timtracking routes by adding subgroups /times and /times/stopwatch (Proposed by @lafriks ) * Restricting write access to timetracking based on the repo settings (Proposed by @lafriks ) * Fixed minor permissions bug. * Adding CanUseTimetracker and IsTimetrackerEnabled in ctx.Repo * Allow assignees and authors to track there time too. * Fixed some build-time-errors + logical errors. * Removing unused Get...ByID functions * Moving IsTimetrackerEnabled from context.Repository to models.Repository * Adding a seperate file for issue related repo functions * Adding license headers * Fixed GetUserByParams return 404 * Moving /users/:username/times to /repos/:username/:reponame/times/:username for security reasons * Adding /repos/:username/times to get all tracked times of the repo * Updating sdk-dependency * Updating swagger.v1.json * Adding warning if user has already a running stopwatch (auto-timetracker) * Replacing GetTrackedTimesBy... with GetTrackedTimes(options FindTrackedTimesOptions) * Changing code.gitea.io/sdk back to code.gitea.io/sdk * Correcting spelling mistake * Updating vendor.json * Changing GET stopwatch/toggle to POST stopwatch/toggle * Changing GET stopwatch/cancel to POST stopwatch/cancel * Added migration for stopwatches/timetracking * Fixed some access bugs for read-only users * Added default allow only contributors to track time value to config * Fixed migration by chaging x.Iterate to x.Find * Resorted imports * Moved Add Time Manually form to repo_form.go * Removed "Seconds" field from Add Time Manually * Resorted imports * Improved permission checking * Fixed some bugs * Added integration test * gofmt * Adding integration test by @lafriks * Added created_unix to comment fixtures * Using last event instead of a fixed event * Adding another integration test by @lafriks * Fixing bug Timetracker enabled causing error 500 at sidebar.tpl * Fixed a refactoring bug that resulted in hiding "HasUserStopwatch" warning. * Returning TrackedTime instead of AddTimeOption at AddTime. * Updating SDK from go-gitea/go-sdk#69 * Resetting Go-SDK back to default repository * Fixing test-vendor by changing ini back to original repository * Adding "tags" to swagger spec * govendor sync * Removed duplicate * Formatting templates * Adding IsTimetrackingEnabled checks to API * Improving translations / english texts * Improving documentation * Updating swagger spec * Fixing integration test caused be translation-changes * Removed encoding issues in local_en-US.ini. * "Added" copyright line * Moved unit.IssuesConfig().EnableTimetracker into a != nil check * Removed some other encoding issues in local_en-US.ini * Improved javascript by checking if data-context exists * Replaced manual comment creation with CreateComment * Removed unnecessary code * Improved error checking * Small cosmetic changes * Replaced int>string>duration parsing with int>duration parsing * Fixed encoding issues * Removed unused imports Signed-off-by: Jonas Franz <info@jonasfranz.software>
7 years ago
Feature: Timetracking (#2211) * Added comment's hashtag to url for mail notifications. * Added explanation to return statement + documentation. * Replacing in-line link generation with HTMLURL. (+gofmt) * Replaced action-based model with nil-based model. (+gofmt) * Replaced mailIssueActionToParticipants with mailIssueCommentToParticipants. * Updating comment for mailIssueCommentToParticipants * Added link to comment in "Dashboard" * Deleting feed entry if a comment is going to be deleted * Added migration * Added improved migration to add a CommentID column to action. * Added improved links to comments in feed entries. * Fixes #1956 by filtering for deleted comments that are referenced in actions. * Introducing "IsDeleted" column to action. * Adding design draft (not functional) * Adding database models for stopwatches and trackedtimes * See go-gitea/gitea#967 * Adding design draft (not functional) * Adding translations and improving design * Implementing stopwatch (for timetracking) * Make UI functional * Add hints in timeline for time tracking events * Implementing timetracking feature * Adding "Add time manual" option * Improved stopwatch * Created report of total spent time by user * Only showing total time spent if theire is something to show. * Adding license headers. * Improved error handling for "Add Time Manual" * Adding @sapks 's changes, refactoring * Adding API for feature tracking * Adding unit test * Adding DISABLE/ENABLE option to Repository settings page * Improving translations * Applying @sapk 's changes * Removing repo_unit and using IssuesSetting for disabling/enabling timetracker * Adding DEFAULT_ENABLE_TIMETRACKER to config, installation and admin menu * Improving documentation * Fixing vendor/ folder * Changing timtracking routes by adding subgroups /times and /times/stopwatch (Proposed by @lafriks ) * Restricting write access to timetracking based on the repo settings (Proposed by @lafriks ) * Fixed minor permissions bug. * Adding CanUseTimetracker and IsTimetrackerEnabled in ctx.Repo * Allow assignees and authors to track there time too. * Fixed some build-time-errors + logical errors. * Removing unused Get...ByID functions * Moving IsTimetrackerEnabled from context.Repository to models.Repository * Adding a seperate file for issue related repo functions * Adding license headers * Fixed GetUserByParams return 404 * Moving /users/:username/times to /repos/:username/:reponame/times/:username for security reasons * Adding /repos/:username/times to get all tracked times of the repo * Updating sdk-dependency * Updating swagger.v1.json * Adding warning if user has already a running stopwatch (auto-timetracker) * Replacing GetTrackedTimesBy... with GetTrackedTimes(options FindTrackedTimesOptions) * Changing code.gitea.io/sdk back to code.gitea.io/sdk * Correcting spelling mistake * Updating vendor.json * Changing GET stopwatch/toggle to POST stopwatch/toggle * Changing GET stopwatch/cancel to POST stopwatch/cancel * Added migration for stopwatches/timetracking * Fixed some access bugs for read-only users * Added default allow only contributors to track time value to config * Fixed migration by chaging x.Iterate to x.Find * Resorted imports * Moved Add Time Manually form to repo_form.go * Removed "Seconds" field from Add Time Manually * Resorted imports * Improved permission checking * Fixed some bugs * Added integration test * gofmt * Adding integration test by @lafriks * Added created_unix to comment fixtures * Using last event instead of a fixed event * Adding another integration test by @lafriks * Fixing bug Timetracker enabled causing error 500 at sidebar.tpl * Fixed a refactoring bug that resulted in hiding "HasUserStopwatch" warning. * Returning TrackedTime instead of AddTimeOption at AddTime. * Updating SDK from go-gitea/go-sdk#69 * Resetting Go-SDK back to default repository * Fixing test-vendor by changing ini back to original repository * Adding "tags" to swagger spec * govendor sync * Removed duplicate * Formatting templates * Adding IsTimetrackingEnabled checks to API * Improving translations / english texts * Improving documentation * Updating swagger spec * Fixing integration test caused be translation-changes * Removed encoding issues in local_en-US.ini. * "Added" copyright line * Moved unit.IssuesConfig().EnableTimetracker into a != nil check * Removed some other encoding issues in local_en-US.ini * Improved javascript by checking if data-context exists * Replaced manual comment creation with CreateComment * Removed unnecessary code * Improved error checking * Small cosmetic changes * Replaced int>string>duration parsing with int>duration parsing * Fixed encoding issues * Removed unused imports Signed-off-by: Jonas Franz <info@jonasfranz.software>
7 years ago
Feature: Timetracking (#2211) * Added comment's hashtag to url for mail notifications. * Added explanation to return statement + documentation. * Replacing in-line link generation with HTMLURL. (+gofmt) * Replaced action-based model with nil-based model. (+gofmt) * Replaced mailIssueActionToParticipants with mailIssueCommentToParticipants. * Updating comment for mailIssueCommentToParticipants * Added link to comment in "Dashboard" * Deleting feed entry if a comment is going to be deleted * Added migration * Added improved migration to add a CommentID column to action. * Added improved links to comments in feed entries. * Fixes #1956 by filtering for deleted comments that are referenced in actions. * Introducing "IsDeleted" column to action. * Adding design draft (not functional) * Adding database models for stopwatches and trackedtimes * See go-gitea/gitea#967 * Adding design draft (not functional) * Adding translations and improving design * Implementing stopwatch (for timetracking) * Make UI functional * Add hints in timeline for time tracking events * Implementing timetracking feature * Adding "Add time manual" option * Improved stopwatch * Created report of total spent time by user * Only showing total time spent if theire is something to show. * Adding license headers. * Improved error handling for "Add Time Manual" * Adding @sapks 's changes, refactoring * Adding API for feature tracking * Adding unit test * Adding DISABLE/ENABLE option to Repository settings page * Improving translations * Applying @sapk 's changes * Removing repo_unit and using IssuesSetting for disabling/enabling timetracker * Adding DEFAULT_ENABLE_TIMETRACKER to config, installation and admin menu * Improving documentation * Fixing vendor/ folder * Changing timtracking routes by adding subgroups /times and /times/stopwatch (Proposed by @lafriks ) * Restricting write access to timetracking based on the repo settings (Proposed by @lafriks ) * Fixed minor permissions bug. * Adding CanUseTimetracker and IsTimetrackerEnabled in ctx.Repo * Allow assignees and authors to track there time too. * Fixed some build-time-errors + logical errors. * Removing unused Get...ByID functions * Moving IsTimetrackerEnabled from context.Repository to models.Repository * Adding a seperate file for issue related repo functions * Adding license headers * Fixed GetUserByParams return 404 * Moving /users/:username/times to /repos/:username/:reponame/times/:username for security reasons * Adding /repos/:username/times to get all tracked times of the repo * Updating sdk-dependency * Updating swagger.v1.json * Adding warning if user has already a running stopwatch (auto-timetracker) * Replacing GetTrackedTimesBy... with GetTrackedTimes(options FindTrackedTimesOptions) * Changing code.gitea.io/sdk back to code.gitea.io/sdk * Correcting spelling mistake * Updating vendor.json * Changing GET stopwatch/toggle to POST stopwatch/toggle * Changing GET stopwatch/cancel to POST stopwatch/cancel * Added migration for stopwatches/timetracking * Fixed some access bugs for read-only users * Added default allow only contributors to track time value to config * Fixed migration by chaging x.Iterate to x.Find * Resorted imports * Moved Add Time Manually form to repo_form.go * Removed "Seconds" field from Add Time Manually * Resorted imports * Improved permission checking * Fixed some bugs * Added integration test * gofmt * Adding integration test by @lafriks * Added created_unix to comment fixtures * Using last event instead of a fixed event * Adding another integration test by @lafriks * Fixing bug Timetracker enabled causing error 500 at sidebar.tpl * Fixed a refactoring bug that resulted in hiding "HasUserStopwatch" warning. * Returning TrackedTime instead of AddTimeOption at AddTime. * Updating SDK from go-gitea/go-sdk#69 * Resetting Go-SDK back to default repository * Fixing test-vendor by changing ini back to original repository * Adding "tags" to swagger spec * govendor sync * Removed duplicate * Formatting templates * Adding IsTimetrackingEnabled checks to API * Improving translations / english texts * Improving documentation * Updating swagger spec * Fixing integration test caused be translation-changes * Removed encoding issues in local_en-US.ini. * "Added" copyright line * Moved unit.IssuesConfig().EnableTimetracker into a != nil check * Removed some other encoding issues in local_en-US.ini * Improved javascript by checking if data-context exists * Replaced manual comment creation with CreateComment * Removed unnecessary code * Improved error checking * Small cosmetic changes * Replaced int>string>duration parsing with int>duration parsing * Fixed encoding issues * Removed unused imports Signed-off-by: Jonas Franz <info@jonasfranz.software>
7 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
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
9 years ago
11 years ago
9 years ago
9 years ago
11 years ago
9 years ago
10 years ago
9 years ago
9 years ago
9 years ago
9 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
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
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
11 years ago
11 years ago
9 years ago
9 years ago
9 years ago
9 years ago
11 years ago
11 years ago
11 years ago
10 years ago
10 years ago
9 years ago
Git LFS support v2 (#122) * Import github.com/git-lfs/lfs-test-server as lfs module base Imported commit is 3968aac269a77b73924649b9412ae03f7ccd3198 Removed: Dockerfile CONTRIBUTING.md mgmt* script/ vendor/ kvlogger.go .dockerignore .gitignore README.md * Remove config, add JWT support from github.com/mgit-at/lfs-test-server Imported commit f0cdcc5a01599c5a955dc1bbf683bb4acecdba83 * Add LFS settings * Add LFS meta object model * Add LFS routes and initialization * Import github.com/dgrijalva/jwt-go into vendor/ * Adapt LFS module: handlers, routing, meta store * Move LFS routes to /user/repo/info/lfs/* * Add request header checks to LFS BatchHandler / PostHandler * Implement LFS basic authentication * Rework JWT secret generation / load * Implement LFS SSH token authentication with JWT Specification: https://github.com/github/git-lfs/tree/master/docs/api * Integrate LFS settings into install process * Remove LFS objects when repository is deleted Only removes objects from content store when deleted repo is the only referencing repository * Make LFS module stateless Fixes bug where LFS would not work after installation without restarting Gitea * Change 500 'Internal Server Error' to 400 'Bad Request' * Change sql query to xorm call * Remove unneeded type from LFS module * Change internal imports to code.gitea.io/gitea/ * Add Gitea authors copyright * Change basic auth realm to "gitea-lfs" * Add unique indexes to LFS model * Use xorm count function in LFS check on repository delete * Return io.ReadCloser from content store and close after usage * Add LFS info to runWeb() * Export LFS content store base path * LFS file download from UI * Work around git-lfs client issue with unauthenticated requests Returning a dummy Authorization header for unauthenticated requests lets git-lfs client skip asking for auth credentials See: https://github.com/github/git-lfs/issues/1088 * Fix unauthenticated UI downloads from public repositories * Authentication check order, Finish LFS file view logic * Ignore LFS hooks if installed for current OS user Fixes Gitea UI actions for repositories tracking LFS files. Checks for minimum needed git version by parsing the semantic version string. * Hide LFS metafile diff from commit view, marking as binary * Show LFS notice if file in commit view is tracked * Add notbefore/nbf JWT claim * Correct lint suggestions - comments for structs and functions - Add comments to LFS model - Function comment for GetRandomBytesAsBase64 - LFS server function comments and lint variable suggestion * Move secret generation code out of conditional Ensures no LFS code may run with an empty secret * Do not hand out JWT tokens if LFS server support is disabled
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
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
Repository avatars (#6986) * Repository avatars - first variant of code from old work for gogs - add migration 87 - add new option in app.ini - add en-US locale string - add new class in repository.less * Add changed index.css, remove unused template name * Update en-us doc about configuration options * Add comments to new functions, add new option to docker app.ini * Add comment for lint * Remove variable, not needed * Fix formatting * Update swagger api template * Check if avatar exists * Fix avatar link/path checks * Typo * TEXT column can't have a default value * Fixes: - remove old avatar file on upload - use ID in name of avatar file - users may upload same files - add simple tests * Fix fmt check * Generate PNG instead of "static" GIF * More informative comment * Fix error message * Update avatar upload checks: - add file size check - add new option - update config docs - add new string to en-us locale * Fixes: - use FileHEader field for check file size - add new test - upload big image * Fix formatting * Update comments * Update log message * Removed wrong style - not needed * Use Sync2 to migrate * Update repos list view - bigger avatar - fix html blocks alignment * A little adjust avatar size * Use small icons for explore/repo list * Use new cool avatar preparation func by @lafriks * Missing changes for new function * Remove unused import, move imports * Missed new option definition in app.ini Add file size check in user/profile avatar upload * Use smaller field length for Avatar * Use session to update repo DB data, update DeleteAvatar - use session too * Fix err variable definition * As suggested @lafriks - return as soon as possible, code readability
6 years ago
11 years ago
11 years ago
11 years ago
11 years ago
9 years ago
9 years ago
11 years ago
9 years ago
10 years ago
10 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
9 years ago
10 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
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
10 years ago
10 years ago
10 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
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
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
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
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
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
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
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
Template Repositories (#8768) * Start work on templates Signed-off-by: jolheiser <john.olheiser@gmail.com> * Continue work Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix IsTemplate vs IsGenerated Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix tabs vs spaces * Tabs vs Spaces * Add templates to API & start adding tests Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix integration tests Signed-off-by: jolheiser <john.olheiser@gmail.com> * Remove unused User Signed-off-by: jolheiser <john.olheiser@gmail.com> * Move template tests to existing repos Signed-off-by: jolheiser <john.olheiser@gmail.com> * Minor re-check updates and cleanup Signed-off-by: jolheiser <john.olheiser@gmail.com> * make fmt Signed-off-by: jolheiser <john.olheiser@gmail.com> * Test cleanup Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix optionalbool Signed-off-by: jolheiser <john.olheiser@gmail.com> * make fmt Signed-off-by: jolheiser <john.olheiser@gmail.com> * Test fixes and icon change Signed-off-by: jolheiser <john.olheiser@gmail.com> * Add new user and repo for tests Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix tests (finally) Signed-off-by: jolheiser <john.olheiser@gmail.com> * Update meta repo with env variables Signed-off-by: jolheiser <john.olheiser@gmail.com> * Move generation to create page Combine with repo create template Modify API search to prioritize owner for repo Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix tests and coverage Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix swagger and JS lint Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix API searching for own private repos Signed-off-by: jolheiser <john.olheiser@gmail.com> * Change wording Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix repo search test. User had a private repo that didn't show up Signed-off-by: jolheiser <john.olheiser@gmail.com> * Another search test fix Signed-off-by: jolheiser <john.olheiser@gmail.com> * Clarify git content Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> * Feedback updates Signed-off-by: jolheiser <john.olheiser@gmail.com> * Add topics WIP Signed-off-by: jolheiser <john.olheiser@gmail.com> * Finish adding topics Signed-off-by: jolheiser <john.olheiser@gmail.com> * Update locale Signed-off-by: jolheiser <john.olheiser@gmail.com>
5 years ago
11 years ago
Git LFS support v2 (#122) * Import github.com/git-lfs/lfs-test-server as lfs module base Imported commit is 3968aac269a77b73924649b9412ae03f7ccd3198 Removed: Dockerfile CONTRIBUTING.md mgmt* script/ vendor/ kvlogger.go .dockerignore .gitignore README.md * Remove config, add JWT support from github.com/mgit-at/lfs-test-server Imported commit f0cdcc5a01599c5a955dc1bbf683bb4acecdba83 * Add LFS settings * Add LFS meta object model * Add LFS routes and initialization * Import github.com/dgrijalva/jwt-go into vendor/ * Adapt LFS module: handlers, routing, meta store * Move LFS routes to /user/repo/info/lfs/* * Add request header checks to LFS BatchHandler / PostHandler * Implement LFS basic authentication * Rework JWT secret generation / load * Implement LFS SSH token authentication with JWT Specification: https://github.com/github/git-lfs/tree/master/docs/api * Integrate LFS settings into install process * Remove LFS objects when repository is deleted Only removes objects from content store when deleted repo is the only referencing repository * Make LFS module stateless Fixes bug where LFS would not work after installation without restarting Gitea * Change 500 'Internal Server Error' to 400 'Bad Request' * Change sql query to xorm call * Remove unneeded type from LFS module * Change internal imports to code.gitea.io/gitea/ * Add Gitea authors copyright * Change basic auth realm to "gitea-lfs" * Add unique indexes to LFS model * Use xorm count function in LFS check on repository delete * Return io.ReadCloser from content store and close after usage * Add LFS info to runWeb() * Export LFS content store base path * LFS file download from UI * Work around git-lfs client issue with unauthenticated requests Returning a dummy Authorization header for unauthenticated requests lets git-lfs client skip asking for auth credentials See: https://github.com/github/git-lfs/issues/1088 * Fix unauthenticated UI downloads from public repositories * Authentication check order, Finish LFS file view logic * Ignore LFS hooks if installed for current OS user Fixes Gitea UI actions for repositories tracking LFS files. Checks for minimum needed git version by parsing the semantic version string. * Hide LFS metafile diff from commit view, marking as binary * Show LFS notice if file in commit view is tracked * Add notbefore/nbf JWT claim * Correct lint suggestions - comments for structs and functions - Add comments to LFS model - Function comment for GetRandomBytesAsBase64 - LFS server function comments and lint variable suggestion * Move secret generation code out of conditional Ensures no LFS code may run with an empty secret * Do not hand out JWT tokens if LFS server support is disabled
8 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
Template Repositories (#8768) * Start work on templates Signed-off-by: jolheiser <john.olheiser@gmail.com> * Continue work Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix IsTemplate vs IsGenerated Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix tabs vs spaces * Tabs vs Spaces * Add templates to API & start adding tests Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix integration tests Signed-off-by: jolheiser <john.olheiser@gmail.com> * Remove unused User Signed-off-by: jolheiser <john.olheiser@gmail.com> * Move template tests to existing repos Signed-off-by: jolheiser <john.olheiser@gmail.com> * Minor re-check updates and cleanup Signed-off-by: jolheiser <john.olheiser@gmail.com> * make fmt Signed-off-by: jolheiser <john.olheiser@gmail.com> * Test cleanup Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix optionalbool Signed-off-by: jolheiser <john.olheiser@gmail.com> * make fmt Signed-off-by: jolheiser <john.olheiser@gmail.com> * Test fixes and icon change Signed-off-by: jolheiser <john.olheiser@gmail.com> * Add new user and repo for tests Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix tests (finally) Signed-off-by: jolheiser <john.olheiser@gmail.com> * Update meta repo with env variables Signed-off-by: jolheiser <john.olheiser@gmail.com> * Move generation to create page Combine with repo create template Modify API search to prioritize owner for repo Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix tests and coverage Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix swagger and JS lint Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix API searching for own private repos Signed-off-by: jolheiser <john.olheiser@gmail.com> * Change wording Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix repo search test. User had a private repo that didn't show up Signed-off-by: jolheiser <john.olheiser@gmail.com> * Another search test fix Signed-off-by: jolheiser <john.olheiser@gmail.com> * Clarify git content Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> * Feedback updates Signed-off-by: jolheiser <john.olheiser@gmail.com> * Add topics WIP Signed-off-by: jolheiser <john.olheiser@gmail.com> * Finish adding topics Signed-off-by: jolheiser <john.olheiser@gmail.com> * Update locale Signed-off-by: jolheiser <john.olheiser@gmail.com>
5 years ago
9 years ago
Squashed commit of the following: commit 0afcb843d7ffd596991c4885cab768273a6eb42c Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 17:13:29 2016 -0600 Removed Upload stats as the upload table is just a temporary table commit 7ecd73ff5535612d79d471409173ee7f1fcfa157 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 08:42:41 2016 -0600 Fix for CodeMirror mode commit c29b9ab531e2e7af0fb5db24dc17e51027dd1174 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 08:03:33 2016 -0600 Made tabbing in editor use spaces commit 23af384c53206a8a40e11e45bf49d7a149c4adcd Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 07:56:46 2016 -0600 Fix for data-url commit cfb8a97591cb6fc0a92e49563b7b764c524db0e9 Merge: 7fc8a89 991ce42 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 07:42:53 2016 -0600 Merge remote-tracking branch 'gogits/develop' into feature-create-and-edit-repo-file Conflicts: modules/bindata/bindata.go public/js/gogs.js commit 7fc8a89cb495478225b02d613e647f99a1489634 Merge: fd3d86c c03d040 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 07:40:00 2016 -0600 Merge branch 'feature-create-and-edit-repo-file' of github.com:richmahn/gogs into feature-create-and-edit-repo-file commit fd3d86ca6bbc02cfda566a504ffd6b03db4f75ef Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Sun Jul 31 07:39:44 2016 -0600 Code cleanup commit c03d0401c1049eeeccc32ab1f9c3303c130be5ee Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Fri Jul 29 15:38:23 2016 -0600 Code cleanup commit 98e1206ccf9f9a4503c020e3a7830cf9f861dfae Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Thu Jul 28 18:36:01 2016 -0600 Code cleanup and fixes commit c2895dc742f25f8412879c9fa15e18f27f42f194 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Thu Jul 28 18:24:04 2016 -0600 Fixes per Unknwon's requests commit 6aa7e46b21ad4c96e562daa2eac26a8fb408f8ef Merge: 889e9fa ad7ea88 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Thu Jul 28 17:13:43 2016 -0600 Merge remote-tracking branch 'gogits/develop' into feature-create-and-edit-repo-file Conflicts: modules/bindata/bindata.go modules/setting/setting.go commit 889e9faf1bd8559a4979c8f46005d488c1a234d4 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Fri Jul 22 14:09:18 2016 -0600 Fix in gogs.js commit 47603edf223f147b114be65f3bd27bc1e88827a5 Merge: bb57912 cf85e9e Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Fri Jul 22 14:07:36 2016 -0600 Merge remote-tracking branch 'gogits/develop' into feature-create-and-edit-repo-file Conflicts: modules/bindata/bindata.go public/js/gogs.js commit bb5791255867a71c11a77b639db050ad09c597a4 Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Fri Jul 22 14:02:18 2016 -0600 Update for using CodeMirror mode addon commit d10d128c51039be19e2af9c66c63db66a9f2ec6d Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Tue Jul 19 16:12:57 2016 -0600 Update for Edit commit 34a34982025144e3225e389f7849eb6273c1d576 Merge: fa1b752 1c7dcdd Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Tue Jul 19 11:52:02 2016 -0600 Merge remote-tracking branch 'gogits/develop' into feature-create-and-edit-repo-file Conflicts: modules/bindata/bindata.go commit fa1b752be29cd455c5184ddac2ffe80b3489763e Author: Richard Mahn <richard_mahn@wycliffeassociates.org> Date: Fri Jul 15 18:35:42 2016 -0600 Feature for editing, creating, uploading and deleting files
8 years ago
Repository avatars (#6986) * Repository avatars - first variant of code from old work for gogs - add migration 87 - add new option in app.ini - add en-US locale string - add new class in repository.less * Add changed index.css, remove unused template name * Update en-us doc about configuration options * Add comments to new functions, add new option to docker app.ini * Add comment for lint * Remove variable, not needed * Fix formatting * Update swagger api template * Check if avatar exists * Fix avatar link/path checks * Typo * TEXT column can't have a default value * Fixes: - remove old avatar file on upload - use ID in name of avatar file - users may upload same files - add simple tests * Fix fmt check * Generate PNG instead of "static" GIF * More informative comment * Fix error message * Update avatar upload checks: - add file size check - add new option - update config docs - add new string to en-us locale * Fixes: - use FileHEader field for check file size - add new test - upload big image * Fix formatting * Update comments * Update log message * Removed wrong style - not needed * Use Sync2 to migrate * Update repos list view - bigger avatar - fix html blocks alignment * A little adjust avatar size * Use small icons for explore/repo list * Use new cool avatar preparation func by @lafriks * Missing changes for new function * Remove unused import, move imports * Missed new option definition in app.ini Add file size check in user/profile avatar upload * Use smaller field length for Avatar * Use session to update repo DB data, update DeleteAvatar - use session too * Fix err variable definition * As suggested @lafriks - return as soon as possible, code readability
6 years ago
Repository avatars (#6986) * Repository avatars - first variant of code from old work for gogs - add migration 87 - add new option in app.ini - add en-US locale string - add new class in repository.less * Add changed index.css, remove unused template name * Update en-us doc about configuration options * Add comments to new functions, add new option to docker app.ini * Add comment for lint * Remove variable, not needed * Fix formatting * Update swagger api template * Check if avatar exists * Fix avatar link/path checks * Typo * TEXT column can't have a default value * Fixes: - remove old avatar file on upload - use ID in name of avatar file - users may upload same files - add simple tests * Fix fmt check * Generate PNG instead of "static" GIF * More informative comment * Fix error message * Update avatar upload checks: - add file size check - add new option - update config docs - add new string to en-us locale * Fixes: - use FileHEader field for check file size - add new test - upload big image * Fix formatting * Update comments * Update log message * Removed wrong style - not needed * Use Sync2 to migrate * Update repos list view - bigger avatar - fix html blocks alignment * A little adjust avatar size * Use small icons for explore/repo list * Use new cool avatar preparation func by @lafriks * Missing changes for new function * Remove unused import, move imports * Missed new option definition in app.ini Add file size check in user/profile avatar upload * Use smaller field length for Avatar * Use session to update repo DB data, update DeleteAvatar - use session too * Fix err variable definition * As suggested @lafriks - return as soon as possible, code readability
6 years ago
Repository avatars (#6986) * Repository avatars - first variant of code from old work for gogs - add migration 87 - add new option in app.ini - add en-US locale string - add new class in repository.less * Add changed index.css, remove unused template name * Update en-us doc about configuration options * Add comments to new functions, add new option to docker app.ini * Add comment for lint * Remove variable, not needed * Fix formatting * Update swagger api template * Check if avatar exists * Fix avatar link/path checks * Typo * TEXT column can't have a default value * Fixes: - remove old avatar file on upload - use ID in name of avatar file - users may upload same files - add simple tests * Fix fmt check * Generate PNG instead of "static" GIF * More informative comment * Fix error message * Update avatar upload checks: - add file size check - add new option - update config docs - add new string to en-us locale * Fixes: - use FileHEader field for check file size - add new test - upload big image * Fix formatting * Update comments * Update log message * Removed wrong style - not needed * Use Sync2 to migrate * Update repos list view - bigger avatar - fix html blocks alignment * A little adjust avatar size * Use small icons for explore/repo list * Use new cool avatar preparation func by @lafriks * Missing changes for new function * Remove unused import, move imports * Missed new option definition in app.ini Add file size check in user/profile avatar upload * Use smaller field length for Avatar * Use session to update repo DB data, update DeleteAvatar - use session too * Fix err variable definition * As suggested @lafriks - return as soon as possible, code readability
6 years ago
Repository avatars (#6986) * Repository avatars - first variant of code from old work for gogs - add migration 87 - add new option in app.ini - add en-US locale string - add new class in repository.less * Add changed index.css, remove unused template name * Update en-us doc about configuration options * Add comments to new functions, add new option to docker app.ini * Add comment for lint * Remove variable, not needed * Fix formatting * Update swagger api template * Check if avatar exists * Fix avatar link/path checks * Typo * TEXT column can't have a default value * Fixes: - remove old avatar file on upload - use ID in name of avatar file - users may upload same files - add simple tests * Fix fmt check * Generate PNG instead of "static" GIF * More informative comment * Fix error message * Update avatar upload checks: - add file size check - add new option - update config docs - add new string to en-us locale * Fixes: - use FileHEader field for check file size - add new test - upload big image * Fix formatting * Update comments * Update log message * Removed wrong style - not needed * Use Sync2 to migrate * Update repos list view - bigger avatar - fix html blocks alignment * A little adjust avatar size * Use small icons for explore/repo list * Use new cool avatar preparation func by @lafriks * Missing changes for new function * Remove unused import, move imports * Missed new option definition in app.ini Add file size check in user/profile avatar upload * Use smaller field length for Avatar * Use session to update repo DB data, update DeleteAvatar - use session too * Fix err variable definition * As suggested @lafriks - return as soon as possible, code readability
6 years ago
Repository avatars (#6986) * Repository avatars - first variant of code from old work for gogs - add migration 87 - add new option in app.ini - add en-US locale string - add new class in repository.less * Add changed index.css, remove unused template name * Update en-us doc about configuration options * Add comments to new functions, add new option to docker app.ini * Add comment for lint * Remove variable, not needed * Fix formatting * Update swagger api template * Check if avatar exists * Fix avatar link/path checks * Typo * TEXT column can't have a default value * Fixes: - remove old avatar file on upload - use ID in name of avatar file - users may upload same files - add simple tests * Fix fmt check * Generate PNG instead of "static" GIF * More informative comment * Fix error message * Update avatar upload checks: - add file size check - add new option - update config docs - add new string to en-us locale * Fixes: - use FileHEader field for check file size - add new test - upload big image * Fix formatting * Update comments * Update log message * Removed wrong style - not needed * Use Sync2 to migrate * Update repos list view - bigger avatar - fix html blocks alignment * A little adjust avatar size * Use small icons for explore/repo list * Use new cool avatar preparation func by @lafriks * Missing changes for new function * Remove unused import, move imports * Missed new option definition in app.ini Add file size check in user/profile avatar upload * Use smaller field length for Avatar * Use session to update repo DB data, update DeleteAvatar - use session too * Fix err variable definition * As suggested @lafriks - return as soon as possible, code readability
6 years ago
Repository avatars (#6986) * Repository avatars - first variant of code from old work for gogs - add migration 87 - add new option in app.ini - add en-US locale string - add new class in repository.less * Add changed index.css, remove unused template name * Update en-us doc about configuration options * Add comments to new functions, add new option to docker app.ini * Add comment for lint * Remove variable, not needed * Fix formatting * Update swagger api template * Check if avatar exists * Fix avatar link/path checks * Typo * TEXT column can't have a default value * Fixes: - remove old avatar file on upload - use ID in name of avatar file - users may upload same files - add simple tests * Fix fmt check * Generate PNG instead of "static" GIF * More informative comment * Fix error message * Update avatar upload checks: - add file size check - add new option - update config docs - add new string to en-us locale * Fixes: - use FileHEader field for check file size - add new test - upload big image * Fix formatting * Update comments * Update log message * Removed wrong style - not needed * Use Sync2 to migrate * Update repos list view - bigger avatar - fix html blocks alignment * A little adjust avatar size * Use small icons for explore/repo list * Use new cool avatar preparation func by @lafriks * Missing changes for new function * Remove unused import, move imports * Missed new option definition in app.ini Add file size check in user/profile avatar upload * Use smaller field length for Avatar * Use session to update repo DB data, update DeleteAvatar - use session too * Fix err variable definition * As suggested @lafriks - return as soon as possible, code readability
6 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Copyright 2017 The Gitea 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 models
  6. import (
  7. "bytes"
  8. "crypto/md5"
  9. "errors"
  10. "fmt"
  11. "html/template"
  12. // Needed for jpeg support
  13. _ "image/jpeg"
  14. "image/png"
  15. "io/ioutil"
  16. "net/url"
  17. "os"
  18. "path"
  19. "path/filepath"
  20. "sort"
  21. "strconv"
  22. "strings"
  23. "time"
  24. "code.gitea.io/gitea/modules/avatar"
  25. "code.gitea.io/gitea/modules/git"
  26. "code.gitea.io/gitea/modules/log"
  27. "code.gitea.io/gitea/modules/markup"
  28. "code.gitea.io/gitea/modules/options"
  29. "code.gitea.io/gitea/modules/setting"
  30. "code.gitea.io/gitea/modules/structs"
  31. api "code.gitea.io/gitea/modules/structs"
  32. "code.gitea.io/gitea/modules/sync"
  33. "code.gitea.io/gitea/modules/timeutil"
  34. "code.gitea.io/gitea/modules/util"
  35. "github.com/mcuadros/go-version"
  36. "github.com/unknwon/com"
  37. ini "gopkg.in/ini.v1"
  38. "xorm.io/builder"
  39. )
  40. // RepoWorkingPool represents a working pool to order the parallel changes to the same repository
  41. var RepoWorkingPool = sync.NewExclusivePool()
  42. var (
  43. // ErrMirrorNotExist mirror does not exist error
  44. ErrMirrorNotExist = errors.New("Mirror does not exist")
  45. // ErrNameEmpty name is empty error
  46. ErrNameEmpty = errors.New("Name is empty")
  47. )
  48. var (
  49. // Gitignores contains the gitiginore files
  50. Gitignores []string
  51. // Licenses contains the license files
  52. Licenses []string
  53. // Readmes contains the readme files
  54. Readmes []string
  55. // LabelTemplates contains the label template files
  56. LabelTemplates []string
  57. // ItemsPerPage maximum items per page in forks, watchers and stars of a repo
  58. ItemsPerPage = 40
  59. )
  60. // loadRepoConfig loads the repository config
  61. func loadRepoConfig() {
  62. // Load .gitignore and license files and readme templates.
  63. types := []string{"gitignore", "license", "readme", "label"}
  64. typeFiles := make([][]string, 4)
  65. for i, t := range types {
  66. files, err := options.Dir(t)
  67. if err != nil {
  68. log.Fatal("Failed to get %s files: %v", t, err)
  69. }
  70. customPath := path.Join(setting.CustomPath, "options", t)
  71. if com.IsDir(customPath) {
  72. customFiles, err := com.StatDir(customPath)
  73. if err != nil {
  74. log.Fatal("Failed to get custom %s files: %v", t, err)
  75. }
  76. for _, f := range customFiles {
  77. if !com.IsSliceContainsStr(files, f) {
  78. files = append(files, f)
  79. }
  80. }
  81. }
  82. typeFiles[i] = files
  83. }
  84. Gitignores = typeFiles[0]
  85. Licenses = typeFiles[1]
  86. Readmes = typeFiles[2]
  87. LabelTemplates = typeFiles[3]
  88. sort.Strings(Gitignores)
  89. sort.Strings(Licenses)
  90. sort.Strings(Readmes)
  91. sort.Strings(LabelTemplates)
  92. // Filter out invalid names and promote preferred licenses.
  93. sortedLicenses := make([]string, 0, len(Licenses))
  94. for _, name := range setting.Repository.PreferredLicenses {
  95. if com.IsSliceContainsStr(Licenses, name) {
  96. sortedLicenses = append(sortedLicenses, name)
  97. }
  98. }
  99. for _, name := range Licenses {
  100. if !com.IsSliceContainsStr(setting.Repository.PreferredLicenses, name) {
  101. sortedLicenses = append(sortedLicenses, name)
  102. }
  103. }
  104. Licenses = sortedLicenses
  105. }
  106. // NewRepoContext creates a new repository context
  107. func NewRepoContext() {
  108. loadRepoConfig()
  109. RemoveAllWithNotice("Clean up repository temporary data", filepath.Join(setting.AppDataPath, "tmp"))
  110. }
  111. // RepositoryStatus defines the status of repository
  112. type RepositoryStatus int
  113. // all kinds of RepositoryStatus
  114. const (
  115. RepositoryReady RepositoryStatus = iota // a normal repository
  116. RepositoryBeingMigrated // repository is migrating
  117. )
  118. // Repository represents a git repository.
  119. type Repository struct {
  120. ID int64 `xorm:"pk autoincr"`
  121. OwnerID int64 `xorm:"UNIQUE(s) index"`
  122. OwnerName string `xorm:"-"`
  123. Owner *User `xorm:"-"`
  124. LowerName string `xorm:"UNIQUE(s) INDEX NOT NULL"`
  125. Name string `xorm:"INDEX NOT NULL"`
  126. Description string `xorm:"TEXT"`
  127. Website string `xorm:"VARCHAR(2048)"`
  128. OriginalServiceType structs.GitServiceType `xorm:"index"`
  129. OriginalURL string `xorm:"VARCHAR(2048)"`
  130. DefaultBranch string
  131. NumWatches int
  132. NumStars int
  133. NumForks int
  134. NumIssues int
  135. NumClosedIssues int
  136. NumOpenIssues int `xorm:"-"`
  137. NumPulls int
  138. NumClosedPulls int
  139. NumOpenPulls int `xorm:"-"`
  140. NumMilestones int `xorm:"NOT NULL DEFAULT 0"`
  141. NumClosedMilestones int `xorm:"NOT NULL DEFAULT 0"`
  142. NumOpenMilestones int `xorm:"-"`
  143. NumReleases int `xorm:"-"`
  144. IsPrivate bool `xorm:"INDEX"`
  145. IsEmpty bool `xorm:"INDEX"`
  146. IsArchived bool `xorm:"INDEX"`
  147. IsMirror bool `xorm:"INDEX"`
  148. *Mirror `xorm:"-"`
  149. Status RepositoryStatus `xorm:"NOT NULL DEFAULT 0"`
  150. RenderingMetas map[string]string `xorm:"-"`
  151. Units []*RepoUnit `xorm:"-"`
  152. IsFork bool `xorm:"INDEX NOT NULL DEFAULT false"`
  153. ForkID int64 `xorm:"INDEX"`
  154. BaseRepo *Repository `xorm:"-"`
  155. IsTemplate bool `xorm:"INDEX NOT NULL DEFAULT false"`
  156. TemplateID int64 `xorm:"INDEX"`
  157. TemplateRepo *Repository `xorm:"-"`
  158. Size int64 `xorm:"NOT NULL DEFAULT 0"`
  159. IndexerStatus *RepoIndexerStatus `xorm:"-"`
  160. IsFsckEnabled bool `xorm:"NOT NULL DEFAULT true"`
  161. CloseIssuesViaCommitInAnyBranch bool `xorm:"NOT NULL DEFAULT false"`
  162. Topics []string `xorm:"TEXT JSON"`
  163. // Avatar: ID(10-20)-md5(32) - must fit into 64 symbols
  164. Avatar string `xorm:"VARCHAR(64)"`
  165. CreatedUnix timeutil.TimeStamp `xorm:"INDEX created"`
  166. UpdatedUnix timeutil.TimeStamp `xorm:"INDEX updated"`
  167. }
  168. // ColorFormat returns a colored string to represent this repo
  169. func (repo *Repository) ColorFormat(s fmt.State) {
  170. var ownerName interface{}
  171. if repo.OwnerName != "" {
  172. ownerName = repo.OwnerName
  173. } else if repo.Owner != nil {
  174. ownerName = repo.Owner.Name
  175. } else {
  176. ownerName = log.NewColoredIDValue(strconv.FormatInt(repo.OwnerID, 10))
  177. }
  178. log.ColorFprintf(s, "%d:%s/%s",
  179. log.NewColoredIDValue(repo.ID),
  180. ownerName,
  181. repo.Name)
  182. }
  183. // IsBeingMigrated indicates that repository is being migtated
  184. func (repo *Repository) IsBeingMigrated() bool {
  185. return repo.Status == RepositoryBeingMigrated
  186. }
  187. // IsBeingCreated indicates that repository is being migrated or forked
  188. func (repo *Repository) IsBeingCreated() bool {
  189. return repo.IsBeingMigrated()
  190. }
  191. // AfterLoad is invoked from XORM after setting the values of all fields of this object.
  192. func (repo *Repository) AfterLoad() {
  193. // FIXME: use models migration to solve all at once.
  194. if len(repo.DefaultBranch) == 0 {
  195. repo.DefaultBranch = "master"
  196. }
  197. repo.NumOpenIssues = repo.NumIssues - repo.NumClosedIssues
  198. repo.NumOpenPulls = repo.NumPulls - repo.NumClosedPulls
  199. repo.NumOpenMilestones = repo.NumMilestones - repo.NumClosedMilestones
  200. }
  201. // MustOwner always returns a valid *User object to avoid
  202. // conceptually impossible error handling.
  203. // It creates a fake object that contains error details
  204. // when error occurs.
  205. func (repo *Repository) MustOwner() *User {
  206. return repo.mustOwner(x)
  207. }
  208. // MustOwnerName always returns valid owner name to avoid
  209. // conceptually impossible error handling.
  210. // It returns "error" and logs error details when error
  211. // occurs.
  212. func (repo *Repository) MustOwnerName() string {
  213. return repo.mustOwnerName(x)
  214. }
  215. // FullName returns the repository full name
  216. func (repo *Repository) FullName() string {
  217. return repo.MustOwnerName() + "/" + repo.Name
  218. }
  219. // HTMLURL returns the repository HTML URL
  220. func (repo *Repository) HTMLURL() string {
  221. return setting.AppURL + repo.FullName()
  222. }
  223. // APIURL returns the repository API URL
  224. func (repo *Repository) APIURL() string {
  225. return setting.AppURL + path.Join("api/v1/repos", repo.FullName())
  226. }
  227. // APIFormat converts a Repository to api.Repository
  228. func (repo *Repository) APIFormat(mode AccessMode) *api.Repository {
  229. return repo.innerAPIFormat(x, mode, false)
  230. }
  231. // GetCommitsCountCacheKey returns cache key used for commits count caching.
  232. func (repo *Repository) GetCommitsCountCacheKey(contextName string, isRef bool) string {
  233. var prefix string
  234. if isRef {
  235. prefix = "ref"
  236. } else {
  237. prefix = "commit"
  238. }
  239. return fmt.Sprintf("commits-count-%d-%s-%s", repo.ID, prefix, contextName)
  240. }
  241. func (repo *Repository) innerAPIFormat(e Engine, mode AccessMode, isParent bool) *api.Repository {
  242. var parent *api.Repository
  243. cloneLink := repo.cloneLink(e, false)
  244. permission := &api.Permission{
  245. Admin: mode >= AccessModeAdmin,
  246. Push: mode >= AccessModeWrite,
  247. Pull: mode >= AccessModeRead,
  248. }
  249. if !isParent {
  250. err := repo.getBaseRepo(e)
  251. if err != nil {
  252. log.Error("APIFormat: %v", err)
  253. }
  254. if repo.BaseRepo != nil {
  255. parent = repo.BaseRepo.innerAPIFormat(e, mode, true)
  256. }
  257. }
  258. hasIssues := false
  259. var externalTracker *api.ExternalTracker
  260. var internalTracker *api.InternalTracker
  261. if unit, err := repo.getUnit(e, UnitTypeIssues); err == nil {
  262. config := unit.IssuesConfig()
  263. hasIssues = true
  264. internalTracker = &api.InternalTracker{
  265. EnableTimeTracker: config.EnableTimetracker,
  266. AllowOnlyContributorsToTrackTime: config.AllowOnlyContributorsToTrackTime,
  267. EnableIssueDependencies: config.EnableDependencies,
  268. }
  269. } else if unit, err := repo.getUnit(e, UnitTypeExternalTracker); err == nil {
  270. config := unit.ExternalTrackerConfig()
  271. hasIssues = true
  272. externalTracker = &api.ExternalTracker{
  273. ExternalTrackerURL: config.ExternalTrackerURL,
  274. ExternalTrackerFormat: config.ExternalTrackerFormat,
  275. ExternalTrackerStyle: config.ExternalTrackerStyle,
  276. }
  277. }
  278. hasWiki := false
  279. var externalWiki *api.ExternalWiki
  280. if _, err := repo.getUnit(e, UnitTypeWiki); err == nil {
  281. hasWiki = true
  282. } else if unit, err := repo.getUnit(e, UnitTypeExternalWiki); err == nil {
  283. hasWiki = true
  284. config := unit.ExternalWikiConfig()
  285. externalWiki = &api.ExternalWiki{
  286. ExternalWikiURL: config.ExternalWikiURL,
  287. }
  288. }
  289. hasPullRequests := false
  290. ignoreWhitespaceConflicts := false
  291. allowMerge := false
  292. allowRebase := false
  293. allowRebaseMerge := false
  294. allowSquash := false
  295. if unit, err := repo.getUnit(e, UnitTypePullRequests); err == nil {
  296. config := unit.PullRequestsConfig()
  297. hasPullRequests = true
  298. ignoreWhitespaceConflicts = config.IgnoreWhitespaceConflicts
  299. allowMerge = config.AllowMerge
  300. allowRebase = config.AllowRebase
  301. allowRebaseMerge = config.AllowRebaseMerge
  302. allowSquash = config.AllowSquash
  303. }
  304. return &api.Repository{
  305. ID: repo.ID,
  306. Owner: repo.Owner.APIFormat(),
  307. Name: repo.Name,
  308. FullName: repo.FullName(),
  309. Description: repo.Description,
  310. Private: repo.IsPrivate,
  311. Template: repo.IsTemplate,
  312. Empty: repo.IsEmpty,
  313. Archived: repo.IsArchived,
  314. Size: int(repo.Size / 1024),
  315. Fork: repo.IsFork,
  316. Parent: parent,
  317. Mirror: repo.IsMirror,
  318. HTMLURL: repo.HTMLURL(),
  319. SSHURL: cloneLink.SSH,
  320. CloneURL: cloneLink.HTTPS,
  321. Website: repo.Website,
  322. Stars: repo.NumStars,
  323. Forks: repo.NumForks,
  324. Watchers: repo.NumWatches,
  325. OpenIssues: repo.NumOpenIssues,
  326. OpenPulls: repo.NumOpenPulls,
  327. Releases: repo.NumReleases,
  328. DefaultBranch: repo.DefaultBranch,
  329. Created: repo.CreatedUnix.AsTime(),
  330. Updated: repo.UpdatedUnix.AsTime(),
  331. Permissions: permission,
  332. HasIssues: hasIssues,
  333. ExternalTracker: externalTracker,
  334. InternalTracker: internalTracker,
  335. HasWiki: hasWiki,
  336. ExternalWiki: externalWiki,
  337. HasPullRequests: hasPullRequests,
  338. IgnoreWhitespaceConflicts: ignoreWhitespaceConflicts,
  339. AllowMerge: allowMerge,
  340. AllowRebase: allowRebase,
  341. AllowRebaseMerge: allowRebaseMerge,
  342. AllowSquash: allowSquash,
  343. AvatarURL: repo.avatarLink(e),
  344. }
  345. }
  346. func (repo *Repository) getUnits(e Engine) (err error) {
  347. if repo.Units != nil {
  348. return nil
  349. }
  350. repo.Units, err = getUnitsByRepoID(e, repo.ID)
  351. return err
  352. }
  353. // CheckUnitUser check whether user could visit the unit of this repository
  354. func (repo *Repository) CheckUnitUser(userID int64, isAdmin bool, unitType UnitType) bool {
  355. return repo.checkUnitUser(x, userID, isAdmin, unitType)
  356. }
  357. func (repo *Repository) checkUnitUser(e Engine, userID int64, isAdmin bool, unitType UnitType) bool {
  358. if isAdmin {
  359. return true
  360. }
  361. user, err := getUserByID(e, userID)
  362. if err != nil {
  363. return false
  364. }
  365. perm, err := getUserRepoPermission(e, repo, user)
  366. if err != nil {
  367. return false
  368. }
  369. return perm.CanRead(unitType)
  370. }
  371. // UnitEnabled if this repository has the given unit enabled
  372. func (repo *Repository) UnitEnabled(tp UnitType) bool {
  373. if err := repo.getUnits(x); err != nil {
  374. log.Warn("Error loading repository (ID: %d) units: %s", repo.ID, err.Error())
  375. }
  376. for _, unit := range repo.Units {
  377. if unit.Type == tp {
  378. return true
  379. }
  380. }
  381. return false
  382. }
  383. // ErrUnitTypeNotExist represents a "UnitTypeNotExist" kind of error.
  384. type ErrUnitTypeNotExist struct {
  385. UT UnitType
  386. }
  387. // IsErrUnitTypeNotExist checks if an error is a ErrUnitNotExist.
  388. func IsErrUnitTypeNotExist(err error) bool {
  389. _, ok := err.(ErrUnitTypeNotExist)
  390. return ok
  391. }
  392. func (err ErrUnitTypeNotExist) Error() string {
  393. return fmt.Sprintf("Unit type does not exist: %s", err.UT.String())
  394. }
  395. // MustGetUnit always returns a RepoUnit object
  396. func (repo *Repository) MustGetUnit(tp UnitType) *RepoUnit {
  397. ru, err := repo.GetUnit(tp)
  398. if err == nil {
  399. return ru
  400. }
  401. if tp == UnitTypeExternalWiki {
  402. return &RepoUnit{
  403. Type: tp,
  404. Config: new(ExternalWikiConfig),
  405. }
  406. } else if tp == UnitTypeExternalTracker {
  407. return &RepoUnit{
  408. Type: tp,
  409. Config: new(ExternalTrackerConfig),
  410. }
  411. } else if tp == UnitTypePullRequests {
  412. return &RepoUnit{
  413. Type: tp,
  414. Config: new(PullRequestsConfig),
  415. }
  416. } else if tp == UnitTypeIssues {
  417. return &RepoUnit{
  418. Type: tp,
  419. Config: new(IssuesConfig),
  420. }
  421. }
  422. return &RepoUnit{
  423. Type: tp,
  424. Config: new(UnitConfig),
  425. }
  426. }
  427. // GetUnit returns a RepoUnit object
  428. func (repo *Repository) GetUnit(tp UnitType) (*RepoUnit, error) {
  429. return repo.getUnit(x, tp)
  430. }
  431. func (repo *Repository) getUnit(e Engine, tp UnitType) (*RepoUnit, error) {
  432. if err := repo.getUnits(e); err != nil {
  433. return nil, err
  434. }
  435. for _, unit := range repo.Units {
  436. if unit.Type == tp {
  437. return unit, nil
  438. }
  439. }
  440. return nil, ErrUnitTypeNotExist{tp}
  441. }
  442. func (repo *Repository) getOwner(e Engine) (err error) {
  443. if repo.Owner != nil {
  444. return nil
  445. }
  446. repo.Owner, err = getUserByID(e, repo.OwnerID)
  447. return err
  448. }
  449. // GetOwner returns the repository owner
  450. func (repo *Repository) GetOwner() error {
  451. return repo.getOwner(x)
  452. }
  453. func (repo *Repository) mustOwner(e Engine) *User {
  454. if err := repo.getOwner(e); err != nil {
  455. return &User{
  456. Name: "error",
  457. FullName: err.Error(),
  458. }
  459. }
  460. return repo.Owner
  461. }
  462. func (repo *Repository) getOwnerName(e Engine) error {
  463. if len(repo.OwnerName) > 0 {
  464. return nil
  465. }
  466. if repo.Owner != nil {
  467. repo.OwnerName = repo.Owner.Name
  468. return nil
  469. }
  470. u := new(User)
  471. has, err := e.ID(repo.OwnerID).Cols("name").Get(u)
  472. if err != nil {
  473. return err
  474. } else if !has {
  475. return ErrUserNotExist{repo.OwnerID, "", 0}
  476. }
  477. repo.OwnerName = u.Name
  478. return nil
  479. }
  480. // GetOwnerName returns the repository owner name
  481. func (repo *Repository) GetOwnerName() error {
  482. return repo.getOwnerName(x)
  483. }
  484. func (repo *Repository) mustOwnerName(e Engine) string {
  485. if err := repo.getOwnerName(e); err != nil {
  486. log.Error("Error loading repository owner name: %v", err)
  487. return "error"
  488. }
  489. return repo.OwnerName
  490. }
  491. // ComposeMetas composes a map of metas for properly rendering issue links and external issue trackers.
  492. func (repo *Repository) ComposeMetas() map[string]string {
  493. if repo.RenderingMetas == nil {
  494. metas := map[string]string{
  495. "user": repo.MustOwner().Name,
  496. "repo": repo.Name,
  497. "repoPath": repo.RepoPath(),
  498. }
  499. unit, err := repo.GetUnit(UnitTypeExternalTracker)
  500. if err == nil {
  501. metas["format"] = unit.ExternalTrackerConfig().ExternalTrackerFormat
  502. switch unit.ExternalTrackerConfig().ExternalTrackerStyle {
  503. case markup.IssueNameStyleAlphanumeric:
  504. metas["style"] = markup.IssueNameStyleAlphanumeric
  505. default:
  506. metas["style"] = markup.IssueNameStyleNumeric
  507. }
  508. }
  509. if repo.Owner.IsOrganization() {
  510. teams := make([]string, 0, 5)
  511. _ = x.Table("team_repo").
  512. Join("INNER", "team", "team.id = team_repo.team_id").
  513. Where("team_repo.repo_id = ?", repo.ID).
  514. Select("team.lower_name").
  515. OrderBy("team.lower_name").
  516. Find(&teams)
  517. metas["teams"] = "," + strings.Join(teams, ",") + ","
  518. metas["org"] = repo.Owner.LowerName
  519. }
  520. repo.RenderingMetas = metas
  521. }
  522. return repo.RenderingMetas
  523. }
  524. // DeleteWiki removes the actual and local copy of repository wiki.
  525. func (repo *Repository) DeleteWiki() error {
  526. return repo.deleteWiki(x)
  527. }
  528. func (repo *Repository) deleteWiki(e Engine) error {
  529. wikiPaths := []string{repo.WikiPath()}
  530. for _, wikiPath := range wikiPaths {
  531. removeAllWithNotice(e, "Delete repository wiki", wikiPath)
  532. }
  533. _, err := e.Where("repo_id = ?", repo.ID).And("type = ?", UnitTypeWiki).Delete(new(RepoUnit))
  534. return err
  535. }
  536. func (repo *Repository) getAssignees(e Engine) (_ []*User, err error) {
  537. if err = repo.getOwner(e); err != nil {
  538. return nil, err
  539. }
  540. accesses := make([]*Access, 0, 10)
  541. if err = e.
  542. Where("repo_id = ? AND mode >= ?", repo.ID, AccessModeWrite).
  543. Find(&accesses); err != nil {
  544. return nil, err
  545. }
  546. // Leave a seat for owner itself to append later, but if owner is an organization
  547. // and just waste 1 unit is cheaper than re-allocate memory once.
  548. users := make([]*User, 0, len(accesses)+1)
  549. if len(accesses) > 0 {
  550. userIDs := make([]int64, len(accesses))
  551. for i := 0; i < len(accesses); i++ {
  552. userIDs[i] = accesses[i].UserID
  553. }
  554. if err = e.In("id", userIDs).Find(&users); err != nil {
  555. return nil, err
  556. }
  557. }
  558. if !repo.Owner.IsOrganization() {
  559. users = append(users, repo.Owner)
  560. }
  561. return users, nil
  562. }
  563. // GetAssignees returns all users that have write access and can be assigned to issues
  564. // of the repository,
  565. func (repo *Repository) GetAssignees() (_ []*User, err error) {
  566. return repo.getAssignees(x)
  567. }
  568. // GetMilestoneByID returns the milestone belongs to repository by given ID.
  569. func (repo *Repository) GetMilestoneByID(milestoneID int64) (*Milestone, error) {
  570. return GetMilestoneByRepoID(repo.ID, milestoneID)
  571. }
  572. // IssueStats returns number of open and closed repository issues by given filter mode.
  573. func (repo *Repository) IssueStats(uid int64, filterMode int, isPull bool) (int64, int64) {
  574. return GetRepoIssueStats(repo.ID, uid, filterMode, isPull)
  575. }
  576. // GetMirror sets the repository mirror, returns an error upon failure
  577. func (repo *Repository) GetMirror() (err error) {
  578. repo.Mirror, err = GetMirrorByRepoID(repo.ID)
  579. return err
  580. }
  581. // GetBaseRepo populates repo.BaseRepo for a fork repository and
  582. // returns an error on failure (NOTE: no error is returned for
  583. // non-fork repositories, and BaseRepo will be left untouched)
  584. func (repo *Repository) GetBaseRepo() (err error) {
  585. return repo.getBaseRepo(x)
  586. }
  587. func (repo *Repository) getBaseRepo(e Engine) (err error) {
  588. if !repo.IsFork {
  589. return nil
  590. }
  591. repo.BaseRepo, err = getRepositoryByID(e, repo.ForkID)
  592. return err
  593. }
  594. // IsGenerated returns whether _this_ repository was generated from a template
  595. func (repo *Repository) IsGenerated() bool {
  596. return repo.TemplateID != 0
  597. }
  598. // GetTemplateRepo populates repo.TemplateRepo for a generated repository and
  599. // returns an error on failure (NOTE: no error is returned for
  600. // non-generated repositories, and TemplateRepo will be left untouched)
  601. func (repo *Repository) GetTemplateRepo() (err error) {
  602. return repo.getTemplateRepo(x)
  603. }
  604. func (repo *Repository) getTemplateRepo(e Engine) (err error) {
  605. if !repo.IsGenerated() {
  606. return nil
  607. }
  608. repo.TemplateRepo, err = getRepositoryByID(e, repo.TemplateID)
  609. return err
  610. }
  611. func (repo *Repository) repoPath(e Engine) string {
  612. return RepoPath(repo.mustOwnerName(e), repo.Name)
  613. }
  614. // RepoPath returns the repository path
  615. func (repo *Repository) RepoPath() string {
  616. return repo.repoPath(x)
  617. }
  618. // GitConfigPath returns the path to a repository's git config/ directory
  619. func GitConfigPath(repoPath string) string {
  620. return filepath.Join(repoPath, "config")
  621. }
  622. // GitConfigPath returns the repository git config path
  623. func (repo *Repository) GitConfigPath() string {
  624. return GitConfigPath(repo.RepoPath())
  625. }
  626. // RelLink returns the repository relative link
  627. func (repo *Repository) RelLink() string {
  628. return "/" + repo.FullName()
  629. }
  630. // Link returns the repository link
  631. func (repo *Repository) Link() string {
  632. return setting.AppSubURL + "/" + repo.FullName()
  633. }
  634. // ComposeCompareURL returns the repository comparison URL
  635. func (repo *Repository) ComposeCompareURL(oldCommitID, newCommitID string) string {
  636. return fmt.Sprintf("%s/%s/compare/%s...%s", repo.MustOwner().Name, repo.Name, oldCommitID, newCommitID)
  637. }
  638. // UpdateDefaultBranch updates the default branch
  639. func (repo *Repository) UpdateDefaultBranch() error {
  640. _, err := x.ID(repo.ID).Cols("default_branch").Update(repo)
  641. return err
  642. }
  643. // IsOwnedBy returns true when user owns this repository
  644. func (repo *Repository) IsOwnedBy(userID int64) bool {
  645. return repo.OwnerID == userID
  646. }
  647. func (repo *Repository) updateSize(e Engine) error {
  648. size, err := util.GetDirectorySize(repo.repoPath(e))
  649. if err != nil {
  650. return fmt.Errorf("UpdateSize: %v", err)
  651. }
  652. repo.Size = size
  653. _, err = e.ID(repo.ID).Cols("size").Update(repo)
  654. return err
  655. }
  656. // UpdateSize updates the repository size, calculating it using util.GetDirectorySize
  657. func (repo *Repository) UpdateSize() error {
  658. return repo.updateSize(x)
  659. }
  660. // CanUserFork returns true if specified user can fork repository.
  661. func (repo *Repository) CanUserFork(user *User) (bool, error) {
  662. if user == nil {
  663. return false, nil
  664. }
  665. if repo.OwnerID != user.ID && !user.HasForkedRepo(repo.ID) {
  666. return true, nil
  667. }
  668. if err := user.GetOwnedOrganizations(); err != nil {
  669. return false, err
  670. }
  671. for _, org := range user.OwnedOrgs {
  672. if repo.OwnerID != org.ID && !org.HasForkedRepo(repo.ID) {
  673. return true, nil
  674. }
  675. }
  676. return false, nil
  677. }
  678. // CanUserDelete returns true if user could delete the repository
  679. func (repo *Repository) CanUserDelete(user *User) (bool, error) {
  680. if user.IsAdmin || user.ID == repo.OwnerID {
  681. return true, nil
  682. }
  683. if err := repo.GetOwner(); err != nil {
  684. return false, err
  685. }
  686. if repo.Owner.IsOrganization() {
  687. isOwner, err := repo.Owner.IsOwnedBy(user.ID)
  688. if err != nil {
  689. return false, err
  690. } else if isOwner {
  691. return true, nil
  692. }
  693. }
  694. return false, nil
  695. }
  696. // CanEnablePulls returns true if repository meets the requirements of accepting pulls.
  697. func (repo *Repository) CanEnablePulls() bool {
  698. return !repo.IsMirror && !repo.IsEmpty
  699. }
  700. // AllowsPulls returns true if repository meets the requirements of accepting pulls and has them enabled.
  701. func (repo *Repository) AllowsPulls() bool {
  702. return repo.CanEnablePulls() && repo.UnitEnabled(UnitTypePullRequests)
  703. }
  704. // CanEnableEditor returns true if repository meets the requirements of web editor.
  705. func (repo *Repository) CanEnableEditor() bool {
  706. return !repo.IsMirror
  707. }
  708. // GetReaders returns all users that have explicit read access or higher to the repository.
  709. func (repo *Repository) GetReaders() (_ []*User, err error) {
  710. return repo.getUsersWithAccessMode(x, AccessModeRead)
  711. }
  712. // GetWriters returns all users that have write access to the repository.
  713. func (repo *Repository) GetWriters() (_ []*User, err error) {
  714. return repo.getUsersWithAccessMode(x, AccessModeWrite)
  715. }
  716. // IsReader returns true if user has explicit read access or higher to the repository.
  717. func (repo *Repository) IsReader(userID int64) (bool, error) {
  718. if repo.OwnerID == userID {
  719. return true, nil
  720. }
  721. return x.Where("repo_id = ? AND user_id = ? AND mode >= ?", repo.ID, userID, AccessModeRead).Get(&Access{})
  722. }
  723. // getUsersWithAccessMode returns users that have at least given access mode to the repository.
  724. func (repo *Repository) getUsersWithAccessMode(e Engine, mode AccessMode) (_ []*User, err error) {
  725. if err = repo.getOwner(e); err != nil {
  726. return nil, err
  727. }
  728. accesses := make([]*Access, 0, 10)
  729. if err = e.Where("repo_id = ? AND mode >= ?", repo.ID, mode).Find(&accesses); err != nil {
  730. return nil, err
  731. }
  732. // Leave a seat for owner itself to append later, but if owner is an organization
  733. // and just waste 1 unit is cheaper than re-allocate memory once.
  734. users := make([]*User, 0, len(accesses)+1)
  735. if len(accesses) > 0 {
  736. userIDs := make([]int64, len(accesses))
  737. for i := 0; i < len(accesses); i++ {
  738. userIDs[i] = accesses[i].UserID
  739. }
  740. if err = e.In("id", userIDs).Find(&users); err != nil {
  741. return nil, err
  742. }
  743. }
  744. if !repo.Owner.IsOrganization() {
  745. users = append(users, repo.Owner)
  746. }
  747. return users, nil
  748. }
  749. // DescriptionHTML does special handles to description and return HTML string.
  750. func (repo *Repository) DescriptionHTML() template.HTML {
  751. desc, err := markup.RenderDescriptionHTML([]byte(repo.Description), repo.HTMLURL(), repo.ComposeMetas())
  752. if err != nil {
  753. log.Error("Failed to render description for %s (ID: %d): %v", repo.Name, repo.ID, err)
  754. return template.HTML(markup.Sanitize(repo.Description))
  755. }
  756. return template.HTML(markup.Sanitize(string(desc)))
  757. }
  758. // PatchPath returns corresponding patch file path of repository by given issue ID.
  759. func (repo *Repository) PatchPath(index int64) (string, error) {
  760. return repo.patchPath(x, index)
  761. }
  762. func (repo *Repository) patchPath(e Engine, index int64) (string, error) {
  763. if err := repo.getOwner(e); err != nil {
  764. return "", err
  765. }
  766. return filepath.Join(RepoPath(repo.Owner.Name, repo.Name), "pulls", com.ToStr(index)+".patch"), nil
  767. }
  768. // SavePatch saves patch data to corresponding location by given issue ID.
  769. func (repo *Repository) SavePatch(index int64, patch []byte) error {
  770. return repo.savePatch(x, index, patch)
  771. }
  772. func (repo *Repository) savePatch(e Engine, index int64, patch []byte) error {
  773. patchPath, err := repo.patchPath(e, index)
  774. if err != nil {
  775. return fmt.Errorf("PatchPath: %v", err)
  776. }
  777. dir := filepath.Dir(patchPath)
  778. if err := os.MkdirAll(dir, os.ModePerm); err != nil {
  779. return fmt.Errorf("Failed to create dir %s: %v", dir, err)
  780. }
  781. if err = ioutil.WriteFile(patchPath, patch, 0644); err != nil {
  782. return fmt.Errorf("WriteFile: %v", err)
  783. }
  784. return nil
  785. }
  786. func isRepositoryExist(e Engine, u *User, repoName string) (bool, error) {
  787. has, err := e.Get(&Repository{
  788. OwnerID: u.ID,
  789. LowerName: strings.ToLower(repoName),
  790. })
  791. return has && com.IsDir(RepoPath(u.Name, repoName)), err
  792. }
  793. // IsRepositoryExist returns true if the repository with given name under user has already existed.
  794. func IsRepositoryExist(u *User, repoName string) (bool, error) {
  795. return isRepositoryExist(x, u, repoName)
  796. }
  797. // CloneLink represents different types of clone URLs of repository.
  798. type CloneLink struct {
  799. SSH string
  800. HTTPS string
  801. Git string
  802. }
  803. // ComposeHTTPSCloneURL returns HTTPS clone URL based on given owner and repository name.
  804. func ComposeHTTPSCloneURL(owner, repo string) string {
  805. return fmt.Sprintf("%s%s/%s.git", setting.AppURL, url.PathEscape(owner), url.PathEscape(repo))
  806. }
  807. func (repo *Repository) cloneLink(e Engine, isWiki bool) *CloneLink {
  808. repoName := repo.Name
  809. if isWiki {
  810. repoName += ".wiki"
  811. }
  812. sshUser := setting.RunUser
  813. if setting.SSH.StartBuiltinServer {
  814. sshUser = setting.SSH.BuiltinServerUser
  815. }
  816. repo.Owner = repo.mustOwner(e)
  817. cl := new(CloneLink)
  818. if setting.SSH.Port != 22 {
  819. cl.SSH = fmt.Sprintf("ssh://%s@%s:%d/%s/%s.git", sshUser, setting.SSH.Domain, setting.SSH.Port, repo.Owner.Name, repoName)
  820. } else if setting.Repository.UseCompatSSHURI {
  821. cl.SSH = fmt.Sprintf("ssh://%s@%s/%s/%s.git", sshUser, setting.SSH.Domain, repo.Owner.Name, repoName)
  822. } else {
  823. cl.SSH = fmt.Sprintf("%s@%s:%s/%s.git", sshUser, setting.SSH.Domain, repo.Owner.Name, repoName)
  824. }
  825. cl.HTTPS = ComposeHTTPSCloneURL(repo.Owner.Name, repoName)
  826. return cl
  827. }
  828. // CloneLink returns clone URLs of repository.
  829. func (repo *Repository) CloneLink() (cl *CloneLink) {
  830. return repo.cloneLink(x, false)
  831. }
  832. /*
  833. GitHub, GitLab, Gogs: *.wiki.git
  834. BitBucket: *.git/wiki
  835. */
  836. var commonWikiURLSuffixes = []string{".wiki.git", ".git/wiki"}
  837. // wikiRemoteURL returns accessible repository URL for wiki if exists.
  838. // Otherwise, it returns an empty string.
  839. func wikiRemoteURL(remote string) string {
  840. remote = strings.TrimSuffix(remote, ".git")
  841. for _, suffix := range commonWikiURLSuffixes {
  842. wikiURL := remote + suffix
  843. if git.IsRepoURLAccessible(wikiURL) {
  844. return wikiURL
  845. }
  846. }
  847. return ""
  848. }
  849. // CheckCreateRepository check if could created a repository
  850. func CheckCreateRepository(doer, u *User, name string) error {
  851. if !doer.CanCreateRepo() {
  852. return ErrReachLimitOfRepo{u.MaxRepoCreation}
  853. }
  854. if err := IsUsableRepoName(name); err != nil {
  855. return err
  856. }
  857. has, err := isRepositoryExist(x, u, name)
  858. if err != nil {
  859. return fmt.Errorf("IsRepositoryExist: %v", err)
  860. } else if has {
  861. return ErrRepoAlreadyExist{u.Name, name}
  862. }
  863. return nil
  864. }
  865. // MigrateRepositoryGitData starts migrating git related data after created migrating repository
  866. func MigrateRepositoryGitData(doer, u *User, repo *Repository, opts api.MigrateRepoOption) (*Repository, error) {
  867. repoPath := RepoPath(u.Name, opts.RepoName)
  868. if u.IsOrganization() {
  869. t, err := u.GetOwnerTeam()
  870. if err != nil {
  871. return nil, err
  872. }
  873. repo.NumWatches = t.NumMembers
  874. } else {
  875. repo.NumWatches = 1
  876. }
  877. migrateTimeout := time.Duration(setting.Git.Timeout.Migrate) * time.Second
  878. var err error
  879. if err = os.RemoveAll(repoPath); err != nil {
  880. return repo, fmt.Errorf("Failed to remove %s: %v", repoPath, err)
  881. }
  882. if err = git.Clone(opts.CloneAddr, repoPath, git.CloneRepoOptions{
  883. Mirror: true,
  884. Quiet: true,
  885. Timeout: migrateTimeout,
  886. }); err != nil {
  887. return repo, fmt.Errorf("Clone: %v", err)
  888. }
  889. if opts.Wiki {
  890. wikiPath := WikiPath(u.Name, opts.RepoName)
  891. wikiRemotePath := wikiRemoteURL(opts.CloneAddr)
  892. if len(wikiRemotePath) > 0 {
  893. if err := os.RemoveAll(wikiPath); err != nil {
  894. return repo, fmt.Errorf("Failed to remove %s: %v", wikiPath, err)
  895. }
  896. if err = git.Clone(wikiRemotePath, wikiPath, git.CloneRepoOptions{
  897. Mirror: true,
  898. Quiet: true,
  899. Timeout: migrateTimeout,
  900. Branch: "master",
  901. }); err != nil {
  902. log.Warn("Clone wiki: %v", err)
  903. if err := os.RemoveAll(wikiPath); err != nil {
  904. return repo, fmt.Errorf("Failed to remove %s: %v", wikiPath, err)
  905. }
  906. }
  907. }
  908. }
  909. gitRepo, err := git.OpenRepository(repoPath)
  910. if err != nil {
  911. return repo, fmt.Errorf("OpenRepository: %v", err)
  912. }
  913. defer gitRepo.Close()
  914. repo.IsEmpty, err = gitRepo.IsEmpty()
  915. if err != nil {
  916. return repo, fmt.Errorf("git.IsEmpty: %v", err)
  917. }
  918. if !opts.Releases && !repo.IsEmpty {
  919. // Try to get HEAD branch and set it as default branch.
  920. headBranch, err := gitRepo.GetHEADBranch()
  921. if err != nil {
  922. return repo, fmt.Errorf("GetHEADBranch: %v", err)
  923. }
  924. if headBranch != nil {
  925. repo.DefaultBranch = headBranch.Name
  926. }
  927. if err = SyncReleasesWithTags(repo, gitRepo); err != nil {
  928. log.Error("Failed to synchronize tags to releases for repository: %v", err)
  929. }
  930. }
  931. if err = repo.UpdateSize(); err != nil {
  932. log.Error("Failed to update size for repository: %v", err)
  933. }
  934. if opts.Mirror {
  935. if _, err = x.InsertOne(&Mirror{
  936. RepoID: repo.ID,
  937. Interval: setting.Mirror.DefaultInterval,
  938. EnablePrune: true,
  939. NextUpdateUnix: timeutil.TimeStampNow().AddDuration(setting.Mirror.DefaultInterval),
  940. }); err != nil {
  941. return repo, fmt.Errorf("InsertOne: %v", err)
  942. }
  943. repo.IsMirror = true
  944. err = UpdateRepository(repo, false)
  945. } else {
  946. repo, err = CleanUpMigrateInfo(repo)
  947. }
  948. if err != nil && !repo.IsEmpty {
  949. UpdateRepoIndexer(repo)
  950. }
  951. return repo, err
  952. }
  953. // cleanUpMigrateGitConfig removes mirror info which prevents "push --all".
  954. // This also removes possible user credentials.
  955. func cleanUpMigrateGitConfig(configPath string) error {
  956. cfg, err := ini.Load(configPath)
  957. if err != nil {
  958. return fmt.Errorf("open config file: %v", err)
  959. }
  960. cfg.DeleteSection("remote \"origin\"")
  961. if err = cfg.SaveToIndent(configPath, "\t"); err != nil {
  962. return fmt.Errorf("save config file: %v", err)
  963. }
  964. return nil
  965. }
  966. // createDelegateHooks creates all the hooks scripts for the repo
  967. func createDelegateHooks(repoPath string) (err error) {
  968. var (
  969. hookNames = []string{"pre-receive", "update", "post-receive"}
  970. hookTpls = []string{
  971. fmt.Sprintf("#!/usr/bin/env %s\ndata=$(cat)\nexitcodes=\"\"\nhookname=$(basename $0)\nGIT_DIR=${GIT_DIR:-$(dirname $0)}\n\nfor hook in ${GIT_DIR}/hooks/${hookname}.d/*; do\ntest -x \"${hook}\" || continue\necho \"${data}\" | \"${hook}\"\nexitcodes=\"${exitcodes} $?\"\ndone\n\nfor i in ${exitcodes}; do\n[ ${i} -eq 0 ] || exit ${i}\ndone\n", setting.ScriptType),
  972. fmt.Sprintf("#!/usr/bin/env %s\nexitcodes=\"\"\nhookname=$(basename $0)\nGIT_DIR=${GIT_DIR:-$(dirname $0)}\n\nfor hook in ${GIT_DIR}/hooks/${hookname}.d/*; do\ntest -x \"${hook}\" || continue\n\"${hook}\" $1 $2 $3\nexitcodes=\"${exitcodes} $?\"\ndone\n\nfor i in ${exitcodes}; do\n[ ${i} -eq 0 ] || exit ${i}\ndone\n", setting.ScriptType),
  973. fmt.Sprintf("#!/usr/bin/env %s\ndata=$(cat)\nexitcodes=\"\"\nhookname=$(basename $0)\nGIT_DIR=${GIT_DIR:-$(dirname $0)}\n\nfor hook in ${GIT_DIR}/hooks/${hookname}.d/*; do\ntest -x \"${hook}\" || continue\necho \"${data}\" | \"${hook}\"\nexitcodes=\"${exitcodes} $?\"\ndone\n\nfor i in ${exitcodes}; do\n[ ${i} -eq 0 ] || exit ${i}\ndone\n", setting.ScriptType),
  974. }
  975. giteaHookTpls = []string{
  976. fmt.Sprintf("#!/usr/bin/env %s\n\"%s\" hook --config='%s' pre-receive\n", setting.ScriptType, setting.AppPath, setting.CustomConf),
  977. fmt.Sprintf("#!/usr/bin/env %s\n\"%s\" hook --config='%s' update $1 $2 $3\n", setting.ScriptType, setting.AppPath, setting.CustomConf),
  978. fmt.Sprintf("#!/usr/bin/env %s\n\"%s\" hook --config='%s' post-receive\n", setting.ScriptType, setting.AppPath, setting.CustomConf),
  979. }
  980. )
  981. hookDir := filepath.Join(repoPath, "hooks")
  982. for i, hookName := range hookNames {
  983. oldHookPath := filepath.Join(hookDir, hookName)
  984. newHookPath := filepath.Join(hookDir, hookName+".d", "gitea")
  985. if err := os.MkdirAll(filepath.Join(hookDir, hookName+".d"), os.ModePerm); err != nil {
  986. return fmt.Errorf("create hooks dir '%s': %v", filepath.Join(hookDir, hookName+".d"), err)
  987. }
  988. // WARNING: This will override all old server-side hooks
  989. if err = ioutil.WriteFile(oldHookPath, []byte(hookTpls[i]), 0777); err != nil {
  990. return fmt.Errorf("write old hook file '%s': %v", oldHookPath, err)
  991. }
  992. if err = ioutil.WriteFile(newHookPath, []byte(giteaHookTpls[i]), 0777); err != nil {
  993. return fmt.Errorf("write new hook file '%s': %v", newHookPath, err)
  994. }
  995. }
  996. return nil
  997. }
  998. // CleanUpMigrateInfo finishes migrating repository and/or wiki with things that don't need to be done for mirrors.
  999. func CleanUpMigrateInfo(repo *Repository) (*Repository, error) {
  1000. repoPath := repo.RepoPath()
  1001. if err := createDelegateHooks(repoPath); err != nil {
  1002. return repo, fmt.Errorf("createDelegateHooks: %v", err)
  1003. }
  1004. if repo.HasWiki() {
  1005. if err := createDelegateHooks(repo.WikiPath()); err != nil {
  1006. return repo, fmt.Errorf("createDelegateHooks.(wiki): %v", err)
  1007. }
  1008. }
  1009. _, err := git.NewCommand("remote", "rm", "origin").RunInDir(repoPath)
  1010. if err != nil && !strings.HasPrefix(err.Error(), "exit status 128 - fatal: No such remote ") {
  1011. return repo, fmt.Errorf("CleanUpMigrateInfo: %v", err)
  1012. }
  1013. if repo.HasWiki() {
  1014. if err := cleanUpMigrateGitConfig(path.Join(repo.WikiPath(), "config")); err != nil {
  1015. return repo, fmt.Errorf("cleanUpMigrateGitConfig (wiki): %v", err)
  1016. }
  1017. }
  1018. return repo, UpdateRepository(repo, false)
  1019. }
  1020. // initRepoCommit temporarily changes with work directory.
  1021. func initRepoCommit(tmpPath string, u *User) (err error) {
  1022. commitTimeStr := time.Now().Format(time.RFC3339)
  1023. sig := u.NewGitSig()
  1024. // Because this may call hooks we should pass in the environment
  1025. env := append(os.Environ(),
  1026. "GIT_AUTHOR_NAME="+sig.Name,
  1027. "GIT_AUTHOR_EMAIL="+sig.Email,
  1028. "GIT_AUTHOR_DATE="+commitTimeStr,
  1029. "GIT_COMMITTER_NAME="+sig.Name,
  1030. "GIT_COMMITTER_EMAIL="+sig.Email,
  1031. "GIT_COMMITTER_DATE="+commitTimeStr,
  1032. )
  1033. if stdout, err := git.NewCommand("add", "--all").
  1034. SetDescription(fmt.Sprintf("initRepoCommit (git add): %s", tmpPath)).
  1035. RunInDir(tmpPath); err != nil {
  1036. log.Error("git add --all failed: Stdout: %s\nError: %v", stdout, err)
  1037. return fmt.Errorf("git add --all: %v", err)
  1038. }
  1039. binVersion, err := git.BinVersion()
  1040. if err != nil {
  1041. return fmt.Errorf("Unable to get git version: %v", err)
  1042. }
  1043. args := []string{
  1044. "commit", fmt.Sprintf("--author='%s <%s>'", sig.Name, sig.Email),
  1045. "-m", "Initial commit",
  1046. }
  1047. if version.Compare(binVersion, "1.7.9", ">=") {
  1048. sign, keyID := SignInitialCommit(tmpPath, u)
  1049. if sign {
  1050. args = append(args, "-S"+keyID)
  1051. } else if version.Compare(binVersion, "2.0.0", ">=") {
  1052. args = append(args, "--no-gpg-sign")
  1053. }
  1054. }
  1055. if stdout, err := git.NewCommand(args...).
  1056. SetDescription(fmt.Sprintf("initRepoCommit (git commit): %s", tmpPath)).
  1057. RunInDirWithEnv(tmpPath, env); err != nil {
  1058. log.Error("Failed to commit: %v: Stdout: %s\nError: %v", args, stdout, err)
  1059. return fmt.Errorf("git commit: %v", err)
  1060. }
  1061. if stdout, err := git.NewCommand("push", "origin", "master").
  1062. SetDescription(fmt.Sprintf("initRepoCommit (git push): %s", tmpPath)).
  1063. RunInDir(tmpPath); err != nil {
  1064. log.Error("Failed to push back to master: Stdout: %s\nError: %v", stdout, err)
  1065. return fmt.Errorf("git push: %v", err)
  1066. }
  1067. return nil
  1068. }
  1069. // CreateRepoOptions contains the create repository options
  1070. type CreateRepoOptions struct {
  1071. Name string
  1072. Description string
  1073. OriginalURL string
  1074. Gitignores string
  1075. IssueLabels string
  1076. License string
  1077. Readme string
  1078. IsPrivate bool
  1079. IsMirror bool
  1080. AutoInit bool
  1081. Status RepositoryStatus
  1082. }
  1083. func getRepoInitFile(tp, name string) ([]byte, error) {
  1084. cleanedName := strings.TrimLeft(path.Clean("/"+name), "/")
  1085. relPath := path.Join("options", tp, cleanedName)
  1086. // Use custom file when available.
  1087. customPath := path.Join(setting.CustomPath, relPath)
  1088. if com.IsFile(customPath) {
  1089. return ioutil.ReadFile(customPath)
  1090. }
  1091. switch tp {
  1092. case "readme":
  1093. return options.Readme(cleanedName)
  1094. case "gitignore":
  1095. return options.Gitignore(cleanedName)
  1096. case "license":
  1097. return options.License(cleanedName)
  1098. case "label":
  1099. return options.Labels(cleanedName)
  1100. default:
  1101. return []byte{}, fmt.Errorf("Invalid init file type")
  1102. }
  1103. }
  1104. func prepareRepoCommit(e Engine, repo *Repository, tmpDir, repoPath string, opts CreateRepoOptions) error {
  1105. commitTimeStr := time.Now().Format(time.RFC3339)
  1106. authorSig := repo.Owner.NewGitSig()
  1107. // Because this may call hooks we should pass in the environment
  1108. env := append(os.Environ(),
  1109. "GIT_AUTHOR_NAME="+authorSig.Name,
  1110. "GIT_AUTHOR_EMAIL="+authorSig.Email,
  1111. "GIT_AUTHOR_DATE="+commitTimeStr,
  1112. "GIT_COMMITTER_NAME="+authorSig.Name,
  1113. "GIT_COMMITTER_EMAIL="+authorSig.Email,
  1114. "GIT_COMMITTER_DATE="+commitTimeStr,
  1115. )
  1116. // Clone to temporary path and do the init commit.
  1117. if stdout, err := git.NewCommand("clone", repoPath, tmpDir).
  1118. SetDescription(fmt.Sprintf("initRepository (git clone): %s to %s", repoPath, tmpDir)).
  1119. RunInDirWithEnv("", env); err != nil {
  1120. log.Error("Failed to clone from %v into %s: stdout: %s\nError: %v", repo, tmpDir, stdout, err)
  1121. return fmt.Errorf("git clone: %v", err)
  1122. }
  1123. // README
  1124. data, err := getRepoInitFile("readme", opts.Readme)
  1125. if err != nil {
  1126. return fmt.Errorf("getRepoInitFile[%s]: %v", opts.Readme, err)
  1127. }
  1128. cloneLink := repo.cloneLink(e, false)
  1129. match := map[string]string{
  1130. "Name": repo.Name,
  1131. "Description": repo.Description,
  1132. "CloneURL.SSH": cloneLink.SSH,
  1133. "CloneURL.HTTPS": cloneLink.HTTPS,
  1134. }
  1135. if err = ioutil.WriteFile(filepath.Join(tmpDir, "README.md"),
  1136. []byte(com.Expand(string(data), match)), 0644); err != nil {
  1137. return fmt.Errorf("write README.md: %v", err)
  1138. }
  1139. // .gitignore
  1140. if len(opts.Gitignores) > 0 {
  1141. var buf bytes.Buffer
  1142. names := strings.Split(opts.Gitignores, ",")
  1143. for _, name := range names {
  1144. data, err = getRepoInitFile("gitignore", name)
  1145. if err != nil {
  1146. return fmt.Errorf("getRepoInitFile[%s]: %v", name, err)
  1147. }
  1148. buf.WriteString("# ---> " + name + "\n")
  1149. buf.Write(data)
  1150. buf.WriteString("\n")
  1151. }
  1152. if buf.Len() > 0 {
  1153. if err = ioutil.WriteFile(filepath.Join(tmpDir, ".gitignore"), buf.Bytes(), 0644); err != nil {
  1154. return fmt.Errorf("write .gitignore: %v", err)
  1155. }
  1156. }
  1157. }
  1158. // LICENSE
  1159. if len(opts.License) > 0 {
  1160. data, err = getRepoInitFile("license", opts.License)
  1161. if err != nil {
  1162. return fmt.Errorf("getRepoInitFile[%s]: %v", opts.License, err)
  1163. }
  1164. if err = ioutil.WriteFile(filepath.Join(tmpDir, "LICENSE"), data, 0644); err != nil {
  1165. return fmt.Errorf("write LICENSE: %v", err)
  1166. }
  1167. }
  1168. return nil
  1169. }
  1170. func checkInitRepository(repoPath string) (err error) {
  1171. // Somehow the directory could exist.
  1172. if com.IsExist(repoPath) {
  1173. return fmt.Errorf("initRepository: path already exists: %s", repoPath)
  1174. }
  1175. // Init git bare new repository.
  1176. if err = git.InitRepository(repoPath, true); err != nil {
  1177. return fmt.Errorf("InitRepository: %v", err)
  1178. } else if err = createDelegateHooks(repoPath); err != nil {
  1179. return fmt.Errorf("createDelegateHooks: %v", err)
  1180. }
  1181. return nil
  1182. }
  1183. // InitRepository initializes README and .gitignore if needed.
  1184. func initRepository(e Engine, repoPath string, u *User, repo *Repository, opts CreateRepoOptions) (err error) {
  1185. if err = checkInitRepository(repoPath); err != nil {
  1186. return err
  1187. }
  1188. tmpDir := filepath.Join(os.TempDir(), "gitea-"+repo.Name+"-"+com.ToStr(time.Now().Nanosecond()))
  1189. // Initialize repository according to user's choice.
  1190. if opts.AutoInit {
  1191. if err := os.MkdirAll(tmpDir, os.ModePerm); err != nil {
  1192. return fmt.Errorf("Failed to create dir %s: %v", tmpDir, err)
  1193. }
  1194. defer os.RemoveAll(tmpDir)
  1195. if err = prepareRepoCommit(e, repo, tmpDir, repoPath, opts); err != nil {
  1196. return fmt.Errorf("prepareRepoCommit: %v", err)
  1197. }
  1198. // Apply changes and commit.
  1199. if err = initRepoCommit(tmpDir, u); err != nil {
  1200. return fmt.Errorf("initRepoCommit: %v", err)
  1201. }
  1202. }
  1203. // Re-fetch the repository from database before updating it (else it would
  1204. // override changes that were done earlier with sql)
  1205. if repo, err = getRepositoryByID(e, repo.ID); err != nil {
  1206. return fmt.Errorf("getRepositoryByID: %v", err)
  1207. }
  1208. if !opts.AutoInit {
  1209. repo.IsEmpty = true
  1210. }
  1211. repo.DefaultBranch = "master"
  1212. if err = updateRepository(e, repo, false); err != nil {
  1213. return fmt.Errorf("updateRepository: %v", err)
  1214. }
  1215. return nil
  1216. }
  1217. var (
  1218. reservedRepoNames = []string{".", ".."}
  1219. reservedRepoPatterns = []string{"*.git", "*.wiki"}
  1220. )
  1221. // IsUsableRepoName returns true when repository is usable
  1222. func IsUsableRepoName(name string) error {
  1223. return isUsableName(reservedRepoNames, reservedRepoPatterns, name)
  1224. }
  1225. func createRepository(e Engine, doer, u *User, repo *Repository) (err error) {
  1226. if err = IsUsableRepoName(repo.Name); err != nil {
  1227. return err
  1228. }
  1229. has, err := isRepositoryExist(e, u, repo.Name)
  1230. if err != nil {
  1231. return fmt.Errorf("IsRepositoryExist: %v", err)
  1232. } else if has {
  1233. return ErrRepoAlreadyExist{u.Name, repo.Name}
  1234. }
  1235. if _, err = e.Insert(repo); err != nil {
  1236. return err
  1237. }
  1238. if err = deleteRepoRedirect(e, u.ID, repo.Name); err != nil {
  1239. return err
  1240. }
  1241. // insert units for repo
  1242. var units = make([]RepoUnit, 0, len(DefaultRepoUnits))
  1243. for _, tp := range DefaultRepoUnits {
  1244. if tp == UnitTypeIssues {
  1245. units = append(units, RepoUnit{
  1246. RepoID: repo.ID,
  1247. Type: tp,
  1248. Config: &IssuesConfig{
  1249. EnableTimetracker: setting.Service.DefaultEnableTimetracking,
  1250. AllowOnlyContributorsToTrackTime: setting.Service.DefaultAllowOnlyContributorsToTrackTime,
  1251. EnableDependencies: setting.Service.DefaultEnableDependencies,
  1252. },
  1253. })
  1254. } else if tp == UnitTypePullRequests {
  1255. units = append(units, RepoUnit{
  1256. RepoID: repo.ID,
  1257. Type: tp,
  1258. Config: &PullRequestsConfig{AllowMerge: true, AllowRebase: true, AllowRebaseMerge: true, AllowSquash: true},
  1259. })
  1260. } else {
  1261. units = append(units, RepoUnit{
  1262. RepoID: repo.ID,
  1263. Type: tp,
  1264. })
  1265. }
  1266. }
  1267. if _, err = e.Insert(&units); err != nil {
  1268. return err
  1269. }
  1270. // Remember visibility preference.
  1271. u.LastRepoVisibility = repo.IsPrivate
  1272. if err = updateUserCols(e, u, "last_repo_visibility"); err != nil {
  1273. return fmt.Errorf("updateUser: %v", err)
  1274. }
  1275. if _, err = e.Incr("num_repos").ID(u.ID).Update(new(User)); err != nil {
  1276. return fmt.Errorf("increment user total_repos: %v", err)
  1277. }
  1278. u.NumRepos++
  1279. // Give access to all members in teams with access to all repositories.
  1280. if u.IsOrganization() {
  1281. if err := u.GetTeams(); err != nil {
  1282. return fmt.Errorf("GetTeams: %v", err)
  1283. }
  1284. for _, t := range u.Teams {
  1285. if t.IncludesAllRepositories {
  1286. if err := t.addRepository(e, repo); err != nil {
  1287. return fmt.Errorf("addRepository: %v", err)
  1288. }
  1289. }
  1290. }
  1291. if isAdmin, err := isUserRepoAdmin(e, repo, doer); err != nil {
  1292. return fmt.Errorf("isUserRepoAdmin: %v", err)
  1293. } else if !isAdmin {
  1294. // Make creator repo admin if it wan't assigned automatically
  1295. if err = repo.addCollaborator(e, doer); err != nil {
  1296. return fmt.Errorf("AddCollaborator: %v", err)
  1297. }
  1298. if err = repo.changeCollaborationAccessMode(e, doer.ID, AccessModeAdmin); err != nil {
  1299. return fmt.Errorf("ChangeCollaborationAccessMode: %v", err)
  1300. }
  1301. }
  1302. } else if err = repo.recalculateAccesses(e); err != nil {
  1303. // Organization automatically called this in addRepository method.
  1304. return fmt.Errorf("recalculateAccesses: %v", err)
  1305. }
  1306. if setting.Service.AutoWatchNewRepos {
  1307. if err = watchRepo(e, doer.ID, repo.ID, true); err != nil {
  1308. return fmt.Errorf("watchRepo: %v", err)
  1309. }
  1310. }
  1311. if err = copyDefaultWebhooksToRepo(e, repo.ID); err != nil {
  1312. return fmt.Errorf("copyDefaultWebhooksToRepo: %v", err)
  1313. }
  1314. return nil
  1315. }
  1316. // CreateRepository creates a repository for the user/organization.
  1317. func CreateRepository(doer, u *User, opts CreateRepoOptions) (_ *Repository, err error) {
  1318. if !doer.IsAdmin && !u.CanCreateRepo() {
  1319. return nil, ErrReachLimitOfRepo{u.MaxRepoCreation}
  1320. }
  1321. repo := &Repository{
  1322. OwnerID: u.ID,
  1323. Owner: u,
  1324. Name: opts.Name,
  1325. LowerName: strings.ToLower(opts.Name),
  1326. Description: opts.Description,
  1327. OriginalURL: opts.OriginalURL,
  1328. IsPrivate: opts.IsPrivate,
  1329. IsFsckEnabled: !opts.IsMirror,
  1330. CloseIssuesViaCommitInAnyBranch: setting.Repository.DefaultCloseIssuesViaCommitsInAnyBranch,
  1331. Status: opts.Status,
  1332. IsEmpty: !opts.AutoInit,
  1333. }
  1334. sess := x.NewSession()
  1335. defer sess.Close()
  1336. if err = sess.Begin(); err != nil {
  1337. return nil, err
  1338. }
  1339. if err = createRepository(sess, doer, u, repo); err != nil {
  1340. return nil, err
  1341. }
  1342. // No need for init mirror.
  1343. if !opts.IsMirror {
  1344. repoPath := RepoPath(u.Name, repo.Name)
  1345. if err = initRepository(sess, repoPath, u, repo, opts); err != nil {
  1346. if err2 := os.RemoveAll(repoPath); err2 != nil {
  1347. log.Error("initRepository: %v", err)
  1348. return nil, fmt.Errorf(
  1349. "delete repo directory %s/%s failed(2): %v", u.Name, repo.Name, err2)
  1350. }
  1351. return nil, fmt.Errorf("initRepository: %v", err)
  1352. }
  1353. // Initialize Issue Labels if selected
  1354. if len(opts.IssueLabels) > 0 {
  1355. if err = initalizeLabels(sess, repo.ID, opts.IssueLabels); err != nil {
  1356. return nil, fmt.Errorf("initalizeLabels: %v", err)
  1357. }
  1358. }
  1359. if stdout, err := git.NewCommand("update-server-info").
  1360. SetDescription(fmt.Sprintf("CreateRepository(git update-server-info): %s", repoPath)).
  1361. RunInDir(repoPath); err != nil {
  1362. log.Error("CreateRepitory(git update-server-info) in %v: Stdout: %s\nError: %v", repo, stdout, err)
  1363. return nil, fmt.Errorf("CreateRepository(git update-server-info): %v", err)
  1364. }
  1365. }
  1366. if err = sess.Commit(); err != nil {
  1367. return nil, err
  1368. }
  1369. return repo, err
  1370. }
  1371. func countRepositories(userID int64, private bool) int64 {
  1372. sess := x.Where("id > 0")
  1373. if userID > 0 {
  1374. sess.And("owner_id = ?", userID)
  1375. }
  1376. if !private {
  1377. sess.And("is_private=?", false)
  1378. }
  1379. count, err := sess.Count(new(Repository))
  1380. if err != nil {
  1381. log.Error("countRepositories: %v", err)
  1382. }
  1383. return count
  1384. }
  1385. // CountRepositories returns number of repositories.
  1386. // Argument private only takes effect when it is false,
  1387. // set it true to count all repositories.
  1388. func CountRepositories(private bool) int64 {
  1389. return countRepositories(-1, private)
  1390. }
  1391. // CountUserRepositories returns number of repositories user owns.
  1392. // Argument private only takes effect when it is false,
  1393. // set it true to count all repositories.
  1394. func CountUserRepositories(userID int64, private bool) int64 {
  1395. return countRepositories(userID, private)
  1396. }
  1397. // RepoPath returns repository path by given user and repository name.
  1398. func RepoPath(userName, repoName string) string {
  1399. return filepath.Join(UserPath(userName), strings.ToLower(repoName)+".git")
  1400. }
  1401. // TransferOwnership transfers all corresponding setting from old user to new one.
  1402. func TransferOwnership(doer *User, newOwnerName string, repo *Repository) error {
  1403. newOwner, err := GetUserByName(newOwnerName)
  1404. if err != nil {
  1405. return fmt.Errorf("get new owner '%s': %v", newOwnerName, err)
  1406. }
  1407. // Check if new owner has repository with same name.
  1408. has, err := IsRepositoryExist(newOwner, repo.Name)
  1409. if err != nil {
  1410. return fmt.Errorf("IsRepositoryExist: %v", err)
  1411. } else if has {
  1412. return ErrRepoAlreadyExist{newOwnerName, repo.Name}
  1413. }
  1414. sess := x.NewSession()
  1415. defer sess.Close()
  1416. if err = sess.Begin(); err != nil {
  1417. return fmt.Errorf("sess.Begin: %v", err)
  1418. }
  1419. oldOwner := repo.Owner
  1420. // Note: we have to set value here to make sure recalculate accesses is based on
  1421. // new owner.
  1422. repo.OwnerID = newOwner.ID
  1423. repo.Owner = newOwner
  1424. // Update repository.
  1425. if _, err := sess.ID(repo.ID).Update(repo); err != nil {
  1426. return fmt.Errorf("update owner: %v", err)
  1427. }
  1428. // Remove redundant collaborators.
  1429. collaborators, err := repo.getCollaborators(sess)
  1430. if err != nil {
  1431. return fmt.Errorf("getCollaborators: %v", err)
  1432. }
  1433. // Dummy object.
  1434. collaboration := &Collaboration{RepoID: repo.ID}
  1435. for _, c := range collaborators {
  1436. if c.ID != newOwner.ID {
  1437. isMember, err := isOrganizationMember(sess, newOwner.ID, c.ID)
  1438. if err != nil {
  1439. return fmt.Errorf("IsOrgMember: %v", err)
  1440. } else if !isMember {
  1441. continue
  1442. }
  1443. }
  1444. collaboration.UserID = c.ID
  1445. if _, err = sess.Delete(collaboration); err != nil {
  1446. return fmt.Errorf("remove collaborator '%d': %v", c.ID, err)
  1447. }
  1448. }
  1449. // Remove old team-repository relations.
  1450. if oldOwner.IsOrganization() {
  1451. if err = oldOwner.removeOrgRepo(sess, repo.ID); err != nil {
  1452. return fmt.Errorf("removeOrgRepo: %v", err)
  1453. }
  1454. }
  1455. if newOwner.IsOrganization() {
  1456. if err := newOwner.GetTeams(); err != nil {
  1457. return fmt.Errorf("GetTeams: %v", err)
  1458. }
  1459. for _, t := range newOwner.Teams {
  1460. if t.IncludesAllRepositories {
  1461. if err := t.addRepository(sess, repo); err != nil {
  1462. return fmt.Errorf("addRepository: %v", err)
  1463. }
  1464. }
  1465. }
  1466. } else if err = repo.recalculateAccesses(sess); err != nil {
  1467. // Organization called this in addRepository method.
  1468. return fmt.Errorf("recalculateAccesses: %v", err)
  1469. }
  1470. // Update repository count.
  1471. if _, err = sess.Exec("UPDATE `user` SET num_repos=num_repos+1 WHERE id=?", newOwner.ID); err != nil {
  1472. return fmt.Errorf("increase new owner repository count: %v", err)
  1473. } else if _, err = sess.Exec("UPDATE `user` SET num_repos=num_repos-1 WHERE id=?", oldOwner.ID); err != nil {
  1474. return fmt.Errorf("decrease old owner repository count: %v", err)
  1475. }
  1476. if err = watchRepo(sess, doer.ID, repo.ID, true); err != nil {
  1477. return fmt.Errorf("watchRepo: %v", err)
  1478. }
  1479. // Remove watch for organization.
  1480. if oldOwner.IsOrganization() {
  1481. if err = watchRepo(sess, oldOwner.ID, repo.ID, false); err != nil {
  1482. return fmt.Errorf("watchRepo [false]: %v", err)
  1483. }
  1484. }
  1485. // Rename remote repository to new path and delete local copy.
  1486. dir := UserPath(newOwner.Name)
  1487. if err := os.MkdirAll(dir, os.ModePerm); err != nil {
  1488. return fmt.Errorf("Failed to create dir %s: %v", dir, err)
  1489. }
  1490. if err = os.Rename(RepoPath(oldOwner.Name, repo.Name), RepoPath(newOwner.Name, repo.Name)); err != nil {
  1491. return fmt.Errorf("rename repository directory: %v", err)
  1492. }
  1493. // Rename remote wiki repository to new path and delete local copy.
  1494. wikiPath := WikiPath(oldOwner.Name, repo.Name)
  1495. if com.IsExist(wikiPath) {
  1496. if err = os.Rename(wikiPath, WikiPath(newOwner.Name, repo.Name)); err != nil {
  1497. return fmt.Errorf("rename repository wiki: %v", err)
  1498. }
  1499. }
  1500. // If there was previously a redirect at this location, remove it.
  1501. if err = deleteRepoRedirect(sess, newOwner.ID, repo.Name); err != nil {
  1502. return fmt.Errorf("delete repo redirect: %v", err)
  1503. }
  1504. if err := NewRepoRedirect(DBContext{sess}, oldOwner.ID, repo.ID, repo.Name, repo.Name); err != nil {
  1505. return fmt.Errorf("NewRepoRedirect: %v", err)
  1506. }
  1507. return sess.Commit()
  1508. }
  1509. // ChangeRepositoryName changes all corresponding setting from old repository name to new one.
  1510. func ChangeRepositoryName(doer *User, repo *Repository, newRepoName string) (err error) {
  1511. oldRepoName := repo.Name
  1512. newRepoName = strings.ToLower(newRepoName)
  1513. if err = IsUsableRepoName(newRepoName); err != nil {
  1514. return err
  1515. }
  1516. if err := repo.GetOwner(); err != nil {
  1517. return err
  1518. }
  1519. has, err := IsRepositoryExist(repo.Owner, newRepoName)
  1520. if err != nil {
  1521. return fmt.Errorf("IsRepositoryExist: %v", err)
  1522. } else if has {
  1523. return ErrRepoAlreadyExist{repo.Owner.Name, newRepoName}
  1524. }
  1525. newRepoPath := RepoPath(repo.Owner.Name, newRepoName)
  1526. if err = os.Rename(repo.RepoPath(), newRepoPath); err != nil {
  1527. return fmt.Errorf("rename repository directory: %v", err)
  1528. }
  1529. wikiPath := repo.WikiPath()
  1530. if com.IsExist(wikiPath) {
  1531. if err = os.Rename(wikiPath, WikiPath(repo.Owner.Name, newRepoName)); err != nil {
  1532. return fmt.Errorf("rename repository wiki: %v", err)
  1533. }
  1534. }
  1535. sess := x.NewSession()
  1536. defer sess.Close()
  1537. if err = sess.Begin(); err != nil {
  1538. return fmt.Errorf("sess.Begin: %v", err)
  1539. }
  1540. // If there was previously a redirect at this location, remove it.
  1541. if err = deleteRepoRedirect(sess, repo.OwnerID, newRepoName); err != nil {
  1542. return fmt.Errorf("delete repo redirect: %v", err)
  1543. }
  1544. if err := NewRepoRedirect(DBContext{sess}, repo.Owner.ID, repo.ID, oldRepoName, newRepoName); err != nil {
  1545. return err
  1546. }
  1547. return sess.Commit()
  1548. }
  1549. func getRepositoriesByForkID(e Engine, forkID int64) ([]*Repository, error) {
  1550. repos := make([]*Repository, 0, 10)
  1551. return repos, e.
  1552. Where("fork_id=?", forkID).
  1553. Find(&repos)
  1554. }
  1555. // GetRepositoriesByForkID returns all repositories with given fork ID.
  1556. func GetRepositoriesByForkID(forkID int64) ([]*Repository, error) {
  1557. return getRepositoriesByForkID(x, forkID)
  1558. }
  1559. func updateRepository(e Engine, repo *Repository, visibilityChanged bool) (err error) {
  1560. repo.LowerName = strings.ToLower(repo.Name)
  1561. if len(repo.Description) > 255 {
  1562. repo.Description = repo.Description[:255]
  1563. }
  1564. if len(repo.Website) > 255 {
  1565. repo.Website = repo.Website[:255]
  1566. }
  1567. if _, err = e.ID(repo.ID).AllCols().Update(repo); err != nil {
  1568. return fmt.Errorf("update: %v", err)
  1569. }
  1570. if visibilityChanged {
  1571. if err = repo.getOwner(e); err != nil {
  1572. return fmt.Errorf("getOwner: %v", err)
  1573. }
  1574. if repo.Owner.IsOrganization() {
  1575. // Organization repository need to recalculate access table when visibility is changed.
  1576. if err = repo.recalculateTeamAccesses(e, 0); err != nil {
  1577. return fmt.Errorf("recalculateTeamAccesses: %v", err)
  1578. }
  1579. }
  1580. // If repo has become private, we need to set its actions to private.
  1581. if repo.IsPrivate {
  1582. _, err = e.Where("repo_id = ?", repo.ID).Cols("is_private").Update(&Action{
  1583. IsPrivate: true,
  1584. })
  1585. if err != nil {
  1586. return err
  1587. }
  1588. }
  1589. // Create/Remove git-daemon-export-ok for git-daemon...
  1590. daemonExportFile := path.Join(repo.repoPath(e), `git-daemon-export-ok`)
  1591. if repo.IsPrivate && com.IsExist(daemonExportFile) {
  1592. if err = os.Remove(daemonExportFile); err != nil {
  1593. log.Error("Failed to remove %s: %v", daemonExportFile, err)
  1594. }
  1595. } else if !repo.IsPrivate && !com.IsExist(daemonExportFile) {
  1596. if f, err := os.Create(daemonExportFile); err != nil {
  1597. log.Error("Failed to create %s: %v", daemonExportFile, err)
  1598. } else {
  1599. f.Close()
  1600. }
  1601. }
  1602. forkRepos, err := getRepositoriesByForkID(e, repo.ID)
  1603. if err != nil {
  1604. return fmt.Errorf("getRepositoriesByForkID: %v", err)
  1605. }
  1606. for i := range forkRepos {
  1607. forkRepos[i].IsPrivate = repo.IsPrivate
  1608. if err = updateRepository(e, forkRepos[i], true); err != nil {
  1609. return fmt.Errorf("updateRepository[%d]: %v", forkRepos[i].ID, err)
  1610. }
  1611. }
  1612. if err = repo.updateSize(e); err != nil {
  1613. log.Error("Failed to update size for repository: %v", err)
  1614. }
  1615. }
  1616. return nil
  1617. }
  1618. // UpdateRepository updates a repository
  1619. func UpdateRepository(repo *Repository, visibilityChanged bool) (err error) {
  1620. sess := x.NewSession()
  1621. defer sess.Close()
  1622. if err = sess.Begin(); err != nil {
  1623. return err
  1624. }
  1625. if err = updateRepository(sess, repo, visibilityChanged); err != nil {
  1626. return fmt.Errorf("updateRepository: %v", err)
  1627. }
  1628. return sess.Commit()
  1629. }
  1630. // UpdateRepositoryUpdatedTime updates a repository's updated time
  1631. func UpdateRepositoryUpdatedTime(repoID int64, updateTime time.Time) error {
  1632. _, err := x.Exec("UPDATE repository SET updated_unix = ? WHERE id = ?", updateTime.Unix(), repoID)
  1633. return err
  1634. }
  1635. // UpdateRepositoryUnits updates a repository's units
  1636. func UpdateRepositoryUnits(repo *Repository, units []RepoUnit) (err error) {
  1637. sess := x.NewSession()
  1638. defer sess.Close()
  1639. if err = sess.Begin(); err != nil {
  1640. return err
  1641. }
  1642. if _, err = sess.Where("repo_id = ?", repo.ID).Delete(new(RepoUnit)); err != nil {
  1643. return err
  1644. }
  1645. if _, err = sess.Insert(units); err != nil {
  1646. return err
  1647. }
  1648. return sess.Commit()
  1649. }
  1650. // DeleteRepository deletes a repository for a user or organization.
  1651. func DeleteRepository(doer *User, uid, repoID int64) error {
  1652. // In case is a organization.
  1653. org, err := GetUserByID(uid)
  1654. if err != nil {
  1655. return err
  1656. }
  1657. if org.IsOrganization() {
  1658. if err = org.GetTeams(); err != nil {
  1659. return err
  1660. }
  1661. }
  1662. sess := x.NewSession()
  1663. defer sess.Close()
  1664. if err = sess.Begin(); err != nil {
  1665. return err
  1666. }
  1667. repo := &Repository{ID: repoID, OwnerID: uid}
  1668. has, err := sess.Get(repo)
  1669. if err != nil {
  1670. return err
  1671. } else if !has {
  1672. return ErrRepoNotExist{repoID, uid, "", ""}
  1673. }
  1674. // Delete Deploy Keys
  1675. deployKeys, err := listDeployKeys(sess, repo.ID)
  1676. if err != nil {
  1677. return fmt.Errorf("listDeployKeys: %v", err)
  1678. }
  1679. for _, dKey := range deployKeys {
  1680. if err := deleteDeployKey(sess, doer, dKey.ID); err != nil {
  1681. return fmt.Errorf("deleteDeployKeys: %v", err)
  1682. }
  1683. }
  1684. if cnt, err := sess.ID(repoID).Delete(&Repository{}); err != nil {
  1685. return err
  1686. } else if cnt != 1 {
  1687. return ErrRepoNotExist{repoID, uid, "", ""}
  1688. }
  1689. if org.IsOrganization() {
  1690. for _, t := range org.Teams {
  1691. if !t.hasRepository(sess, repoID) {
  1692. continue
  1693. } else if err = t.removeRepository(sess, repo, false); err != nil {
  1694. return err
  1695. }
  1696. }
  1697. }
  1698. if err = deleteBeans(sess,
  1699. &Access{RepoID: repo.ID},
  1700. &Action{RepoID: repo.ID},
  1701. &Watch{RepoID: repoID},
  1702. &Star{RepoID: repoID},
  1703. &Mirror{RepoID: repoID},
  1704. &Milestone{RepoID: repoID},
  1705. &Release{RepoID: repoID},
  1706. &Collaboration{RepoID: repoID},
  1707. &PullRequest{BaseRepoID: repoID},
  1708. &RepoUnit{RepoID: repoID},
  1709. &RepoRedirect{RedirectRepoID: repoID},
  1710. &Webhook{RepoID: repoID},
  1711. &HookTask{RepoID: repoID},
  1712. &Notification{RepoID: repoID},
  1713. &CommitStatus{RepoID: repoID},
  1714. &RepoIndexerStatus{RepoID: repoID},
  1715. &Comment{RefRepoID: repoID},
  1716. &Task{RepoID: repoID},
  1717. ); err != nil {
  1718. return fmt.Errorf("deleteBeans: %v", err)
  1719. }
  1720. deleteCond := builder.Select("id").From("issue").Where(builder.Eq{"repo_id": repoID})
  1721. // Delete comments and attachments
  1722. if _, err = sess.In("issue_id", deleteCond).
  1723. Delete(&Comment{}); err != nil {
  1724. return err
  1725. }
  1726. if _, err = sess.In("issue_id", deleteCond).
  1727. Delete(&IssueUser{}); err != nil {
  1728. return err
  1729. }
  1730. if _, err = sess.In("issue_id", deleteCond).
  1731. Delete(&Reaction{}); err != nil {
  1732. return err
  1733. }
  1734. if _, err = sess.In("issue_id", deleteCond).
  1735. Delete(&IssueWatch{}); err != nil {
  1736. return err
  1737. }
  1738. if _, err = sess.In("issue_id", deleteCond).
  1739. Delete(&Stopwatch{}); err != nil {
  1740. return err
  1741. }
  1742. attachmentPaths := make([]string, 0, 20)
  1743. attachments := make([]*Attachment, 0, len(attachmentPaths))
  1744. if err = sess.Join("INNER", "issue", "issue.id = attachment.issue_id").
  1745. Where("issue.repo_id = ?", repoID).
  1746. Find(&attachments); err != nil {
  1747. return err
  1748. }
  1749. for j := range attachments {
  1750. attachmentPaths = append(attachmentPaths, attachments[j].LocalPath())
  1751. }
  1752. if _, err = sess.In("issue_id", deleteCond).
  1753. Delete(&Attachment{}); err != nil {
  1754. return err
  1755. }
  1756. if _, err = sess.Delete(&Issue{RepoID: repoID}); err != nil {
  1757. return err
  1758. }
  1759. if _, err = sess.Where("repo_id = ?", repoID).Delete(new(RepoUnit)); err != nil {
  1760. return err
  1761. }
  1762. if repo.IsFork {
  1763. if _, err = sess.Exec("UPDATE `repository` SET num_forks=num_forks-1 WHERE id=?", repo.ForkID); err != nil {
  1764. return fmt.Errorf("decrease fork count: %v", err)
  1765. }
  1766. }
  1767. if _, err = sess.Exec("UPDATE `user` SET num_repos=num_repos-1 WHERE id=?", uid); err != nil {
  1768. return err
  1769. }
  1770. // FIXME: Remove repository files should be executed after transaction succeed.
  1771. repoPath := repo.repoPath(sess)
  1772. removeAllWithNotice(sess, "Delete repository files", repoPath)
  1773. err = repo.deleteWiki(sess)
  1774. if err != nil {
  1775. return err
  1776. }
  1777. // Remove attachment files.
  1778. for i := range attachmentPaths {
  1779. removeAllWithNotice(sess, "Delete attachment", attachmentPaths[i])
  1780. }
  1781. // Remove LFS objects
  1782. var lfsObjects []*LFSMetaObject
  1783. if err = sess.Where("repository_id=?", repoID).Find(&lfsObjects); err != nil {
  1784. return err
  1785. }
  1786. for _, v := range lfsObjects {
  1787. count, err := sess.Count(&LFSMetaObject{Oid: v.Oid})
  1788. if err != nil {
  1789. return err
  1790. }
  1791. if count > 1 {
  1792. continue
  1793. }
  1794. oidPath := filepath.Join(setting.LFS.ContentPath, v.Oid[0:2], v.Oid[2:4], v.Oid[4:len(v.Oid)])
  1795. removeAllWithNotice(sess, "Delete orphaned LFS file", oidPath)
  1796. }
  1797. if _, err := sess.Delete(&LFSMetaObject{RepositoryID: repoID}); err != nil {
  1798. return err
  1799. }
  1800. if repo.NumForks > 0 {
  1801. if _, err = sess.Exec("UPDATE `repository` SET fork_id=0,is_fork=? WHERE fork_id=?", false, repo.ID); err != nil {
  1802. log.Error("reset 'fork_id' and 'is_fork': %v", err)
  1803. }
  1804. }
  1805. if err = sess.Commit(); err != nil {
  1806. if len(deployKeys) > 0 {
  1807. // We need to rewrite the public keys because the commit failed
  1808. if err2 := RewriteAllPublicKeys(); err2 != nil {
  1809. return fmt.Errorf("Commit: %v SSH Keys: %v", err, err2)
  1810. }
  1811. }
  1812. return fmt.Errorf("Commit: %v", err)
  1813. }
  1814. if len(repo.Avatar) > 0 {
  1815. avatarPath := repo.CustomAvatarPath()
  1816. if com.IsExist(avatarPath) {
  1817. if err := os.Remove(avatarPath); err != nil {
  1818. return fmt.Errorf("Failed to remove %s: %v", avatarPath, err)
  1819. }
  1820. }
  1821. }
  1822. return nil
  1823. }
  1824. // GetRepositoryByOwnerAndName returns the repository by given ownername and reponame.
  1825. func GetRepositoryByOwnerAndName(ownerName, repoName string) (*Repository, error) {
  1826. return getRepositoryByOwnerAndName(x, ownerName, repoName)
  1827. }
  1828. func getRepositoryByOwnerAndName(e Engine, ownerName, repoName string) (*Repository, error) {
  1829. var repo Repository
  1830. has, err := e.Table("repository").Select("repository.*").
  1831. Join("INNER", "`user`", "`user`.id = repository.owner_id").
  1832. Where("repository.lower_name = ?", strings.ToLower(repoName)).
  1833. And("`user`.lower_name = ?", strings.ToLower(ownerName)).
  1834. Get(&repo)
  1835. if err != nil {
  1836. return nil, err
  1837. } else if !has {
  1838. return nil, ErrRepoNotExist{0, 0, ownerName, repoName}
  1839. }
  1840. return &repo, nil
  1841. }
  1842. // GetRepositoryByName returns the repository by given name under user if exists.
  1843. func GetRepositoryByName(ownerID int64, name string) (*Repository, error) {
  1844. repo := &Repository{
  1845. OwnerID: ownerID,
  1846. LowerName: strings.ToLower(name),
  1847. }
  1848. has, err := x.Get(repo)
  1849. if err != nil {
  1850. return nil, err
  1851. } else if !has {
  1852. return nil, ErrRepoNotExist{0, ownerID, "", name}
  1853. }
  1854. return repo, err
  1855. }
  1856. func getRepositoryByID(e Engine, id int64) (*Repository, error) {
  1857. repo := new(Repository)
  1858. has, err := e.ID(id).Get(repo)
  1859. if err != nil {
  1860. return nil, err
  1861. } else if !has {
  1862. return nil, ErrRepoNotExist{id, 0, "", ""}
  1863. }
  1864. return repo, nil
  1865. }
  1866. // GetRepositoryByID returns the repository by given id if exists.
  1867. func GetRepositoryByID(id int64) (*Repository, error) {
  1868. return getRepositoryByID(x, id)
  1869. }
  1870. // GetRepositoriesMapByIDs returns the repositories by given id slice.
  1871. func GetRepositoriesMapByIDs(ids []int64) (map[int64]*Repository, error) {
  1872. var repos = make(map[int64]*Repository, len(ids))
  1873. return repos, x.In("id", ids).Find(&repos)
  1874. }
  1875. // GetUserRepositories returns a list of repositories of given user.
  1876. func GetUserRepositories(userID int64, private bool, page, pageSize int, orderBy string) ([]*Repository, error) {
  1877. if len(orderBy) == 0 {
  1878. orderBy = "updated_unix DESC"
  1879. }
  1880. sess := x.
  1881. Where("owner_id = ?", userID).
  1882. OrderBy(orderBy)
  1883. if !private {
  1884. sess.And("is_private=?", false)
  1885. }
  1886. if page <= 0 {
  1887. page = 1
  1888. }
  1889. sess.Limit(pageSize, (page-1)*pageSize)
  1890. repos := make([]*Repository, 0, pageSize)
  1891. return repos, sess.Find(&repos)
  1892. }
  1893. // GetUserMirrorRepositories returns a list of mirror repositories of given user.
  1894. func GetUserMirrorRepositories(userID int64) ([]*Repository, error) {
  1895. repos := make([]*Repository, 0, 10)
  1896. return repos, x.
  1897. Where("owner_id = ?", userID).
  1898. And("is_mirror = ?", true).
  1899. Find(&repos)
  1900. }
  1901. func getRepositoryCount(e Engine, u *User) (int64, error) {
  1902. return e.Count(&Repository{OwnerID: u.ID})
  1903. }
  1904. func getPublicRepositoryCount(e Engine, u *User) (int64, error) {
  1905. return e.Where("is_private = ?", false).Count(&Repository{OwnerID: u.ID})
  1906. }
  1907. func getPrivateRepositoryCount(e Engine, u *User) (int64, error) {
  1908. return e.Where("is_private = ?", true).Count(&Repository{OwnerID: u.ID})
  1909. }
  1910. // GetRepositoryCount returns the total number of repositories of user.
  1911. func GetRepositoryCount(u *User) (int64, error) {
  1912. return getRepositoryCount(x, u)
  1913. }
  1914. // GetPublicRepositoryCount returns the total number of public repositories of user.
  1915. func GetPublicRepositoryCount(u *User) (int64, error) {
  1916. return getPublicRepositoryCount(x, u)
  1917. }
  1918. // GetPrivateRepositoryCount returns the total number of private repositories of user.
  1919. func GetPrivateRepositoryCount(u *User) (int64, error) {
  1920. return getPrivateRepositoryCount(x, u)
  1921. }
  1922. // DeleteRepositoryArchives deletes all repositories' archives.
  1923. func DeleteRepositoryArchives() error {
  1924. return x.
  1925. Where("id > 0").
  1926. Iterate(new(Repository),
  1927. func(idx int, bean interface{}) error {
  1928. repo := bean.(*Repository)
  1929. return os.RemoveAll(filepath.Join(repo.RepoPath(), "archives"))
  1930. })
  1931. }
  1932. // DeleteOldRepositoryArchives deletes old repository archives.
  1933. func DeleteOldRepositoryArchives() {
  1934. log.Trace("Doing: ArchiveCleanup")
  1935. if err := x.Where("id > 0").Iterate(new(Repository), deleteOldRepositoryArchives); err != nil {
  1936. log.Error("ArchiveClean: %v", err)
  1937. }
  1938. }
  1939. func deleteOldRepositoryArchives(idx int, bean interface{}) error {
  1940. repo := bean.(*Repository)
  1941. basePath := filepath.Join(repo.RepoPath(), "archives")
  1942. for _, ty := range []string{"zip", "targz"} {
  1943. path := filepath.Join(basePath, ty)
  1944. file, err := os.Open(path)
  1945. if err != nil {
  1946. if !os.IsNotExist(err) {
  1947. log.Warn("Unable to open directory %s: %v", path, err)
  1948. return err
  1949. }
  1950. // If the directory doesn't exist, that's okay.
  1951. continue
  1952. }
  1953. files, err := file.Readdir(0)
  1954. file.Close()
  1955. if err != nil {
  1956. log.Warn("Unable to read directory %s: %v", path, err)
  1957. return err
  1958. }
  1959. minimumOldestTime := time.Now().Add(-setting.Cron.ArchiveCleanup.OlderThan)
  1960. for _, info := range files {
  1961. if info.ModTime().Before(minimumOldestTime) && !info.IsDir() {
  1962. toDelete := filepath.Join(path, info.Name())
  1963. // This is a best-effort purge, so we do not check error codes to confirm removal.
  1964. if err = os.Remove(toDelete); err != nil {
  1965. log.Trace("Unable to delete %s, but proceeding: %v", toDelete, err)
  1966. }
  1967. }
  1968. }
  1969. }
  1970. return nil
  1971. }
  1972. func gatherMissingRepoRecords() ([]*Repository, error) {
  1973. repos := make([]*Repository, 0, 10)
  1974. if err := x.
  1975. Where("id > 0").
  1976. Iterate(new(Repository),
  1977. func(idx int, bean interface{}) error {
  1978. repo := bean.(*Repository)
  1979. if !com.IsDir(repo.RepoPath()) {
  1980. repos = append(repos, repo)
  1981. }
  1982. return nil
  1983. }); err != nil {
  1984. if err2 := CreateRepositoryNotice(fmt.Sprintf("gatherMissingRepoRecords: %v", err)); err2 != nil {
  1985. return nil, fmt.Errorf("CreateRepositoryNotice: %v", err)
  1986. }
  1987. }
  1988. return repos, nil
  1989. }
  1990. // DeleteMissingRepositories deletes all repository records that lost Git files.
  1991. func DeleteMissingRepositories(doer *User) error {
  1992. repos, err := gatherMissingRepoRecords()
  1993. if err != nil {
  1994. return fmt.Errorf("gatherMissingRepoRecords: %v", err)
  1995. }
  1996. if len(repos) == 0 {
  1997. return nil
  1998. }
  1999. for _, repo := range repos {
  2000. log.Trace("Deleting %d/%d...", repo.OwnerID, repo.ID)
  2001. if err := DeleteRepository(doer, repo.OwnerID, repo.ID); err != nil {
  2002. if err2 := CreateRepositoryNotice(fmt.Sprintf("DeleteRepository [%d]: %v", repo.ID, err)); err2 != nil {
  2003. return fmt.Errorf("CreateRepositoryNotice: %v", err)
  2004. }
  2005. }
  2006. }
  2007. return nil
  2008. }
  2009. // ReinitMissingRepositories reinitializes all repository records that lost Git files.
  2010. func ReinitMissingRepositories() error {
  2011. repos, err := gatherMissingRepoRecords()
  2012. if err != nil {
  2013. return fmt.Errorf("gatherMissingRepoRecords: %v", err)
  2014. }
  2015. if len(repos) == 0 {
  2016. return nil
  2017. }
  2018. for _, repo := range repos {
  2019. log.Trace("Initializing %d/%d...", repo.OwnerID, repo.ID)
  2020. if err := git.InitRepository(repo.RepoPath(), true); err != nil {
  2021. if err2 := CreateRepositoryNotice(fmt.Sprintf("InitRepository [%d]: %v", repo.ID, err)); err2 != nil {
  2022. return fmt.Errorf("CreateRepositoryNotice: %v", err)
  2023. }
  2024. }
  2025. }
  2026. return nil
  2027. }
  2028. // SyncRepositoryHooks rewrites all repositories' pre-receive, update and post-receive hooks
  2029. // to make sure the binary and custom conf path are up-to-date.
  2030. func SyncRepositoryHooks() error {
  2031. return x.Cols("owner_id", "name").Where("id > 0").Iterate(new(Repository),
  2032. func(idx int, bean interface{}) error {
  2033. if err := createDelegateHooks(bean.(*Repository).RepoPath()); err != nil {
  2034. return fmt.Errorf("SyncRepositoryHook: %v", err)
  2035. }
  2036. if bean.(*Repository).HasWiki() {
  2037. if err := createDelegateHooks(bean.(*Repository).WikiPath()); err != nil {
  2038. return fmt.Errorf("SyncRepositoryHook: %v", err)
  2039. }
  2040. }
  2041. return nil
  2042. })
  2043. }
  2044. // GitFsck calls 'git fsck' to check repository health.
  2045. func GitFsck() {
  2046. log.Trace("Doing: GitFsck")
  2047. if err := x.
  2048. Where("id>0 AND is_fsck_enabled=?", true).BufferSize(setting.Database.IterateBufferSize).
  2049. Iterate(new(Repository),
  2050. func(idx int, bean interface{}) error {
  2051. repo := bean.(*Repository)
  2052. repoPath := repo.RepoPath()
  2053. log.Trace("Running health check on repository %s", repoPath)
  2054. if err := git.Fsck(repoPath, setting.Cron.RepoHealthCheck.Timeout, setting.Cron.RepoHealthCheck.Args...); err != nil {
  2055. desc := fmt.Sprintf("Failed to health check repository (%s): %v", repoPath, err)
  2056. log.Warn(desc)
  2057. if err = CreateRepositoryNotice(desc); err != nil {
  2058. log.Error("CreateRepositoryNotice: %v", err)
  2059. }
  2060. }
  2061. return nil
  2062. }); err != nil {
  2063. log.Error("GitFsck: %v", err)
  2064. }
  2065. log.Trace("Finished: GitFsck")
  2066. }
  2067. // GitGcRepos calls 'git gc' to remove unnecessary files and optimize the local repository
  2068. func GitGcRepos() error {
  2069. args := append([]string{"gc"}, setting.Git.GCArgs...)
  2070. return x.
  2071. Where("id > 0").BufferSize(setting.Database.IterateBufferSize).
  2072. Iterate(new(Repository),
  2073. func(idx int, bean interface{}) error {
  2074. repo := bean.(*Repository)
  2075. if err := repo.GetOwner(); err != nil {
  2076. return err
  2077. }
  2078. if stdout, err := git.NewCommand(args...).
  2079. SetDescription(fmt.Sprintf("Repository Garbage Collection: %s", repo.FullName())).
  2080. RunInDirTimeout(
  2081. time.Duration(setting.Git.Timeout.GC)*time.Second,
  2082. RepoPath(repo.Owner.Name, repo.Name)); err != nil {
  2083. log.Error("Repository garbage collection failed for %v. Stdout: %s\nError: %v", repo, stdout, err)
  2084. return fmt.Errorf("Repository garbage collection failed: Error: %v", err)
  2085. }
  2086. return nil
  2087. })
  2088. }
  2089. type repoChecker struct {
  2090. querySQL, correctSQL string
  2091. desc string
  2092. }
  2093. func repoStatsCheck(checker *repoChecker) {
  2094. results, err := x.Query(checker.querySQL)
  2095. if err != nil {
  2096. log.Error("Select %s: %v", checker.desc, err)
  2097. return
  2098. }
  2099. for _, result := range results {
  2100. id := com.StrTo(result["id"]).MustInt64()
  2101. log.Trace("Updating %s: %d", checker.desc, id)
  2102. _, err = x.Exec(checker.correctSQL, id, id)
  2103. if err != nil {
  2104. log.Error("Update %s[%d]: %v", checker.desc, id, err)
  2105. }
  2106. }
  2107. }
  2108. // CheckRepoStats checks the repository stats
  2109. func CheckRepoStats() {
  2110. log.Trace("Doing: CheckRepoStats")
  2111. checkers := []*repoChecker{
  2112. // Repository.NumWatches
  2113. {
  2114. "SELECT repo.id FROM `repository` repo WHERE repo.num_watches!=(SELECT COUNT(*) FROM `watch` WHERE repo_id=repo.id AND mode<>2)",
  2115. "UPDATE `repository` SET num_watches=(SELECT COUNT(*) FROM `watch` WHERE repo_id=? AND mode<>2) WHERE id=?",
  2116. "repository count 'num_watches'",
  2117. },
  2118. // Repository.NumStars
  2119. {
  2120. "SELECT repo.id FROM `repository` repo WHERE repo.num_stars!=(SELECT COUNT(*) FROM `star` WHERE repo_id=repo.id)",
  2121. "UPDATE `repository` SET num_stars=(SELECT COUNT(*) FROM `star` WHERE repo_id=?) WHERE id=?",
  2122. "repository count 'num_stars'",
  2123. },
  2124. // Label.NumIssues
  2125. {
  2126. "SELECT label.id FROM `label` WHERE label.num_issues!=(SELECT COUNT(*) FROM `issue_label` WHERE label_id=label.id)",
  2127. "UPDATE `label` SET num_issues=(SELECT COUNT(*) FROM `issue_label` WHERE label_id=?) WHERE id=?",
  2128. "label count 'num_issues'",
  2129. },
  2130. // User.NumRepos
  2131. {
  2132. "SELECT `user`.id FROM `user` WHERE `user`.num_repos!=(SELECT COUNT(*) FROM `repository` WHERE owner_id=`user`.id)",
  2133. "UPDATE `user` SET num_repos=(SELECT COUNT(*) FROM `repository` WHERE owner_id=?) WHERE id=?",
  2134. "user count 'num_repos'",
  2135. },
  2136. // Issue.NumComments
  2137. {
  2138. "SELECT `issue`.id FROM `issue` WHERE `issue`.num_comments!=(SELECT COUNT(*) FROM `comment` WHERE issue_id=`issue`.id AND type=0)",
  2139. "UPDATE `issue` SET num_comments=(SELECT COUNT(*) FROM `comment` WHERE issue_id=? AND type=0) WHERE id=?",
  2140. "issue count 'num_comments'",
  2141. },
  2142. }
  2143. for i := range checkers {
  2144. repoStatsCheck(checkers[i])
  2145. }
  2146. // ***** START: Repository.NumClosedIssues *****
  2147. desc := "repository count 'num_closed_issues'"
  2148. results, err := x.Query("SELECT repo.id FROM `repository` repo WHERE repo.num_closed_issues!=(SELECT COUNT(*) FROM `issue` WHERE repo_id=repo.id AND is_closed=? AND is_pull=?)", true, false)
  2149. if err != nil {
  2150. log.Error("Select %s: %v", desc, err)
  2151. } else {
  2152. for _, result := range results {
  2153. id := com.StrTo(result["id"]).MustInt64()
  2154. log.Trace("Updating %s: %d", desc, id)
  2155. _, err = x.Exec("UPDATE `repository` SET num_closed_issues=(SELECT COUNT(*) FROM `issue` WHERE repo_id=? AND is_closed=? AND is_pull=?) WHERE id=?", id, true, false, id)
  2156. if err != nil {
  2157. log.Error("Update %s[%d]: %v", desc, id, err)
  2158. }
  2159. }
  2160. }
  2161. // ***** END: Repository.NumClosedIssues *****
  2162. // ***** START: Repository.NumClosedPulls *****
  2163. desc = "repository count 'num_closed_pulls'"
  2164. results, err = x.Query("SELECT repo.id FROM `repository` repo WHERE repo.num_closed_pulls!=(SELECT COUNT(*) FROM `issue` WHERE repo_id=repo.id AND is_closed=? AND is_pull=?)", true, true)
  2165. if err != nil {
  2166. log.Error("Select %s: %v", desc, err)
  2167. } else {
  2168. for _, result := range results {
  2169. id := com.StrTo(result["id"]).MustInt64()
  2170. log.Trace("Updating %s: %d", desc, id)
  2171. _, err = x.Exec("UPDATE `repository` SET num_closed_pulls=(SELECT COUNT(*) FROM `issue` WHERE repo_id=? AND is_closed=? AND is_pull=?) WHERE id=?", id, true, true, id)
  2172. if err != nil {
  2173. log.Error("Update %s[%d]: %v", desc, id, err)
  2174. }
  2175. }
  2176. }
  2177. // ***** END: Repository.NumClosedPulls *****
  2178. // FIXME: use checker when stop supporting old fork repo format.
  2179. // ***** START: Repository.NumForks *****
  2180. results, err = x.Query("SELECT repo.id FROM `repository` repo WHERE repo.num_forks!=(SELECT COUNT(*) FROM `repository` WHERE fork_id=repo.id)")
  2181. if err != nil {
  2182. log.Error("Select repository count 'num_forks': %v", err)
  2183. } else {
  2184. for _, result := range results {
  2185. id := com.StrTo(result["id"]).MustInt64()
  2186. log.Trace("Updating repository count 'num_forks': %d", id)
  2187. repo, err := GetRepositoryByID(id)
  2188. if err != nil {
  2189. log.Error("GetRepositoryByID[%d]: %v", id, err)
  2190. continue
  2191. }
  2192. rawResult, err := x.Query("SELECT COUNT(*) FROM `repository` WHERE fork_id=?", repo.ID)
  2193. if err != nil {
  2194. log.Error("Select count of forks[%d]: %v", repo.ID, err)
  2195. continue
  2196. }
  2197. repo.NumForks = int(parseCountResult(rawResult))
  2198. if err = UpdateRepository(repo, false); err != nil {
  2199. log.Error("UpdateRepository[%d]: %v", id, err)
  2200. continue
  2201. }
  2202. }
  2203. }
  2204. // ***** END: Repository.NumForks *****
  2205. }
  2206. // SetArchiveRepoState sets if a repo is archived
  2207. func (repo *Repository) SetArchiveRepoState(isArchived bool) (err error) {
  2208. repo.IsArchived = isArchived
  2209. _, err = x.Where("id = ?", repo.ID).Cols("is_archived").Update(repo)
  2210. return
  2211. }
  2212. // ___________ __
  2213. // \_ _____/__________| | __
  2214. // | __)/ _ \_ __ \ |/ /
  2215. // | \( <_> ) | \/ <
  2216. // \___ / \____/|__| |__|_ \
  2217. // \/ \/
  2218. // HasForkedRepo checks if given user has already forked a repository with given ID.
  2219. func HasForkedRepo(ownerID, repoID int64) (*Repository, bool) {
  2220. repo := new(Repository)
  2221. has, _ := x.
  2222. Where("owner_id=? AND fork_id=?", ownerID, repoID).
  2223. Get(repo)
  2224. return repo, has
  2225. }
  2226. // CopyLFS copies LFS data from one repo to another
  2227. func CopyLFS(newRepo, oldRepo *Repository) error {
  2228. return copyLFS(x, newRepo, oldRepo)
  2229. }
  2230. func copyLFS(e Engine, newRepo, oldRepo *Repository) error {
  2231. var lfsObjects []*LFSMetaObject
  2232. if err := e.Where("repository_id=?", oldRepo.ID).Find(&lfsObjects); err != nil {
  2233. return err
  2234. }
  2235. for _, v := range lfsObjects {
  2236. v.ID = 0
  2237. v.RepositoryID = newRepo.ID
  2238. if _, err := e.Insert(v); err != nil {
  2239. return err
  2240. }
  2241. }
  2242. return nil
  2243. }
  2244. // ForkRepository forks a repository
  2245. func ForkRepository(doer, owner *User, oldRepo *Repository, name, desc string) (_ *Repository, err error) {
  2246. forkedRepo, err := oldRepo.GetUserFork(owner.ID)
  2247. if err != nil {
  2248. return nil, err
  2249. }
  2250. if forkedRepo != nil {
  2251. return nil, ErrForkAlreadyExist{
  2252. Uname: owner.Name,
  2253. RepoName: oldRepo.FullName(),
  2254. ForkName: forkedRepo.FullName(),
  2255. }
  2256. }
  2257. repo := &Repository{
  2258. OwnerID: owner.ID,
  2259. Owner: owner,
  2260. Name: name,
  2261. LowerName: strings.ToLower(name),
  2262. Description: desc,
  2263. DefaultBranch: oldRepo.DefaultBranch,
  2264. IsPrivate: oldRepo.IsPrivate,
  2265. IsEmpty: oldRepo.IsEmpty,
  2266. IsFork: true,
  2267. ForkID: oldRepo.ID,
  2268. }
  2269. sess := x.NewSession()
  2270. defer sess.Close()
  2271. if err = sess.Begin(); err != nil {
  2272. return nil, err
  2273. }
  2274. if err = createRepository(sess, doer, owner, repo); err != nil {
  2275. return nil, err
  2276. }
  2277. if _, err = sess.Exec("UPDATE `repository` SET num_forks=num_forks+1 WHERE id=?", oldRepo.ID); err != nil {
  2278. return nil, err
  2279. }
  2280. repoPath := RepoPath(owner.Name, repo.Name)
  2281. if stdout, err := git.NewCommand(
  2282. "clone", "--bare", oldRepo.repoPath(sess), repoPath).
  2283. SetDescription(fmt.Sprintf("ForkRepository(git clone): %s to %s", oldRepo.FullName(), repo.FullName())).
  2284. RunInDirTimeout(10*time.Minute, ""); err != nil {
  2285. log.Error("Fork Repository (git clone) Failed for %v (from %v):\nStdout: %s\nError: %v", repo, oldRepo, stdout, err)
  2286. return nil, fmt.Errorf("git clone: %v", err)
  2287. }
  2288. if stdout, err := git.NewCommand("update-server-info").
  2289. SetDescription(fmt.Sprintf("ForkRepository(git update-server-info): %s", repo.FullName())).
  2290. RunInDir(repoPath); err != nil {
  2291. log.Error("Fork Repository (git update-server-info) failed for %v:\nStdout: %s\nError: %v", repo, stdout, err)
  2292. return nil, fmt.Errorf("git update-server-info: %v", err)
  2293. }
  2294. if err = createDelegateHooks(repoPath); err != nil {
  2295. return nil, fmt.Errorf("createDelegateHooks: %v", err)
  2296. }
  2297. //Commit repo to get Fork ID
  2298. err = sess.Commit()
  2299. if err != nil {
  2300. return nil, err
  2301. }
  2302. if err = repo.UpdateSize(); err != nil {
  2303. log.Error("Failed to update size for repository: %v", err)
  2304. }
  2305. return repo, CopyLFS(repo, oldRepo)
  2306. }
  2307. // GetForks returns all the forks of the repository
  2308. func (repo *Repository) GetForks() ([]*Repository, error) {
  2309. forks := make([]*Repository, 0, repo.NumForks)
  2310. return forks, x.Find(&forks, &Repository{ForkID: repo.ID})
  2311. }
  2312. // GetUserFork return user forked repository from this repository, if not forked return nil
  2313. func (repo *Repository) GetUserFork(userID int64) (*Repository, error) {
  2314. var forkedRepo Repository
  2315. has, err := x.Where("fork_id = ?", repo.ID).And("owner_id = ?", userID).Get(&forkedRepo)
  2316. if err != nil {
  2317. return nil, err
  2318. }
  2319. if !has {
  2320. return nil, nil
  2321. }
  2322. return &forkedRepo, nil
  2323. }
  2324. // CustomAvatarPath returns repository custom avatar file path.
  2325. func (repo *Repository) CustomAvatarPath() string {
  2326. // Avatar empty by default
  2327. if len(repo.Avatar) == 0 {
  2328. return ""
  2329. }
  2330. return filepath.Join(setting.RepositoryAvatarUploadPath, repo.Avatar)
  2331. }
  2332. // generateRandomAvatar generates a random avatar for repository.
  2333. func (repo *Repository) generateRandomAvatar(e Engine) error {
  2334. idToString := fmt.Sprintf("%d", repo.ID)
  2335. seed := idToString
  2336. img, err := avatar.RandomImage([]byte(seed))
  2337. if err != nil {
  2338. return fmt.Errorf("RandomImage: %v", err)
  2339. }
  2340. repo.Avatar = idToString
  2341. if err = os.MkdirAll(filepath.Dir(repo.CustomAvatarPath()), os.ModePerm); err != nil {
  2342. return fmt.Errorf("MkdirAll: %v", err)
  2343. }
  2344. fw, err := os.Create(repo.CustomAvatarPath())
  2345. if err != nil {
  2346. return fmt.Errorf("Create: %v", err)
  2347. }
  2348. defer fw.Close()
  2349. if err = png.Encode(fw, img); err != nil {
  2350. return fmt.Errorf("Encode: %v", err)
  2351. }
  2352. log.Info("New random avatar created for repository: %d", repo.ID)
  2353. if _, err := e.ID(repo.ID).Cols("avatar").NoAutoTime().Update(repo); err != nil {
  2354. return err
  2355. }
  2356. return nil
  2357. }
  2358. // RemoveRandomAvatars removes the randomly generated avatars that were created for repositories
  2359. func RemoveRandomAvatars() error {
  2360. return x.
  2361. Where("id > 0").BufferSize(setting.Database.IterateBufferSize).
  2362. Iterate(new(Repository),
  2363. func(idx int, bean interface{}) error {
  2364. repository := bean.(*Repository)
  2365. stringifiedID := strconv.FormatInt(repository.ID, 10)
  2366. if repository.Avatar == stringifiedID {
  2367. return repository.DeleteAvatar()
  2368. }
  2369. return nil
  2370. })
  2371. }
  2372. // RelAvatarLink returns a relative link to the repository's avatar.
  2373. func (repo *Repository) RelAvatarLink() string {
  2374. return repo.relAvatarLink(x)
  2375. }
  2376. func (repo *Repository) relAvatarLink(e Engine) string {
  2377. // If no avatar - path is empty
  2378. avatarPath := repo.CustomAvatarPath()
  2379. if len(avatarPath) == 0 || !com.IsFile(avatarPath) {
  2380. switch mode := setting.RepositoryAvatarFallback; mode {
  2381. case "image":
  2382. return setting.RepositoryAvatarFallbackImage
  2383. case "random":
  2384. if err := repo.generateRandomAvatar(e); err != nil {
  2385. log.Error("generateRandomAvatar: %v", err)
  2386. }
  2387. default:
  2388. // default behaviour: do not display avatar
  2389. return ""
  2390. }
  2391. }
  2392. return setting.AppSubURL + "/repo-avatars/" + repo.Avatar
  2393. }
  2394. // avatarLink returns user avatar absolute link.
  2395. func (repo *Repository) avatarLink(e Engine) string {
  2396. link := repo.relAvatarLink(e)
  2397. // link may be empty!
  2398. if len(link) > 0 {
  2399. if link[0] == '/' && link[1] != '/' {
  2400. return setting.AppURL + strings.TrimPrefix(link, setting.AppSubURL)[1:]
  2401. }
  2402. }
  2403. return link
  2404. }
  2405. // UploadAvatar saves custom avatar for repository.
  2406. // FIXME: split uploads to different subdirs in case we have massive number of repos.
  2407. func (repo *Repository) UploadAvatar(data []byte) error {
  2408. m, err := avatar.Prepare(data)
  2409. if err != nil {
  2410. return err
  2411. }
  2412. sess := x.NewSession()
  2413. defer sess.Close()
  2414. if err = sess.Begin(); err != nil {
  2415. return err
  2416. }
  2417. oldAvatarPath := repo.CustomAvatarPath()
  2418. // Users can upload the same image to other repo - prefix it with ID
  2419. // Then repo will be removed - only it avatar file will be removed
  2420. repo.Avatar = fmt.Sprintf("%d-%x", repo.ID, md5.Sum(data))
  2421. if _, err := sess.ID(repo.ID).Cols("avatar").Update(repo); err != nil {
  2422. return fmt.Errorf("UploadAvatar: Update repository avatar: %v", err)
  2423. }
  2424. if err := os.MkdirAll(setting.RepositoryAvatarUploadPath, os.ModePerm); err != nil {
  2425. return fmt.Errorf("UploadAvatar: Failed to create dir %s: %v", setting.RepositoryAvatarUploadPath, err)
  2426. }
  2427. fw, err := os.Create(repo.CustomAvatarPath())
  2428. if err != nil {
  2429. return fmt.Errorf("UploadAvatar: Create file: %v", err)
  2430. }
  2431. defer fw.Close()
  2432. if err = png.Encode(fw, *m); err != nil {
  2433. return fmt.Errorf("UploadAvatar: Encode png: %v", err)
  2434. }
  2435. if len(oldAvatarPath) > 0 && oldAvatarPath != repo.CustomAvatarPath() {
  2436. if err := os.Remove(oldAvatarPath); err != nil {
  2437. return fmt.Errorf("UploadAvatar: Failed to remove old repo avatar %s: %v", oldAvatarPath, err)
  2438. }
  2439. }
  2440. return sess.Commit()
  2441. }
  2442. // DeleteAvatar deletes the repos's custom avatar.
  2443. func (repo *Repository) DeleteAvatar() error {
  2444. // Avatar not exists
  2445. if len(repo.Avatar) == 0 {
  2446. return nil
  2447. }
  2448. avatarPath := repo.CustomAvatarPath()
  2449. log.Trace("DeleteAvatar[%d]: %s", repo.ID, avatarPath)
  2450. sess := x.NewSession()
  2451. defer sess.Close()
  2452. if err := sess.Begin(); err != nil {
  2453. return err
  2454. }
  2455. repo.Avatar = ""
  2456. if _, err := sess.ID(repo.ID).Cols("avatar").Update(repo); err != nil {
  2457. return fmt.Errorf("DeleteAvatar: Update repository avatar: %v", err)
  2458. }
  2459. if _, err := os.Stat(avatarPath); err == nil {
  2460. if err := os.Remove(avatarPath); err != nil {
  2461. return fmt.Errorf("DeleteAvatar: Failed to remove %s: %v", avatarPath, err)
  2462. }
  2463. } else {
  2464. // // Schrodinger: file may or may not exist. See err for details.
  2465. log.Trace("DeleteAvatar[%d]: %v", err)
  2466. }
  2467. return sess.Commit()
  2468. }
  2469. // GetOriginalURLHostname returns the hostname of a URL or the URL
  2470. func (repo *Repository) GetOriginalURLHostname() string {
  2471. u, err := url.Parse(repo.OriginalURL)
  2472. if err != nil {
  2473. return repo.OriginalURL
  2474. }
  2475. return u.Host
  2476. }
  2477. // GetTreePathLock returns LSF lock for the treePath
  2478. func (repo *Repository) GetTreePathLock(treePath string) (*LFSLock, error) {
  2479. if setting.LFS.StartServer {
  2480. locks, err := GetLFSLockByRepoID(repo.ID)
  2481. if err != nil {
  2482. return nil, err
  2483. }
  2484. for _, lock := range locks {
  2485. if lock.Path == treePath {
  2486. return lock, nil
  2487. }
  2488. }
  2489. }
  2490. return nil, nil
  2491. }
  2492. func updateRepositoryCols(e Engine, repo *Repository, cols ...string) error {
  2493. _, err := e.ID(repo.ID).Cols(cols...).Update(repo)
  2494. return err
  2495. }
  2496. // UpdateRepositoryCols updates repository's columns
  2497. func UpdateRepositoryCols(repo *Repository, cols ...string) error {
  2498. return updateRepositoryCols(x, repo, cols...)
  2499. }