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.

2393 lines
70 KiB

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