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

repo.go 90 kB

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