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.

2272 lines
66 KiB

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