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

repo.go 75 kB

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