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.

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