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

repo.go 69KB

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