You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

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