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