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

repo.go 76 kB

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