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

repo.go 70KB

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