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.

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