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