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 82 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
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
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
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
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>
6 years ago
10 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
10 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
10 years ago
10 years ago
10 years ago
11 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
11 years ago
10 years ago
10 years ago
11 years ago
10 years ago
10 years ago
10 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>
8 years ago
Feature: Timetracking (#2211) * Added comment's hashtag to url for mail notifications. * Added explanation to return statement + documentation. * Replacing in-line link generation with HTMLURL. (+gofmt) * Replaced action-based model with nil-based model. (+gofmt) * Replaced mailIssueActionToParticipants with mailIssueCommentToParticipants. * Updating comment for mailIssueCommentToParticipants * Added link to comment in "Dashboard" * Deleting feed entry if a comment is going to be deleted * Added migration * Added improved migration to add a CommentID column to action. * Added improved links to comments in feed entries. * Fixes #1956 by filtering for deleted comments that are referenced in actions. * Introducing "IsDeleted" column to action. * Adding design draft (not functional) * Adding database models for stopwatches and trackedtimes * See go-gitea/gitea#967 * Adding design draft (not functional) * Adding translations and improving design * Implementing stopwatch (for timetracking) * Make UI functional * Add hints in timeline for time tracking events * Implementing timetracking feature * Adding "Add time manual" option * Improved stopwatch * Created report of total spent time by user * Only showing total time spent if theire is something to show. * Adding license headers. * Improved error handling for "Add Time Manual" * Adding @sapks 's changes, refactoring * Adding API for feature tracking * Adding unit test * Adding DISABLE/ENABLE option to Repository settings page * Improving translations * Applying @sapk 's changes * Removing repo_unit and using IssuesSetting for disabling/enabling timetracker * Adding DEFAULT_ENABLE_TIMETRACKER to config, installation and admin menu * Improving documentation * Fixing vendor/ folder * Changing timtracking routes by adding subgroups /times and /times/stopwatch (Proposed by @lafriks ) * Restricting write access to timetracking based on the repo settings (Proposed by @lafriks ) * Fixed minor permissions bug. * Adding CanUseTimetracker and IsTimetrackerEnabled in ctx.Repo * Allow assignees and authors to track there time too. * Fixed some build-time-errors + logical errors. * Removing unused Get...ByID functions * Moving IsTimetrackerEnabled from context.Repository to models.Repository * Adding a seperate file for issue related repo functions * Adding license headers * Fixed GetUserByParams return 404 * Moving /users/:username/times to /repos/:username/:reponame/times/:username for security reasons * Adding /repos/:username/times to get all tracked times of the repo * Updating sdk-dependency * Updating swagger.v1.json * Adding warning if user has already a running stopwatch (auto-timetracker) * Replacing GetTrackedTimesBy... with GetTrackedTimes(options FindTrackedTimesOptions) * Changing code.gitea.io/sdk back to code.gitea.io/sdk * Correcting spelling mistake * Updating vendor.json * Changing GET stopwatch/toggle to POST stopwatch/toggle * Changing GET stopwatch/cancel to POST stopwatch/cancel * Added migration for stopwatches/timetracking * Fixed some access bugs for read-only users * Added default allow only contributors to track time value to config * Fixed migration by chaging x.Iterate to x.Find * Resorted imports * Moved Add Time Manually form to repo_form.go * Removed "Seconds" field from Add Time Manually * Resorted imports * Improved permission checking * Fixed some bugs * Added integration test * gofmt * Adding integration test by @lafriks * Added created_unix to comment fixtures * Using last event instead of a fixed event * Adding another integration test by @lafriks * Fixing bug Timetracker enabled causing error 500 at sidebar.tpl * Fixed a refactoring bug that resulted in hiding "HasUserStopwatch" warning. * Returning TrackedTime instead of AddTimeOption at AddTime. * Updating SDK from go-gitea/go-sdk#69 * Resetting Go-SDK back to default repository * Fixing test-vendor by changing ini back to original repository * Adding "tags" to swagger spec * govendor sync * Removed duplicate * Formatting templates * Adding IsTimetrackingEnabled checks to API * Improving translations / english texts * Improving documentation * Updating swagger spec * Fixing integration test caused be translation-changes * Removed encoding issues in local_en-US.ini. * "Added" copyright line * Moved unit.IssuesConfig().EnableTimetracker into a != nil check * Removed some other encoding issues in local_en-US.ini * Improved javascript by checking if data-context exists * Replaced manual comment creation with CreateComment * Removed unnecessary code * Improved error checking * Small cosmetic changes * Replaced int>string>duration parsing with int>duration parsing * Fixed encoding issues * Removed unused imports Signed-off-by: Jonas Franz <info@jonasfranz.software>
8 years ago
Feature: Timetracking (#2211) * Added comment's hashtag to url for mail notifications. * Added explanation to return statement + documentation. * Replacing in-line link generation with HTMLURL. (+gofmt) * Replaced action-based model with nil-based model. (+gofmt) * Replaced mailIssueActionToParticipants with mailIssueCommentToParticipants. * Updating comment for mailIssueCommentToParticipants * Added link to comment in "Dashboard" * Deleting feed entry if a comment is going to be deleted * Added migration * Added improved migration to add a CommentID column to action. * Added improved links to comments in feed entries. * Fixes #1956 by filtering for deleted comments that are referenced in actions. * Introducing "IsDeleted" column to action. * Adding design draft (not functional) * Adding database models for stopwatches and trackedtimes * See go-gitea/gitea#967 * Adding design draft (not functional) * Adding translations and improving design * Implementing stopwatch (for timetracking) * Make UI functional * Add hints in timeline for time tracking events * Implementing timetracking feature * Adding "Add time manual" option * Improved stopwatch * Created report of total spent time by user * Only showing total time spent if theire is something to show. * Adding license headers. * Improved error handling for "Add Time Manual" * Adding @sapks 's changes, refactoring * Adding API for feature tracking * Adding unit test * Adding DISABLE/ENABLE option to Repository settings page * Improving translations * Applying @sapk 's changes * Removing repo_unit and using IssuesSetting for disabling/enabling timetracker * Adding DEFAULT_ENABLE_TIMETRACKER to config, installation and admin menu * Improving documentation * Fixing vendor/ folder * Changing timtracking routes by adding subgroups /times and /times/stopwatch (Proposed by @lafriks ) * Restricting write access to timetracking based on the repo settings (Proposed by @lafriks ) * Fixed minor permissions bug. * Adding CanUseTimetracker and IsTimetrackerEnabled in ctx.Repo * Allow assignees and authors to track there time too. * Fixed some build-time-errors + logical errors. * Removing unused Get...ByID functions * Moving IsTimetrackerEnabled from context.Repository to models.Repository * Adding a seperate file for issue related repo functions * Adding license headers * Fixed GetUserByParams return 404 * Moving /users/:username/times to /repos/:username/:reponame/times/:username for security reasons * Adding /repos/:username/times to get all tracked times of the repo * Updating sdk-dependency * Updating swagger.v1.json * Adding warning if user has already a running stopwatch (auto-timetracker) * Replacing GetTrackedTimesBy... with GetTrackedTimes(options FindTrackedTimesOptions) * Changing code.gitea.io/sdk back to code.gitea.io/sdk * Correcting spelling mistake * Updating vendor.json * Changing GET stopwatch/toggle to POST stopwatch/toggle * Changing GET stopwatch/cancel to POST stopwatch/cancel * Added migration for stopwatches/timetracking * Fixed some access bugs for read-only users * Added default allow only contributors to track time value to config * Fixed migration by chaging x.Iterate to x.Find * Resorted imports * Moved Add Time Manually form to repo_form.go * Removed "Seconds" field from Add Time Manually * Resorted imports * Improved permission checking * Fixed some bugs * Added integration test * gofmt * Adding integration test by @lafriks * Added created_unix to comment fixtures * Using last event instead of a fixed event * Adding another integration test by @lafriks * Fixing bug Timetracker enabled causing error 500 at sidebar.tpl * Fixed a refactoring bug that resulted in hiding "HasUserStopwatch" warning. * Returning TrackedTime instead of AddTimeOption at AddTime. * Updating SDK from go-gitea/go-sdk#69 * Resetting Go-SDK back to default repository * Fixing test-vendor by changing ini back to original repository * Adding "tags" to swagger spec * govendor sync * Removed duplicate * Formatting templates * Adding IsTimetrackingEnabled checks to API * Improving translations / english texts * Improving documentation * Updating swagger spec * Fixing integration test caused be translation-changes * Removed encoding issues in local_en-US.ini. * "Added" copyright line * Moved unit.IssuesConfig().EnableTimetracker into a != nil check * Removed some other encoding issues in local_en-US.ini * Improved javascript by checking if data-context exists * Replaced manual comment creation with CreateComment * Removed unnecessary code * Improved error checking * Small cosmetic changes * Replaced int>string>duration parsing with int>duration parsing * Fixed encoding issues * Removed unused imports Signed-off-by: Jonas Franz <info@jonasfranz.software>
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
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
10 years ago
11 years ago
10 years ago
10 years ago
10 years ago
10 years ago
11 years ago
10 years ago
11 years ago
11 years ago
10 years ago
10 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
11 years ago
11 years ago
10 years ago
10 years ago
10 years ago
10 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
10 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
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
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
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
10 years ago
10 years ago
11 years ago
10 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
10 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
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
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
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
11 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
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
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
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
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
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
9 years ago
10 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
9 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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751
  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. "bytes"
  8. "crypto/md5"
  9. "errors"
  10. "fmt"
  11. "html/template"
  12. // Needed for jpeg support
  13. _ "image/jpeg"
  14. "image/png"
  15. "io/ioutil"
  16. "net/url"
  17. "os"
  18. "path"
  19. "path/filepath"
  20. "sort"
  21. "strconv"
  22. "strings"
  23. "time"
  24. "code.gitea.io/gitea/modules/avatar"
  25. "code.gitea.io/gitea/modules/git"
  26. "code.gitea.io/gitea/modules/log"
  27. "code.gitea.io/gitea/modules/markup"
  28. "code.gitea.io/gitea/modules/options"
  29. "code.gitea.io/gitea/modules/process"
  30. "code.gitea.io/gitea/modules/setting"
  31. api "code.gitea.io/gitea/modules/structs"
  32. "code.gitea.io/gitea/modules/sync"
  33. "code.gitea.io/gitea/modules/timeutil"
  34. "github.com/go-xorm/xorm"
  35. "github.com/unknwon/com"
  36. ini "gopkg.in/ini.v1"
  37. "xorm.io/builder"
  38. )
  39. var repoWorkingPool = sync.NewExclusivePool()
  40. var (
  41. // ErrMirrorNotExist mirror does not exist error
  42. ErrMirrorNotExist = errors.New("Mirror does not exist")
  43. // ErrNameEmpty name is empty error
  44. ErrNameEmpty = errors.New("Name is empty")
  45. )
  46. var (
  47. // Gitignores contains the gitiginore files
  48. Gitignores []string
  49. // Licenses contains the license files
  50. Licenses []string
  51. // Readmes contains the readme files
  52. Readmes []string
  53. // LabelTemplates contains the label template files
  54. LabelTemplates []string
  55. // ItemsPerPage maximum items per page in forks, watchers and stars of a repo
  56. ItemsPerPage = 40
  57. )
  58. // loadRepoConfig loads the repository config
  59. func loadRepoConfig() {
  60. // Load .gitignore and license files and readme templates.
  61. types := []string{"gitignore", "license", "readme", "label"}
  62. typeFiles := make([][]string, 4)
  63. for i, t := range types {
  64. files, err := options.Dir(t)
  65. if err != nil {
  66. log.Fatal("Failed to get %s files: %v", t, err)
  67. }
  68. customPath := path.Join(setting.CustomPath, "options", t)
  69. if com.IsDir(customPath) {
  70. customFiles, err := com.StatDir(customPath)
  71. if err != nil {
  72. log.Fatal("Failed to get custom %s files: %v", t, err)
  73. }
  74. for _, f := range customFiles {
  75. if !com.IsSliceContainsStr(files, f) {
  76. files = append(files, f)
  77. }
  78. }
  79. }
  80. typeFiles[i] = files
  81. }
  82. Gitignores = typeFiles[0]
  83. Licenses = typeFiles[1]
  84. Readmes = typeFiles[2]
  85. LabelTemplates = typeFiles[3]
  86. sort.Strings(Gitignores)
  87. sort.Strings(Licenses)
  88. sort.Strings(Readmes)
  89. sort.Strings(LabelTemplates)
  90. // Filter out invalid names and promote preferred licenses.
  91. sortedLicenses := make([]string, 0, len(Licenses))
  92. for _, name := range setting.Repository.PreferredLicenses {
  93. if com.IsSliceContainsStr(Licenses, name) {
  94. sortedLicenses = append(sortedLicenses, name)
  95. }
  96. }
  97. for _, name := range Licenses {
  98. if !com.IsSliceContainsStr(setting.Repository.PreferredLicenses, name) {
  99. sortedLicenses = append(sortedLicenses, name)
  100. }
  101. }
  102. Licenses = sortedLicenses
  103. }
  104. // NewRepoContext creates a new repository context
  105. func NewRepoContext() {
  106. loadRepoConfig()
  107. RemoveAllWithNotice("Clean up repository temporary data", filepath.Join(setting.AppDataPath, "tmp"))
  108. }
  109. // Repository represents a git repository.
  110. type Repository struct {
  111. ID int64 `xorm:"pk autoincr"`
  112. OwnerID int64 `xorm:"UNIQUE(s) index"`
  113. OwnerName string `xorm:"-"`
  114. Owner *User `xorm:"-"`
  115. LowerName string `xorm:"UNIQUE(s) INDEX NOT NULL"`
  116. Name string `xorm:"INDEX NOT NULL"`
  117. Description string `xorm:"TEXT"`
  118. Website string `xorm:"VARCHAR(2048)"`
  119. OriginalURL string `xorm:"VARCHAR(2048)"`
  120. DefaultBranch string
  121. NumWatches int
  122. NumStars int
  123. NumForks int
  124. NumIssues int
  125. NumClosedIssues int
  126. NumOpenIssues int `xorm:"-"`
  127. NumPulls int
  128. NumClosedPulls int
  129. NumOpenPulls int `xorm:"-"`
  130. NumMilestones int `xorm:"NOT NULL DEFAULT 0"`
  131. NumClosedMilestones int `xorm:"NOT NULL DEFAULT 0"`
  132. NumOpenMilestones int `xorm:"-"`
  133. NumReleases int `xorm:"-"`
  134. IsPrivate bool `xorm:"INDEX"`
  135. IsEmpty bool `xorm:"INDEX"`
  136. IsArchived bool `xorm:"INDEX"`
  137. IsMirror bool `xorm:"INDEX"`
  138. *Mirror `xorm:"-"`
  139. ExternalMetas map[string]string `xorm:"-"`
  140. Units []*RepoUnit `xorm:"-"`
  141. IsFork bool `xorm:"INDEX NOT NULL DEFAULT false"`
  142. ForkID int64 `xorm:"INDEX"`
  143. BaseRepo *Repository `xorm:"-"`
  144. Size int64 `xorm:"NOT NULL DEFAULT 0"`
  145. IndexerStatus *RepoIndexerStatus `xorm:"-"`
  146. IsFsckEnabled bool `xorm:"NOT NULL DEFAULT true"`
  147. CloseIssuesViaCommitInAnyBranch bool `xorm:"NOT NULL DEFAULT false"`
  148. Topics []string `xorm:"TEXT JSON"`
  149. // Avatar: ID(10-20)-md5(32) - must fit into 64 symbols
  150. Avatar string `xorm:"VARCHAR(64)"`
  151. CreatedUnix timeutil.TimeStamp `xorm:"INDEX created"`
  152. UpdatedUnix timeutil.TimeStamp `xorm:"INDEX updated"`
  153. }
  154. // ColorFormat returns a colored string to represent this repo
  155. func (repo *Repository) ColorFormat(s fmt.State) {
  156. var ownerName interface{}
  157. if repo.OwnerName != "" {
  158. ownerName = repo.OwnerName
  159. } else if repo.Owner != nil {
  160. ownerName = repo.Owner.Name
  161. } else {
  162. ownerName = log.NewColoredIDValue(strconv.FormatInt(repo.OwnerID, 10))
  163. }
  164. log.ColorFprintf(s, "%d:%s/%s",
  165. log.NewColoredIDValue(repo.ID),
  166. ownerName,
  167. repo.Name)
  168. }
  169. // AfterLoad is invoked from XORM after setting the values of all fields of this object.
  170. func (repo *Repository) AfterLoad() {
  171. // FIXME: use models migration to solve all at once.
  172. if len(repo.DefaultBranch) == 0 {
  173. repo.DefaultBranch = "master"
  174. }
  175. repo.NumOpenIssues = repo.NumIssues - repo.NumClosedIssues
  176. repo.NumOpenPulls = repo.NumPulls - repo.NumClosedPulls
  177. repo.NumOpenMilestones = repo.NumMilestones - repo.NumClosedMilestones
  178. }
  179. // MustOwner always returns a valid *User object to avoid
  180. // conceptually impossible error handling.
  181. // It creates a fake object that contains error details
  182. // when error occurs.
  183. func (repo *Repository) MustOwner() *User {
  184. return repo.mustOwner(x)
  185. }
  186. // MustOwnerName always returns valid owner name to avoid
  187. // conceptually impossible error handling.
  188. // It returns "error" and logs error details when error
  189. // occurs.
  190. func (repo *Repository) MustOwnerName() string {
  191. return repo.mustOwnerName(x)
  192. }
  193. // FullName returns the repository full name
  194. func (repo *Repository) FullName() string {
  195. return repo.MustOwnerName() + "/" + repo.Name
  196. }
  197. // HTMLURL returns the repository HTML URL
  198. func (repo *Repository) HTMLURL() string {
  199. return setting.AppURL + repo.FullName()
  200. }
  201. // APIURL returns the repository API URL
  202. func (repo *Repository) APIURL() string {
  203. return setting.AppURL + path.Join("api/v1/repos", repo.FullName())
  204. }
  205. // APIFormat converts a Repository to api.Repository
  206. func (repo *Repository) APIFormat(mode AccessMode) *api.Repository {
  207. return repo.innerAPIFormat(x, mode, false)
  208. }
  209. // GetCommitsCountCacheKey returns cache key used for commits count caching.
  210. func (repo *Repository) GetCommitsCountCacheKey(contextName string, isRef bool) string {
  211. var prefix string
  212. if isRef {
  213. prefix = "ref"
  214. } else {
  215. prefix = "commit"
  216. }
  217. return fmt.Sprintf("commits-count-%d-%s-%s", repo.ID, prefix, contextName)
  218. }
  219. func (repo *Repository) innerAPIFormat(e Engine, mode AccessMode, isParent bool) *api.Repository {
  220. var parent *api.Repository
  221. cloneLink := repo.cloneLink(e, false)
  222. permission := &api.Permission{
  223. Admin: mode >= AccessModeAdmin,
  224. Push: mode >= AccessModeWrite,
  225. Pull: mode >= AccessModeRead,
  226. }
  227. if !isParent {
  228. err := repo.getBaseRepo(e)
  229. if err != nil {
  230. log.Error("APIFormat: %v", err)
  231. }
  232. if repo.BaseRepo != nil {
  233. parent = repo.BaseRepo.innerAPIFormat(e, mode, true)
  234. }
  235. }
  236. hasIssues := false
  237. var externalTracker *api.ExternalTracker
  238. var internalTracker *api.InternalTracker
  239. if unit, err := repo.getUnit(e, UnitTypeIssues); err == nil {
  240. config := unit.IssuesConfig()
  241. hasIssues = true
  242. internalTracker = &api.InternalTracker{
  243. EnableTimeTracker: config.EnableTimetracker,
  244. AllowOnlyContributorsToTrackTime: config.AllowOnlyContributorsToTrackTime,
  245. EnableIssueDependencies: config.EnableDependencies,
  246. }
  247. } else if unit, err := repo.getUnit(e, UnitTypeExternalTracker); err == nil {
  248. config := unit.ExternalTrackerConfig()
  249. hasIssues = true
  250. externalTracker = &api.ExternalTracker{
  251. ExternalTrackerURL: config.ExternalTrackerURL,
  252. ExternalTrackerFormat: config.ExternalTrackerFormat,
  253. ExternalTrackerStyle: config.ExternalTrackerStyle,
  254. }
  255. }
  256. hasWiki := false
  257. var externalWiki *api.ExternalWiki
  258. if _, err := repo.getUnit(e, UnitTypeWiki); err == nil {
  259. hasWiki = true
  260. } else if unit, err := repo.getUnit(e, UnitTypeExternalWiki); err == nil {
  261. hasWiki = true
  262. config := unit.ExternalWikiConfig()
  263. externalWiki = &api.ExternalWiki{
  264. ExternalWikiURL: config.ExternalWikiURL,
  265. }
  266. }
  267. hasPullRequests := false
  268. ignoreWhitespaceConflicts := false
  269. allowMerge := false
  270. allowRebase := false
  271. allowRebaseMerge := false
  272. allowSquash := false
  273. if unit, err := repo.getUnit(e, UnitTypePullRequests); err == nil {
  274. config := unit.PullRequestsConfig()
  275. hasPullRequests = true
  276. ignoreWhitespaceConflicts = config.IgnoreWhitespaceConflicts
  277. allowMerge = config.AllowMerge
  278. allowRebase = config.AllowRebase
  279. allowRebaseMerge = config.AllowRebaseMerge
  280. allowSquash = config.AllowSquash
  281. }
  282. return &api.Repository{
  283. ID: repo.ID,
  284. Owner: repo.Owner.APIFormat(),
  285. Name: repo.Name,
  286. FullName: repo.FullName(),
  287. Description: repo.Description,
  288. Private: repo.IsPrivate,
  289. Empty: repo.IsEmpty,
  290. Archived: repo.IsArchived,
  291. Size: int(repo.Size / 1024),
  292. Fork: repo.IsFork,
  293. Parent: parent,
  294. Mirror: repo.IsMirror,
  295. HTMLURL: repo.HTMLURL(),
  296. SSHURL: cloneLink.SSH,
  297. CloneURL: cloneLink.HTTPS,
  298. Website: repo.Website,
  299. Stars: repo.NumStars,
  300. Forks: repo.NumForks,
  301. Watchers: repo.NumWatches,
  302. OpenIssues: repo.NumOpenIssues,
  303. DefaultBranch: repo.DefaultBranch,
  304. Created: repo.CreatedUnix.AsTime(),
  305. Updated: repo.UpdatedUnix.AsTime(),
  306. Permissions: permission,
  307. HasIssues: hasIssues,
  308. ExternalTracker: externalTracker,
  309. InternalTracker: internalTracker,
  310. HasWiki: hasWiki,
  311. ExternalWiki: externalWiki,
  312. HasPullRequests: hasPullRequests,
  313. IgnoreWhitespaceConflicts: ignoreWhitespaceConflicts,
  314. AllowMerge: allowMerge,
  315. AllowRebase: allowRebase,
  316. AllowRebaseMerge: allowRebaseMerge,
  317. AllowSquash: allowSquash,
  318. AvatarURL: repo.avatarLink(e),
  319. }
  320. }
  321. func (repo *Repository) getUnits(e Engine) (err error) {
  322. if repo.Units != nil {
  323. return nil
  324. }
  325. repo.Units, err = getUnitsByRepoID(e, repo.ID)
  326. return err
  327. }
  328. // CheckUnitUser check whether user could visit the unit of this repository
  329. func (repo *Repository) CheckUnitUser(userID int64, isAdmin bool, unitType UnitType) bool {
  330. return repo.checkUnitUser(x, userID, isAdmin, unitType)
  331. }
  332. func (repo *Repository) checkUnitUser(e Engine, userID int64, isAdmin bool, unitType UnitType) bool {
  333. if isAdmin {
  334. return true
  335. }
  336. user, err := getUserByID(e, userID)
  337. if err != nil {
  338. return false
  339. }
  340. perm, err := getUserRepoPermission(e, repo, user)
  341. if err != nil {
  342. return false
  343. }
  344. return perm.CanRead(unitType)
  345. }
  346. // UnitEnabled if this repository has the given unit enabled
  347. func (repo *Repository) UnitEnabled(tp UnitType) bool {
  348. if err := repo.getUnits(x); err != nil {
  349. log.Warn("Error loading repository (ID: %d) units: %s", repo.ID, err.Error())
  350. }
  351. for _, unit := range repo.Units {
  352. if unit.Type == tp {
  353. return true
  354. }
  355. }
  356. return false
  357. }
  358. // ErrUnitTypeNotExist represents a "UnitTypeNotExist" kind of error.
  359. type ErrUnitTypeNotExist struct {
  360. UT UnitType
  361. }
  362. // IsErrUnitTypeNotExist checks if an error is a ErrUnitNotExist.
  363. func IsErrUnitTypeNotExist(err error) bool {
  364. _, ok := err.(ErrUnitTypeNotExist)
  365. return ok
  366. }
  367. func (err ErrUnitTypeNotExist) Error() string {
  368. return fmt.Sprintf("Unit type does not exist: %s", err.UT.String())
  369. }
  370. // MustGetUnit always returns a RepoUnit object
  371. func (repo *Repository) MustGetUnit(tp UnitType) *RepoUnit {
  372. ru, err := repo.GetUnit(tp)
  373. if err == nil {
  374. return ru
  375. }
  376. if tp == UnitTypeExternalWiki {
  377. return &RepoUnit{
  378. Type: tp,
  379. Config: new(ExternalWikiConfig),
  380. }
  381. } else if tp == UnitTypeExternalTracker {
  382. return &RepoUnit{
  383. Type: tp,
  384. Config: new(ExternalTrackerConfig),
  385. }
  386. } else if tp == UnitTypePullRequests {
  387. return &RepoUnit{
  388. Type: tp,
  389. Config: new(PullRequestsConfig),
  390. }
  391. } else if tp == UnitTypeIssues {
  392. return &RepoUnit{
  393. Type: tp,
  394. Config: new(IssuesConfig),
  395. }
  396. }
  397. return &RepoUnit{
  398. Type: tp,
  399. Config: new(UnitConfig),
  400. }
  401. }
  402. // GetUnit returns a RepoUnit object
  403. func (repo *Repository) GetUnit(tp UnitType) (*RepoUnit, error) {
  404. return repo.getUnit(x, tp)
  405. }
  406. func (repo *Repository) getUnit(e Engine, tp UnitType) (*RepoUnit, error) {
  407. if err := repo.getUnits(e); err != nil {
  408. return nil, err
  409. }
  410. for _, unit := range repo.Units {
  411. if unit.Type == tp {
  412. return unit, nil
  413. }
  414. }
  415. return nil, ErrUnitTypeNotExist{tp}
  416. }
  417. func (repo *Repository) getOwner(e Engine) (err error) {
  418. if repo.Owner != nil {
  419. return nil
  420. }
  421. repo.Owner, err = getUserByID(e, repo.OwnerID)
  422. return err
  423. }
  424. // GetOwner returns the repository owner
  425. func (repo *Repository) GetOwner() error {
  426. return repo.getOwner(x)
  427. }
  428. func (repo *Repository) mustOwner(e Engine) *User {
  429. if err := repo.getOwner(e); err != nil {
  430. return &User{
  431. Name: "error",
  432. FullName: err.Error(),
  433. }
  434. }
  435. return repo.Owner
  436. }
  437. func (repo *Repository) getOwnerName(e Engine) error {
  438. if len(repo.OwnerName) > 0 {
  439. return nil
  440. }
  441. if repo.Owner != nil {
  442. repo.OwnerName = repo.Owner.Name
  443. return nil
  444. }
  445. u := new(User)
  446. has, err := e.ID(repo.OwnerID).Cols("name").Get(u)
  447. if err != nil {
  448. return err
  449. } else if !has {
  450. return ErrUserNotExist{repo.OwnerID, "", 0}
  451. }
  452. repo.OwnerName = u.Name
  453. return nil
  454. }
  455. // GetOwnerName returns the repository owner name
  456. func (repo *Repository) GetOwnerName() error {
  457. return repo.getOwnerName(x)
  458. }
  459. func (repo *Repository) mustOwnerName(e Engine) string {
  460. if err := repo.getOwnerName(e); err != nil {
  461. log.Error("Error loading repository owner name: %v", err)
  462. return "error"
  463. }
  464. return repo.OwnerName
  465. }
  466. // ComposeMetas composes a map of metas for properly rendering issue links and external issue trackers.
  467. func (repo *Repository) ComposeMetas() map[string]string {
  468. if repo.ExternalMetas == nil {
  469. repo.ExternalMetas = map[string]string{
  470. "user": repo.MustOwner().Name,
  471. "repo": repo.Name,
  472. "repoPath": repo.RepoPath(),
  473. }
  474. unit, err := repo.GetUnit(UnitTypeExternalTracker)
  475. if err != nil {
  476. return repo.ExternalMetas
  477. }
  478. repo.ExternalMetas["format"] = unit.ExternalTrackerConfig().ExternalTrackerFormat
  479. switch unit.ExternalTrackerConfig().ExternalTrackerStyle {
  480. case markup.IssueNameStyleAlphanumeric:
  481. repo.ExternalMetas["style"] = markup.IssueNameStyleAlphanumeric
  482. default:
  483. repo.ExternalMetas["style"] = markup.IssueNameStyleNumeric
  484. }
  485. }
  486. return repo.ExternalMetas
  487. }
  488. // DeleteWiki removes the actual and local copy of repository wiki.
  489. func (repo *Repository) DeleteWiki() error {
  490. return repo.deleteWiki(x)
  491. }
  492. func (repo *Repository) deleteWiki(e Engine) error {
  493. wikiPaths := []string{repo.WikiPath()}
  494. for _, wikiPath := range wikiPaths {
  495. removeAllWithNotice(e, "Delete repository wiki", wikiPath)
  496. }
  497. _, err := e.Where("repo_id = ?", repo.ID).And("type = ?", UnitTypeWiki).Delete(new(RepoUnit))
  498. return err
  499. }
  500. func (repo *Repository) getAssignees(e Engine) (_ []*User, err error) {
  501. if err = repo.getOwner(e); err != nil {
  502. return nil, err
  503. }
  504. accesses := make([]*Access, 0, 10)
  505. if err = e.
  506. Where("repo_id = ? AND mode >= ?", repo.ID, AccessModeWrite).
  507. Find(&accesses); err != nil {
  508. return nil, err
  509. }
  510. // Leave a seat for owner itself to append later, but if owner is an organization
  511. // and just waste 1 unit is cheaper than re-allocate memory once.
  512. users := make([]*User, 0, len(accesses)+1)
  513. if len(accesses) > 0 {
  514. userIDs := make([]int64, len(accesses))
  515. for i := 0; i < len(accesses); i++ {
  516. userIDs[i] = accesses[i].UserID
  517. }
  518. if err = e.In("id", userIDs).Find(&users); err != nil {
  519. return nil, err
  520. }
  521. }
  522. if !repo.Owner.IsOrganization() {
  523. users = append(users, repo.Owner)
  524. }
  525. return users, nil
  526. }
  527. // GetAssignees returns all users that have write access and can be assigned to issues
  528. // of the repository,
  529. func (repo *Repository) GetAssignees() (_ []*User, err error) {
  530. return repo.getAssignees(x)
  531. }
  532. // GetMilestoneByID returns the milestone belongs to repository by given ID.
  533. func (repo *Repository) GetMilestoneByID(milestoneID int64) (*Milestone, error) {
  534. return GetMilestoneByRepoID(repo.ID, milestoneID)
  535. }
  536. // IssueStats returns number of open and closed repository issues by given filter mode.
  537. func (repo *Repository) IssueStats(uid int64, filterMode int, isPull bool) (int64, int64) {
  538. return GetRepoIssueStats(repo.ID, uid, filterMode, isPull)
  539. }
  540. // GetMirror sets the repository mirror, returns an error upon failure
  541. func (repo *Repository) GetMirror() (err error) {
  542. repo.Mirror, err = GetMirrorByRepoID(repo.ID)
  543. return err
  544. }
  545. // GetBaseRepo populates repo.BaseRepo for a fork repository and
  546. // returns an error on failure (NOTE: no error is returned for
  547. // non-fork repositories, and BaseRepo will be left untouched)
  548. func (repo *Repository) GetBaseRepo() (err error) {
  549. return repo.getBaseRepo(x)
  550. }
  551. func (repo *Repository) getBaseRepo(e Engine) (err error) {
  552. if !repo.IsFork {
  553. return nil
  554. }
  555. repo.BaseRepo, err = getRepositoryByID(e, repo.ForkID)
  556. return err
  557. }
  558. func (repo *Repository) repoPath(e Engine) string {
  559. return RepoPath(repo.mustOwnerName(e), repo.Name)
  560. }
  561. // RepoPath returns the repository path
  562. func (repo *Repository) RepoPath() string {
  563. return repo.repoPath(x)
  564. }
  565. // GitConfigPath returns the path to a repository's git config/ directory
  566. func GitConfigPath(repoPath string) string {
  567. return filepath.Join(repoPath, "config")
  568. }
  569. // GitConfigPath returns the repository git config path
  570. func (repo *Repository) GitConfigPath() string {
  571. return GitConfigPath(repo.RepoPath())
  572. }
  573. // RelLink returns the repository relative link
  574. func (repo *Repository) RelLink() string {
  575. return "/" + repo.FullName()
  576. }
  577. // Link returns the repository link
  578. func (repo *Repository) Link() string {
  579. return setting.AppSubURL + "/" + repo.FullName()
  580. }
  581. // ComposeCompareURL returns the repository comparison URL
  582. func (repo *Repository) ComposeCompareURL(oldCommitID, newCommitID string) string {
  583. return fmt.Sprintf("%s/%s/compare/%s...%s", repo.MustOwner().Name, repo.Name, oldCommitID, newCommitID)
  584. }
  585. // UpdateDefaultBranch updates the default branch
  586. func (repo *Repository) UpdateDefaultBranch() error {
  587. _, err := x.ID(repo.ID).Cols("default_branch").Update(repo)
  588. return err
  589. }
  590. // IsOwnedBy returns true when user owns this repository
  591. func (repo *Repository) IsOwnedBy(userID int64) bool {
  592. return repo.OwnerID == userID
  593. }
  594. func (repo *Repository) updateSize(e Engine) error {
  595. repoInfoSize, err := git.GetRepoSize(repo.repoPath(e))
  596. if err != nil {
  597. return fmt.Errorf("UpdateSize: %v", err)
  598. }
  599. repo.Size = repoInfoSize.Size + repoInfoSize.SizePack
  600. _, err = e.ID(repo.ID).Cols("size").Update(repo)
  601. return err
  602. }
  603. // UpdateSize updates the repository size, calculating it using git.GetRepoSize
  604. func (repo *Repository) UpdateSize() error {
  605. return repo.updateSize(x)
  606. }
  607. // CanUserFork returns true if specified user can fork repository.
  608. func (repo *Repository) CanUserFork(user *User) (bool, error) {
  609. if user == nil {
  610. return false, nil
  611. }
  612. if repo.OwnerID != user.ID && !user.HasForkedRepo(repo.ID) {
  613. return true, nil
  614. }
  615. if err := user.GetOwnedOrganizations(); err != nil {
  616. return false, err
  617. }
  618. for _, org := range user.OwnedOrgs {
  619. if repo.OwnerID != org.ID && !org.HasForkedRepo(repo.ID) {
  620. return true, nil
  621. }
  622. }
  623. return false, nil
  624. }
  625. // CanEnablePulls returns true if repository meets the requirements of accepting pulls.
  626. func (repo *Repository) CanEnablePulls() bool {
  627. return !repo.IsMirror && !repo.IsEmpty
  628. }
  629. // AllowsPulls returns true if repository meets the requirements of accepting pulls and has them enabled.
  630. func (repo *Repository) AllowsPulls() bool {
  631. return repo.CanEnablePulls() && repo.UnitEnabled(UnitTypePullRequests)
  632. }
  633. // CanEnableEditor returns true if repository meets the requirements of web editor.
  634. func (repo *Repository) CanEnableEditor() bool {
  635. return !repo.IsMirror
  636. }
  637. // GetWriters returns all users that have write access to the repository.
  638. func (repo *Repository) GetWriters() (_ []*User, err error) {
  639. return repo.getUsersWithAccessMode(x, AccessModeWrite)
  640. }
  641. // getUsersWithAccessMode returns users that have at least given access mode to the repository.
  642. func (repo *Repository) getUsersWithAccessMode(e Engine, mode AccessMode) (_ []*User, err error) {
  643. if err = repo.getOwner(e); err != nil {
  644. return nil, err
  645. }
  646. accesses := make([]*Access, 0, 10)
  647. if err = e.Where("repo_id = ? AND mode >= ?", repo.ID, mode).Find(&accesses); err != nil {
  648. return nil, err
  649. }
  650. // Leave a seat for owner itself to append later, but if owner is an organization
  651. // and just waste 1 unit is cheaper than re-allocate memory once.
  652. users := make([]*User, 0, len(accesses)+1)
  653. if len(accesses) > 0 {
  654. userIDs := make([]int64, len(accesses))
  655. for i := 0; i < len(accesses); i++ {
  656. userIDs[i] = accesses[i].UserID
  657. }
  658. if err = e.In("id", userIDs).Find(&users); err != nil {
  659. return nil, err
  660. }
  661. }
  662. if !repo.Owner.IsOrganization() {
  663. users = append(users, repo.Owner)
  664. }
  665. return users, nil
  666. }
  667. // DescriptionHTML does special handles to description and return HTML string.
  668. func (repo *Repository) DescriptionHTML() template.HTML {
  669. desc, err := markup.RenderDescriptionHTML([]byte(repo.Description), repo.HTMLURL(), repo.ComposeMetas())
  670. if err != nil {
  671. log.Error("Failed to render description for %s (ID: %d): %v", repo.Name, repo.ID, err)
  672. return template.HTML(markup.Sanitize(repo.Description))
  673. }
  674. return template.HTML(markup.Sanitize(string(desc)))
  675. }
  676. // PatchPath returns corresponding patch file path of repository by given issue ID.
  677. func (repo *Repository) PatchPath(index int64) (string, error) {
  678. return repo.patchPath(x, index)
  679. }
  680. func (repo *Repository) patchPath(e Engine, index int64) (string, error) {
  681. if err := repo.getOwner(e); err != nil {
  682. return "", err
  683. }
  684. return filepath.Join(RepoPath(repo.Owner.Name, repo.Name), "pulls", com.ToStr(index)+".patch"), nil
  685. }
  686. // SavePatch saves patch data to corresponding location by given issue ID.
  687. func (repo *Repository) SavePatch(index int64, patch []byte) error {
  688. return repo.savePatch(x, index, patch)
  689. }
  690. func (repo *Repository) savePatch(e Engine, index int64, patch []byte) error {
  691. patchPath, err := repo.patchPath(e, index)
  692. if err != nil {
  693. return fmt.Errorf("PatchPath: %v", err)
  694. }
  695. dir := filepath.Dir(patchPath)
  696. if err := os.MkdirAll(dir, os.ModePerm); err != nil {
  697. return fmt.Errorf("Failed to create dir %s: %v", dir, err)
  698. }
  699. if err = ioutil.WriteFile(patchPath, patch, 0644); err != nil {
  700. return fmt.Errorf("WriteFile: %v", err)
  701. }
  702. return nil
  703. }
  704. func isRepositoryExist(e Engine, u *User, repoName string) (bool, error) {
  705. has, err := e.Get(&Repository{
  706. OwnerID: u.ID,
  707. LowerName: strings.ToLower(repoName),
  708. })
  709. return has && com.IsDir(RepoPath(u.Name, repoName)), err
  710. }
  711. // IsRepositoryExist returns true if the repository with given name under user has already existed.
  712. func IsRepositoryExist(u *User, repoName string) (bool, error) {
  713. return isRepositoryExist(x, u, repoName)
  714. }
  715. // CloneLink represents different types of clone URLs of repository.
  716. type CloneLink struct {
  717. SSH string
  718. HTTPS string
  719. Git string
  720. }
  721. // ComposeHTTPSCloneURL returns HTTPS clone URL based on given owner and repository name.
  722. func ComposeHTTPSCloneURL(owner, repo string) string {
  723. return fmt.Sprintf("%s%s/%s.git", setting.AppURL, url.PathEscape(owner), url.PathEscape(repo))
  724. }
  725. func (repo *Repository) cloneLink(e Engine, isWiki bool) *CloneLink {
  726. repoName := repo.Name
  727. if isWiki {
  728. repoName += ".wiki"
  729. }
  730. sshUser := setting.RunUser
  731. if setting.SSH.StartBuiltinServer {
  732. sshUser = setting.SSH.BuiltinServerUser
  733. }
  734. repo.Owner = repo.mustOwner(e)
  735. cl := new(CloneLink)
  736. if setting.SSH.Port != 22 {
  737. cl.SSH = fmt.Sprintf("ssh://%s@%s:%d/%s/%s.git", sshUser, setting.SSH.Domain, setting.SSH.Port, repo.Owner.Name, repoName)
  738. } else if setting.Repository.UseCompatSSHURI {
  739. cl.SSH = fmt.Sprintf("ssh://%s@%s/%s/%s.git", sshUser, setting.SSH.Domain, repo.Owner.Name, repoName)
  740. } else {
  741. cl.SSH = fmt.Sprintf("%s@%s:%s/%s.git", sshUser, setting.SSH.Domain, repo.Owner.Name, repoName)
  742. }
  743. cl.HTTPS = ComposeHTTPSCloneURL(repo.Owner.Name, repoName)
  744. return cl
  745. }
  746. // CloneLink returns clone URLs of repository.
  747. func (repo *Repository) CloneLink() (cl *CloneLink) {
  748. return repo.cloneLink(x, false)
  749. }
  750. // MigrateRepoOptions contains the repository migrate options
  751. type MigrateRepoOptions struct {
  752. Name string
  753. Description string
  754. OriginalURL string
  755. IsPrivate bool
  756. IsMirror bool
  757. RemoteAddr string
  758. Wiki bool // include wiki repository
  759. SyncReleasesWithTags bool // sync releases from tags
  760. }
  761. /*
  762. GitHub, GitLab, Gogs: *.wiki.git
  763. BitBucket: *.git/wiki
  764. */
  765. var commonWikiURLSuffixes = []string{".wiki.git", ".git/wiki"}
  766. // wikiRemoteURL returns accessible repository URL for wiki if exists.
  767. // Otherwise, it returns an empty string.
  768. func wikiRemoteURL(remote string) string {
  769. remote = strings.TrimSuffix(remote, ".git")
  770. for _, suffix := range commonWikiURLSuffixes {
  771. wikiURL := remote + suffix
  772. if git.IsRepoURLAccessible(wikiURL) {
  773. return wikiURL
  774. }
  775. }
  776. return ""
  777. }
  778. // MigrateRepository migrates an existing repository from other project hosting.
  779. func MigrateRepository(doer, u *User, opts MigrateRepoOptions) (*Repository, error) {
  780. repo, err := CreateRepository(doer, u, CreateRepoOptions{
  781. Name: opts.Name,
  782. Description: opts.Description,
  783. OriginalURL: opts.OriginalURL,
  784. IsPrivate: opts.IsPrivate,
  785. IsMirror: opts.IsMirror,
  786. })
  787. if err != nil {
  788. return nil, err
  789. }
  790. repoPath := RepoPath(u.Name, opts.Name)
  791. if u.IsOrganization() {
  792. t, err := u.GetOwnerTeam()
  793. if err != nil {
  794. return nil, err
  795. }
  796. repo.NumWatches = t.NumMembers
  797. } else {
  798. repo.NumWatches = 1
  799. }
  800. migrateTimeout := time.Duration(setting.Git.Timeout.Migrate) * time.Second
  801. if err := os.RemoveAll(repoPath); err != nil {
  802. return repo, fmt.Errorf("Failed to remove %s: %v", repoPath, err)
  803. }
  804. if err = git.Clone(opts.RemoteAddr, repoPath, git.CloneRepoOptions{
  805. Mirror: true,
  806. Quiet: true,
  807. Timeout: migrateTimeout,
  808. }); err != nil {
  809. return repo, fmt.Errorf("Clone: %v", err)
  810. }
  811. if opts.Wiki {
  812. wikiPath := WikiPath(u.Name, opts.Name)
  813. wikiRemotePath := wikiRemoteURL(opts.RemoteAddr)
  814. if len(wikiRemotePath) > 0 {
  815. if err := os.RemoveAll(wikiPath); err != nil {
  816. return repo, fmt.Errorf("Failed to remove %s: %v", wikiPath, err)
  817. }
  818. if err = git.Clone(wikiRemotePath, wikiPath, git.CloneRepoOptions{
  819. Mirror: true,
  820. Quiet: true,
  821. Timeout: migrateTimeout,
  822. Branch: "master",
  823. }); err != nil {
  824. log.Warn("Clone wiki: %v", err)
  825. if err := os.RemoveAll(wikiPath); err != nil {
  826. return repo, fmt.Errorf("Failed to remove %s: %v", wikiPath, err)
  827. }
  828. }
  829. }
  830. }
  831. gitRepo, err := git.OpenRepository(repoPath)
  832. if err != nil {
  833. return repo, fmt.Errorf("OpenRepository: %v", err)
  834. }
  835. repo.IsEmpty, err = gitRepo.IsEmpty()
  836. if err != nil {
  837. return repo, fmt.Errorf("git.IsEmpty: %v", err)
  838. }
  839. if opts.SyncReleasesWithTags && !repo.IsEmpty {
  840. // Try to get HEAD branch and set it as default branch.
  841. headBranch, err := gitRepo.GetHEADBranch()
  842. if err != nil {
  843. return repo, fmt.Errorf("GetHEADBranch: %v", err)
  844. }
  845. if headBranch != nil {
  846. repo.DefaultBranch = headBranch.Name
  847. }
  848. if err = SyncReleasesWithTags(repo, gitRepo); err != nil {
  849. log.Error("Failed to synchronize tags to releases for repository: %v", err)
  850. }
  851. }
  852. if err = repo.UpdateSize(); err != nil {
  853. log.Error("Failed to update size for repository: %v", err)
  854. }
  855. if opts.IsMirror {
  856. if _, err = x.InsertOne(&Mirror{
  857. RepoID: repo.ID,
  858. Interval: setting.Mirror.DefaultInterval,
  859. EnablePrune: true,
  860. NextUpdateUnix: timeutil.TimeStampNow().AddDuration(setting.Mirror.DefaultInterval),
  861. }); err != nil {
  862. return repo, fmt.Errorf("InsertOne: %v", err)
  863. }
  864. repo.IsMirror = true
  865. err = UpdateRepository(repo, false)
  866. } else {
  867. repo, err = CleanUpMigrateInfo(repo)
  868. }
  869. if err != nil && !repo.IsEmpty {
  870. UpdateRepoIndexer(repo)
  871. }
  872. return repo, err
  873. }
  874. // cleanUpMigrateGitConfig removes mirror info which prevents "push --all".
  875. // This also removes possible user credentials.
  876. func cleanUpMigrateGitConfig(configPath string) error {
  877. cfg, err := ini.Load(configPath)
  878. if err != nil {
  879. return fmt.Errorf("open config file: %v", err)
  880. }
  881. cfg.DeleteSection("remote \"origin\"")
  882. if err = cfg.SaveToIndent(configPath, "\t"); err != nil {
  883. return fmt.Errorf("save config file: %v", err)
  884. }
  885. return nil
  886. }
  887. // createDelegateHooks creates all the hooks scripts for the repo
  888. func createDelegateHooks(repoPath string) (err error) {
  889. var (
  890. hookNames = []string{"pre-receive", "update", "post-receive"}
  891. hookTpls = []string{
  892. fmt.Sprintf("#!/usr/bin/env %s\ndata=$(cat)\nexitcodes=\"\"\nhookname=$(basename $0)\nGIT_DIR=${GIT_DIR:-$(dirname $0)}\n\nfor hook in ${GIT_DIR}/hooks/${hookname}.d/*; do\ntest -x \"${hook}\" || continue\necho \"${data}\" | \"${hook}\"\nexitcodes=\"${exitcodes} $?\"\ndone\n\nfor i in ${exitcodes}; do\n[ ${i} -eq 0 ] || exit ${i}\ndone\n", setting.ScriptType),
  893. fmt.Sprintf("#!/usr/bin/env %s\nexitcodes=\"\"\nhookname=$(basename $0)\nGIT_DIR=${GIT_DIR:-$(dirname $0)}\n\nfor hook in ${GIT_DIR}/hooks/${hookname}.d/*; do\ntest -x \"${hook}\" || continue\n\"${hook}\" $1 $2 $3\nexitcodes=\"${exitcodes} $?\"\ndone\n\nfor i in ${exitcodes}; do\n[ ${i} -eq 0 ] || exit ${i}\ndone\n", setting.ScriptType),
  894. fmt.Sprintf("#!/usr/bin/env %s\ndata=$(cat)\nexitcodes=\"\"\nhookname=$(basename $0)\nGIT_DIR=${GIT_DIR:-$(dirname $0)}\n\nfor hook in ${GIT_DIR}/hooks/${hookname}.d/*; do\ntest -x \"${hook}\" || continue\necho \"${data}\" | \"${hook}\"\nexitcodes=\"${exitcodes} $?\"\ndone\n\nfor i in ${exitcodes}; do\n[ ${i} -eq 0 ] || exit ${i}\ndone\n", setting.ScriptType),
  895. }
  896. giteaHookTpls = []string{
  897. fmt.Sprintf("#!/usr/bin/env %s\n\"%s\" hook --config='%s' pre-receive\n", setting.ScriptType, setting.AppPath, setting.CustomConf),
  898. fmt.Sprintf("#!/usr/bin/env %s\n\"%s\" hook --config='%s' update $1 $2 $3\n", setting.ScriptType, setting.AppPath, setting.CustomConf),
  899. fmt.Sprintf("#!/usr/bin/env %s\n\"%s\" hook --config='%s' post-receive\n", setting.ScriptType, setting.AppPath, setting.CustomConf),
  900. }
  901. )
  902. hookDir := filepath.Join(repoPath, "hooks")
  903. for i, hookName := range hookNames {
  904. oldHookPath := filepath.Join(hookDir, hookName)
  905. newHookPath := filepath.Join(hookDir, hookName+".d", "gitea")
  906. if err := os.MkdirAll(filepath.Join(hookDir, hookName+".d"), os.ModePerm); err != nil {
  907. return fmt.Errorf("create hooks dir '%s': %v", filepath.Join(hookDir, hookName+".d"), err)
  908. }
  909. // WARNING: This will override all old server-side hooks
  910. if err = ioutil.WriteFile(oldHookPath, []byte(hookTpls[i]), 0777); err != nil {
  911. return fmt.Errorf("write old hook file '%s': %v", oldHookPath, err)
  912. }
  913. if err = ioutil.WriteFile(newHookPath, []byte(giteaHookTpls[i]), 0777); err != nil {
  914. return fmt.Errorf("write new hook file '%s': %v", newHookPath, err)
  915. }
  916. }
  917. return nil
  918. }
  919. // CleanUpMigrateInfo finishes migrating repository and/or wiki with things that don't need to be done for mirrors.
  920. func CleanUpMigrateInfo(repo *Repository) (*Repository, error) {
  921. repoPath := repo.RepoPath()
  922. if err := createDelegateHooks(repoPath); err != nil {
  923. return repo, fmt.Errorf("createDelegateHooks: %v", err)
  924. }
  925. if repo.HasWiki() {
  926. if err := createDelegateHooks(repo.WikiPath()); err != nil {
  927. return repo, fmt.Errorf("createDelegateHooks.(wiki): %v", err)
  928. }
  929. }
  930. _, err := git.NewCommand("remote", "remove", "origin").RunInDir(repoPath)
  931. if err != nil && !strings.HasPrefix(err.Error(), "exit status 128 - fatal: No such remote ") {
  932. return repo, fmt.Errorf("CleanUpMigrateInfo: %v", err)
  933. }
  934. if repo.HasWiki() {
  935. if err := cleanUpMigrateGitConfig(path.Join(repo.WikiPath(), "config")); err != nil {
  936. return repo, fmt.Errorf("cleanUpMigrateGitConfig (wiki): %v", err)
  937. }
  938. }
  939. return repo, UpdateRepository(repo, false)
  940. }
  941. // initRepoCommit temporarily changes with work directory.
  942. func initRepoCommit(tmpPath string, sig *git.Signature) (err error) {
  943. var stderr string
  944. if _, stderr, err = process.GetManager().ExecDir(-1,
  945. tmpPath, fmt.Sprintf("initRepoCommit (git add): %s", tmpPath),
  946. git.GitExecutable, "add", "--all"); err != nil {
  947. return fmt.Errorf("git add: %s", stderr)
  948. }
  949. if _, stderr, err = process.GetManager().ExecDir(-1,
  950. tmpPath, fmt.Sprintf("initRepoCommit (git commit): %s", tmpPath),
  951. git.GitExecutable, "commit", fmt.Sprintf("--author='%s <%s>'", sig.Name, sig.Email),
  952. "-m", "Initial commit"); err != nil {
  953. return fmt.Errorf("git commit: %s", stderr)
  954. }
  955. if _, stderr, err = process.GetManager().ExecDir(-1,
  956. tmpPath, fmt.Sprintf("initRepoCommit (git push): %s", tmpPath),
  957. git.GitExecutable, "push", "origin", "master"); err != nil {
  958. return fmt.Errorf("git push: %s", stderr)
  959. }
  960. return nil
  961. }
  962. // CreateRepoOptions contains the create repository options
  963. type CreateRepoOptions struct {
  964. Name string
  965. Description string
  966. OriginalURL string
  967. Gitignores string
  968. IssueLabels string
  969. License string
  970. Readme string
  971. IsPrivate bool
  972. IsMirror bool
  973. AutoInit bool
  974. }
  975. func getRepoInitFile(tp, name string) ([]byte, error) {
  976. cleanedName := strings.TrimLeft(path.Clean("/"+name), "/")
  977. relPath := path.Join("options", tp, cleanedName)
  978. // Use custom file when available.
  979. customPath := path.Join(setting.CustomPath, relPath)
  980. if com.IsFile(customPath) {
  981. return ioutil.ReadFile(customPath)
  982. }
  983. switch tp {
  984. case "readme":
  985. return options.Readme(cleanedName)
  986. case "gitignore":
  987. return options.Gitignore(cleanedName)
  988. case "license":
  989. return options.License(cleanedName)
  990. case "label":
  991. return options.Labels(cleanedName)
  992. default:
  993. return []byte{}, fmt.Errorf("Invalid init file type")
  994. }
  995. }
  996. func prepareRepoCommit(e Engine, repo *Repository, tmpDir, repoPath string, opts CreateRepoOptions) error {
  997. // Clone to temporary path and do the init commit.
  998. _, stderr, err := process.GetManager().Exec(
  999. fmt.Sprintf("initRepository(git clone): %s", repoPath),
  1000. git.GitExecutable, "clone", repoPath, tmpDir,
  1001. )
  1002. if err != nil {
  1003. return fmt.Errorf("git clone: %v - %s", err, stderr)
  1004. }
  1005. // README
  1006. data, err := getRepoInitFile("readme", opts.Readme)
  1007. if err != nil {
  1008. return fmt.Errorf("getRepoInitFile[%s]: %v", opts.Readme, err)
  1009. }
  1010. cloneLink := repo.cloneLink(e, false)
  1011. match := map[string]string{
  1012. "Name": repo.Name,
  1013. "Description": repo.Description,
  1014. "CloneURL.SSH": cloneLink.SSH,
  1015. "CloneURL.HTTPS": cloneLink.HTTPS,
  1016. }
  1017. if err = ioutil.WriteFile(filepath.Join(tmpDir, "README.md"),
  1018. []byte(com.Expand(string(data), match)), 0644); err != nil {
  1019. return fmt.Errorf("write README.md: %v", err)
  1020. }
  1021. // .gitignore
  1022. if len(opts.Gitignores) > 0 {
  1023. var buf bytes.Buffer
  1024. names := strings.Split(opts.Gitignores, ",")
  1025. for _, name := range names {
  1026. data, err = getRepoInitFile("gitignore", name)
  1027. if err != nil {
  1028. return fmt.Errorf("getRepoInitFile[%s]: %v", name, err)
  1029. }
  1030. buf.WriteString("# ---> " + name + "\n")
  1031. buf.Write(data)
  1032. buf.WriteString("\n")
  1033. }
  1034. if buf.Len() > 0 {
  1035. if err = ioutil.WriteFile(filepath.Join(tmpDir, ".gitignore"), buf.Bytes(), 0644); err != nil {
  1036. return fmt.Errorf("write .gitignore: %v", err)
  1037. }
  1038. }
  1039. }
  1040. // LICENSE
  1041. if len(opts.License) > 0 {
  1042. data, err = getRepoInitFile("license", opts.License)
  1043. if err != nil {
  1044. return fmt.Errorf("getRepoInitFile[%s]: %v", opts.License, err)
  1045. }
  1046. if err = ioutil.WriteFile(filepath.Join(tmpDir, "LICENSE"), data, 0644); err != nil {
  1047. return fmt.Errorf("write LICENSE: %v", err)
  1048. }
  1049. }
  1050. return nil
  1051. }
  1052. // InitRepository initializes README and .gitignore if needed.
  1053. func initRepository(e Engine, repoPath string, u *User, repo *Repository, opts CreateRepoOptions) (err error) {
  1054. // Somehow the directory could exist.
  1055. if com.IsExist(repoPath) {
  1056. return fmt.Errorf("initRepository: path already exists: %s", repoPath)
  1057. }
  1058. // Init git bare new repository.
  1059. if err = git.InitRepository(repoPath, true); err != nil {
  1060. return fmt.Errorf("InitRepository: %v", err)
  1061. } else if err = createDelegateHooks(repoPath); err != nil {
  1062. return fmt.Errorf("createDelegateHooks: %v", err)
  1063. }
  1064. tmpDir := filepath.Join(os.TempDir(), "gitea-"+repo.Name+"-"+com.ToStr(time.Now().Nanosecond()))
  1065. // Initialize repository according to user's choice.
  1066. if opts.AutoInit {
  1067. if err := os.MkdirAll(tmpDir, os.ModePerm); err != nil {
  1068. return fmt.Errorf("Failed to create dir %s: %v", tmpDir, err)
  1069. }
  1070. defer os.RemoveAll(tmpDir)
  1071. if err = prepareRepoCommit(e, repo, tmpDir, repoPath, opts); err != nil {
  1072. return fmt.Errorf("prepareRepoCommit: %v", err)
  1073. }
  1074. // Apply changes and commit.
  1075. if err = initRepoCommit(tmpDir, u.NewGitSig()); err != nil {
  1076. return fmt.Errorf("initRepoCommit: %v", err)
  1077. }
  1078. }
  1079. // Re-fetch the repository from database before updating it (else it would
  1080. // override changes that were done earlier with sql)
  1081. if repo, err = getRepositoryByID(e, repo.ID); err != nil {
  1082. return fmt.Errorf("getRepositoryByID: %v", err)
  1083. }
  1084. if !opts.AutoInit {
  1085. repo.IsEmpty = true
  1086. }
  1087. repo.DefaultBranch = "master"
  1088. if err = updateRepository(e, repo, false); err != nil {
  1089. return fmt.Errorf("updateRepository: %v", err)
  1090. }
  1091. return nil
  1092. }
  1093. var (
  1094. reservedRepoNames = []string{".", ".."}
  1095. reservedRepoPatterns = []string{"*.git", "*.wiki"}
  1096. )
  1097. // IsUsableRepoName returns true when repository is usable
  1098. func IsUsableRepoName(name string) error {
  1099. return isUsableName(reservedRepoNames, reservedRepoPatterns, name)
  1100. }
  1101. func createRepository(e *xorm.Session, doer, u *User, repo *Repository) (err error) {
  1102. if err = IsUsableRepoName(repo.Name); err != nil {
  1103. return err
  1104. }
  1105. has, err := isRepositoryExist(e, u, repo.Name)
  1106. if err != nil {
  1107. return fmt.Errorf("IsRepositoryExist: %v", err)
  1108. } else if has {
  1109. return ErrRepoAlreadyExist{u.Name, repo.Name}
  1110. }
  1111. if _, err = e.Insert(repo); err != nil {
  1112. return err
  1113. }
  1114. if err = deleteRepoRedirect(e, u.ID, repo.Name); err != nil {
  1115. return err
  1116. }
  1117. // insert units for repo
  1118. var units = make([]RepoUnit, 0, len(DefaultRepoUnits))
  1119. for _, tp := range DefaultRepoUnits {
  1120. if tp == UnitTypeIssues {
  1121. units = append(units, RepoUnit{
  1122. RepoID: repo.ID,
  1123. Type: tp,
  1124. Config: &IssuesConfig{
  1125. EnableTimetracker: setting.Service.DefaultEnableTimetracking,
  1126. AllowOnlyContributorsToTrackTime: setting.Service.DefaultAllowOnlyContributorsToTrackTime,
  1127. EnableDependencies: setting.Service.DefaultEnableDependencies,
  1128. },
  1129. })
  1130. } else if tp == UnitTypePullRequests {
  1131. units = append(units, RepoUnit{
  1132. RepoID: repo.ID,
  1133. Type: tp,
  1134. Config: &PullRequestsConfig{AllowMerge: true, AllowRebase: true, AllowRebaseMerge: true, AllowSquash: true},
  1135. })
  1136. } else {
  1137. units = append(units, RepoUnit{
  1138. RepoID: repo.ID,
  1139. Type: tp,
  1140. })
  1141. }
  1142. }
  1143. if _, err = e.Insert(&units); err != nil {
  1144. return err
  1145. }
  1146. // Remember visibility preference.
  1147. u.LastRepoVisibility = repo.IsPrivate
  1148. if err = updateUserCols(e, u, "last_repo_visibility"); err != nil {
  1149. return fmt.Errorf("updateUser: %v", err)
  1150. }
  1151. if _, err = e.Incr("num_repos").ID(u.ID).Update(new(User)); err != nil {
  1152. return fmt.Errorf("increment user total_repos: %v", err)
  1153. }
  1154. u.NumRepos++
  1155. // Give access to all members in owner team.
  1156. if u.IsOrganization() {
  1157. t, err := u.getOwnerTeam(e)
  1158. if err != nil {
  1159. return fmt.Errorf("getOwnerTeam: %v", err)
  1160. } else if err = t.addRepository(e, repo); err != nil {
  1161. return fmt.Errorf("addRepository: %v", err)
  1162. } else if err = prepareWebhooks(e, repo, HookEventRepository, &api.RepositoryPayload{
  1163. Action: api.HookRepoCreated,
  1164. Repository: repo.innerAPIFormat(e, AccessModeOwner, false),
  1165. Organization: u.APIFormat(),
  1166. Sender: doer.APIFormat(),
  1167. }); err != nil {
  1168. return fmt.Errorf("prepareWebhooks: %v", err)
  1169. }
  1170. } else if err = repo.recalculateAccesses(e); err != nil {
  1171. // Organization automatically called this in addRepository method.
  1172. return fmt.Errorf("recalculateAccesses: %v", err)
  1173. }
  1174. if setting.Service.AutoWatchNewRepos {
  1175. if err = watchRepo(e, doer.ID, repo.ID, true); err != nil {
  1176. return fmt.Errorf("watchRepo: %v", err)
  1177. }
  1178. }
  1179. if err = newRepoAction(e, doer, repo); err != nil {
  1180. return fmt.Errorf("newRepoAction: %v", err)
  1181. }
  1182. if err = copyDefaultWebhooksToRepo(e, repo.ID); err != nil {
  1183. return fmt.Errorf("copyDefaultWebhooksToRepo: %v", err)
  1184. }
  1185. return nil
  1186. }
  1187. // CreateRepository creates a repository for the user/organization.
  1188. func CreateRepository(doer, u *User, opts CreateRepoOptions) (_ *Repository, err error) {
  1189. if !doer.IsAdmin && !u.CanCreateRepo() {
  1190. return nil, ErrReachLimitOfRepo{u.MaxRepoCreation}
  1191. }
  1192. repo := &Repository{
  1193. OwnerID: u.ID,
  1194. Owner: u,
  1195. Name: opts.Name,
  1196. LowerName: strings.ToLower(opts.Name),
  1197. Description: opts.Description,
  1198. OriginalURL: opts.OriginalURL,
  1199. IsPrivate: opts.IsPrivate,
  1200. IsFsckEnabled: !opts.IsMirror,
  1201. CloseIssuesViaCommitInAnyBranch: setting.Repository.DefaultCloseIssuesViaCommitsInAnyBranch,
  1202. }
  1203. sess := x.NewSession()
  1204. defer sess.Close()
  1205. if err = sess.Begin(); err != nil {
  1206. return nil, err
  1207. }
  1208. if err = createRepository(sess, doer, u, repo); err != nil {
  1209. return nil, err
  1210. }
  1211. // No need for init mirror.
  1212. if !opts.IsMirror {
  1213. repoPath := RepoPath(u.Name, repo.Name)
  1214. if err = initRepository(sess, repoPath, u, repo, opts); err != nil {
  1215. if err2 := os.RemoveAll(repoPath); err2 != nil {
  1216. log.Error("initRepository: %v", err)
  1217. return nil, fmt.Errorf(
  1218. "delete repo directory %s/%s failed(2): %v", u.Name, repo.Name, err2)
  1219. }
  1220. return nil, fmt.Errorf("initRepository: %v", err)
  1221. }
  1222. // Initialize Issue Labels if selected
  1223. if len(opts.IssueLabels) > 0 {
  1224. if err = initalizeLabels(sess, repo.ID, opts.IssueLabels); err != nil {
  1225. return nil, fmt.Errorf("initalizeLabels: %v", err)
  1226. }
  1227. }
  1228. _, stderr, err := process.GetManager().ExecDir(-1,
  1229. repoPath, fmt.Sprintf("CreateRepository(git update-server-info): %s", repoPath),
  1230. git.GitExecutable, "update-server-info")
  1231. if err != nil {
  1232. return nil, errors.New("CreateRepository(git update-server-info): " + stderr)
  1233. }
  1234. }
  1235. if err = sess.Commit(); err != nil {
  1236. return nil, err
  1237. }
  1238. // Add to hook queue for created repo after session commit.
  1239. if u.IsOrganization() {
  1240. go HookQueue.Add(repo.ID)
  1241. }
  1242. return repo, err
  1243. }
  1244. func countRepositories(userID int64, private bool) int64 {
  1245. sess := x.Where("id > 0")
  1246. if userID > 0 {
  1247. sess.And("owner_id = ?", userID)
  1248. }
  1249. if !private {
  1250. sess.And("is_private=?", false)
  1251. }
  1252. count, err := sess.Count(new(Repository))
  1253. if err != nil {
  1254. log.Error("countRepositories: %v", err)
  1255. }
  1256. return count
  1257. }
  1258. // CountRepositories returns number of repositories.
  1259. // Argument private only takes effect when it is false,
  1260. // set it true to count all repositories.
  1261. func CountRepositories(private bool) int64 {
  1262. return countRepositories(-1, private)
  1263. }
  1264. // CountUserRepositories returns number of repositories user owns.
  1265. // Argument private only takes effect when it is false,
  1266. // set it true to count all repositories.
  1267. func CountUserRepositories(userID int64, private bool) int64 {
  1268. return countRepositories(userID, private)
  1269. }
  1270. // RepoPath returns repository path by given user and repository name.
  1271. func RepoPath(userName, repoName string) string {
  1272. return filepath.Join(UserPath(userName), strings.ToLower(repoName)+".git")
  1273. }
  1274. // TransferOwnership transfers all corresponding setting from old user to new one.
  1275. func TransferOwnership(doer *User, newOwnerName string, repo *Repository) error {
  1276. newOwner, err := GetUserByName(newOwnerName)
  1277. if err != nil {
  1278. return fmt.Errorf("get new owner '%s': %v", newOwnerName, err)
  1279. }
  1280. // Check if new owner has repository with same name.
  1281. has, err := IsRepositoryExist(newOwner, repo.Name)
  1282. if err != nil {
  1283. return fmt.Errorf("IsRepositoryExist: %v", err)
  1284. } else if has {
  1285. return ErrRepoAlreadyExist{newOwnerName, repo.Name}
  1286. }
  1287. sess := x.NewSession()
  1288. defer sess.Close()
  1289. if err = sess.Begin(); err != nil {
  1290. return fmt.Errorf("sess.Begin: %v", err)
  1291. }
  1292. owner := repo.Owner
  1293. // Note: we have to set value here to make sure recalculate accesses is based on
  1294. // new owner.
  1295. repo.OwnerID = newOwner.ID
  1296. repo.Owner = newOwner
  1297. // Update repository.
  1298. if _, err := sess.ID(repo.ID).Update(repo); err != nil {
  1299. return fmt.Errorf("update owner: %v", err)
  1300. }
  1301. // Remove redundant collaborators.
  1302. collaborators, err := repo.getCollaborators(sess)
  1303. if err != nil {
  1304. return fmt.Errorf("getCollaborators: %v", err)
  1305. }
  1306. // Dummy object.
  1307. collaboration := &Collaboration{RepoID: repo.ID}
  1308. for _, c := range collaborators {
  1309. if c.ID != newOwner.ID {
  1310. isMember, err := isOrganizationMember(sess, newOwner.ID, c.ID)
  1311. if err != nil {
  1312. return fmt.Errorf("IsOrgMember: %v", err)
  1313. } else if !isMember {
  1314. continue
  1315. }
  1316. }
  1317. collaboration.UserID = c.ID
  1318. if _, err = sess.Delete(collaboration); err != nil {
  1319. return fmt.Errorf("remove collaborator '%d': %v", c.ID, err)
  1320. }
  1321. }
  1322. // Remove old team-repository relations.
  1323. if owner.IsOrganization() {
  1324. if err = owner.removeOrgRepo(sess, repo.ID); err != nil {
  1325. return fmt.Errorf("removeOrgRepo: %v", err)
  1326. }
  1327. }
  1328. if newOwner.IsOrganization() {
  1329. t, err := newOwner.getOwnerTeam(sess)
  1330. if err != nil {
  1331. return fmt.Errorf("getOwnerTeam: %v", err)
  1332. } else if err = t.addRepository(sess, repo); err != nil {
  1333. return fmt.Errorf("add to owner team: %v", err)
  1334. }
  1335. } else if err = repo.recalculateAccesses(sess); err != nil {
  1336. // Organization called this in addRepository method.
  1337. return fmt.Errorf("recalculateAccesses: %v", err)
  1338. }
  1339. // Update repository count.
  1340. if _, err = sess.Exec("UPDATE `user` SET num_repos=num_repos+1 WHERE id=?", newOwner.ID); err != nil {
  1341. return fmt.Errorf("increase new owner repository count: %v", err)
  1342. } else if _, err = sess.Exec("UPDATE `user` SET num_repos=num_repos-1 WHERE id=?", owner.ID); err != nil {
  1343. return fmt.Errorf("decrease old owner repository count: %v", err)
  1344. }
  1345. if err = watchRepo(sess, doer.ID, repo.ID, true); err != nil {
  1346. return fmt.Errorf("watchRepo: %v", err)
  1347. } else if err = transferRepoAction(sess, doer, owner, repo); err != nil {
  1348. return fmt.Errorf("transferRepoAction: %v", err)
  1349. }
  1350. // Rename remote repository to new path and delete local copy.
  1351. dir := UserPath(newOwner.Name)
  1352. if err := os.MkdirAll(dir, os.ModePerm); err != nil {
  1353. return fmt.Errorf("Failed to create dir %s: %v", dir, err)
  1354. }
  1355. if err = os.Rename(RepoPath(owner.Name, repo.Name), RepoPath(newOwner.Name, repo.Name)); err != nil {
  1356. return fmt.Errorf("rename repository directory: %v", err)
  1357. }
  1358. // Rename remote wiki repository to new path and delete local copy.
  1359. wikiPath := WikiPath(owner.Name, repo.Name)
  1360. if com.IsExist(wikiPath) {
  1361. if err = os.Rename(wikiPath, WikiPath(newOwner.Name, repo.Name)); err != nil {
  1362. return fmt.Errorf("rename repository wiki: %v", err)
  1363. }
  1364. }
  1365. // If there was previously a redirect at this location, remove it.
  1366. if err = deleteRepoRedirect(sess, newOwner.ID, repo.Name); err != nil {
  1367. return fmt.Errorf("delete repo redirect: %v", err)
  1368. }
  1369. return sess.Commit()
  1370. }
  1371. // ChangeRepositoryName changes all corresponding setting from old repository name to new one.
  1372. func ChangeRepositoryName(u *User, oldRepoName, newRepoName string) (err error) {
  1373. oldRepoName = strings.ToLower(oldRepoName)
  1374. newRepoName = strings.ToLower(newRepoName)
  1375. if err = IsUsableRepoName(newRepoName); err != nil {
  1376. return err
  1377. }
  1378. has, err := IsRepositoryExist(u, newRepoName)
  1379. if err != nil {
  1380. return fmt.Errorf("IsRepositoryExist: %v", err)
  1381. } else if has {
  1382. return ErrRepoAlreadyExist{u.Name, newRepoName}
  1383. }
  1384. repo, err := GetRepositoryByName(u.ID, oldRepoName)
  1385. if err != nil {
  1386. return fmt.Errorf("GetRepositoryByName: %v", err)
  1387. }
  1388. // Change repository directory name. We must lock the local copy of the
  1389. // repo so that we can atomically rename the repo path and updates the
  1390. // local copy's origin accordingly.
  1391. repoWorkingPool.CheckIn(com.ToStr(repo.ID))
  1392. defer repoWorkingPool.CheckOut(com.ToStr(repo.ID))
  1393. newRepoPath := RepoPath(u.Name, newRepoName)
  1394. if err = os.Rename(repo.RepoPath(), newRepoPath); err != nil {
  1395. return fmt.Errorf("rename repository directory: %v", err)
  1396. }
  1397. wikiPath := repo.WikiPath()
  1398. if com.IsExist(wikiPath) {
  1399. if err = os.Rename(wikiPath, WikiPath(u.Name, newRepoName)); err != nil {
  1400. return fmt.Errorf("rename repository wiki: %v", err)
  1401. }
  1402. }
  1403. sess := x.NewSession()
  1404. defer sess.Close()
  1405. if err = sess.Begin(); err != nil {
  1406. return fmt.Errorf("sess.Begin: %v", err)
  1407. }
  1408. // If there was previously a redirect at this location, remove it.
  1409. if err = deleteRepoRedirect(sess, u.ID, newRepoName); err != nil {
  1410. return fmt.Errorf("delete repo redirect: %v", err)
  1411. }
  1412. return sess.Commit()
  1413. }
  1414. func getRepositoriesByForkID(e Engine, forkID int64) ([]*Repository, error) {
  1415. repos := make([]*Repository, 0, 10)
  1416. return repos, e.
  1417. Where("fork_id=?", forkID).
  1418. Find(&repos)
  1419. }
  1420. // GetRepositoriesByForkID returns all repositories with given fork ID.
  1421. func GetRepositoriesByForkID(forkID int64) ([]*Repository, error) {
  1422. return getRepositoriesByForkID(x, forkID)
  1423. }
  1424. func updateRepository(e Engine, repo *Repository, visibilityChanged bool) (err error) {
  1425. repo.LowerName = strings.ToLower(repo.Name)
  1426. if len(repo.Description) > 255 {
  1427. repo.Description = repo.Description[:255]
  1428. }
  1429. if len(repo.Website) > 255 {
  1430. repo.Website = repo.Website[:255]
  1431. }
  1432. if _, err = e.ID(repo.ID).AllCols().Update(repo); err != nil {
  1433. return fmt.Errorf("update: %v", err)
  1434. }
  1435. if visibilityChanged {
  1436. if err = repo.getOwner(e); err != nil {
  1437. return fmt.Errorf("getOwner: %v", err)
  1438. }
  1439. if repo.Owner.IsOrganization() {
  1440. // Organization repository need to recalculate access table when visibility is changed.
  1441. if err = repo.recalculateTeamAccesses(e, 0); err != nil {
  1442. return fmt.Errorf("recalculateTeamAccesses: %v", err)
  1443. }
  1444. }
  1445. // If repo has become private, we need to set its actions to private.
  1446. if repo.IsPrivate {
  1447. _, err = e.Where("repo_id = ?", repo.ID).Cols("is_private").Update(&Action{
  1448. IsPrivate: true,
  1449. })
  1450. if err != nil {
  1451. return err
  1452. }
  1453. }
  1454. // Create/Remove git-daemon-export-ok for git-daemon...
  1455. daemonExportFile := path.Join(repo.repoPath(e), `git-daemon-export-ok`)
  1456. if repo.IsPrivate && com.IsExist(daemonExportFile) {
  1457. if err = os.Remove(daemonExportFile); err != nil {
  1458. log.Error("Failed to remove %s: %v", daemonExportFile, err)
  1459. }
  1460. } else if !repo.IsPrivate && !com.IsExist(daemonExportFile) {
  1461. if f, err := os.Create(daemonExportFile); err != nil {
  1462. log.Error("Failed to create %s: %v", daemonExportFile, err)
  1463. } else {
  1464. f.Close()
  1465. }
  1466. }
  1467. forkRepos, err := getRepositoriesByForkID(e, repo.ID)
  1468. if err != nil {
  1469. return fmt.Errorf("getRepositoriesByForkID: %v", err)
  1470. }
  1471. for i := range forkRepos {
  1472. forkRepos[i].IsPrivate = repo.IsPrivate
  1473. if err = updateRepository(e, forkRepos[i], true); err != nil {
  1474. return fmt.Errorf("updateRepository[%d]: %v", forkRepos[i].ID, err)
  1475. }
  1476. }
  1477. if err = repo.updateSize(e); err != nil {
  1478. log.Error("Failed to update size for repository: %v", err)
  1479. }
  1480. }
  1481. return nil
  1482. }
  1483. // UpdateRepository updates a repository
  1484. func UpdateRepository(repo *Repository, visibilityChanged bool) (err error) {
  1485. sess := x.NewSession()
  1486. defer sess.Close()
  1487. if err = sess.Begin(); err != nil {
  1488. return err
  1489. }
  1490. if err = updateRepository(sess, repo, visibilityChanged); err != nil {
  1491. return fmt.Errorf("updateRepository: %v", err)
  1492. }
  1493. return sess.Commit()
  1494. }
  1495. // UpdateRepositoryUpdatedTime updates a repository's updated time
  1496. func UpdateRepositoryUpdatedTime(repoID int64, updateTime time.Time) error {
  1497. _, err := x.Exec("UPDATE repository SET updated_unix = ? WHERE id = ?", updateTime.Unix(), repoID)
  1498. return err
  1499. }
  1500. // UpdateRepositoryUnits updates a repository's units
  1501. func UpdateRepositoryUnits(repo *Repository, units []RepoUnit) (err error) {
  1502. sess := x.NewSession()
  1503. defer sess.Close()
  1504. if err = sess.Begin(); err != nil {
  1505. return err
  1506. }
  1507. if _, err = sess.Where("repo_id = ?", repo.ID).Delete(new(RepoUnit)); err != nil {
  1508. return err
  1509. }
  1510. if _, err = sess.Insert(units); err != nil {
  1511. return err
  1512. }
  1513. return sess.Commit()
  1514. }
  1515. // DeleteRepository deletes a repository for a user or organization.
  1516. func DeleteRepository(doer *User, uid, repoID int64) error {
  1517. // In case is a organization.
  1518. org, err := GetUserByID(uid)
  1519. if err != nil {
  1520. return err
  1521. }
  1522. if org.IsOrganization() {
  1523. if err = org.GetTeams(); err != nil {
  1524. return err
  1525. }
  1526. }
  1527. sess := x.NewSession()
  1528. defer sess.Close()
  1529. if err = sess.Begin(); err != nil {
  1530. return err
  1531. }
  1532. repo := &Repository{ID: repoID, OwnerID: uid}
  1533. has, err := sess.Get(repo)
  1534. if err != nil {
  1535. return err
  1536. } else if !has {
  1537. return ErrRepoNotExist{repoID, uid, "", ""}
  1538. }
  1539. // Delete Deploy Keys
  1540. deployKeys, err := listDeployKeys(sess, repo.ID)
  1541. if err != nil {
  1542. return fmt.Errorf("listDeployKeys: %v", err)
  1543. }
  1544. for _, dKey := range deployKeys {
  1545. if err := deleteDeployKey(sess, doer, dKey.ID); err != nil {
  1546. return fmt.Errorf("deleteDeployKeys: %v", err)
  1547. }
  1548. }
  1549. if cnt, err := sess.ID(repoID).Delete(&Repository{}); err != nil {
  1550. return err
  1551. } else if cnt != 1 {
  1552. return ErrRepoNotExist{repoID, uid, "", ""}
  1553. }
  1554. if org.IsOrganization() {
  1555. for _, t := range org.Teams {
  1556. if !t.hasRepository(sess, repoID) {
  1557. continue
  1558. } else if err = t.removeRepository(sess, repo, false); err != nil {
  1559. return err
  1560. }
  1561. }
  1562. }
  1563. if err = deleteBeans(sess,
  1564. &Access{RepoID: repo.ID},
  1565. &Action{RepoID: repo.ID},
  1566. &Watch{RepoID: repoID},
  1567. &Star{RepoID: repoID},
  1568. &Mirror{RepoID: repoID},
  1569. &Milestone{RepoID: repoID},
  1570. &Release{RepoID: repoID},
  1571. &Collaboration{RepoID: repoID},
  1572. &PullRequest{BaseRepoID: repoID},
  1573. &RepoUnit{RepoID: repoID},
  1574. &RepoRedirect{RedirectRepoID: repoID},
  1575. &Webhook{RepoID: repoID},
  1576. &HookTask{RepoID: repoID},
  1577. &Notification{RepoID: repoID},
  1578. &CommitStatus{RepoID: repoID},
  1579. &RepoIndexerStatus{RepoID: repoID},
  1580. &Comment{RefRepoID: repoID},
  1581. ); err != nil {
  1582. return fmt.Errorf("deleteBeans: %v", err)
  1583. }
  1584. deleteCond := builder.Select("id").From("issue").Where(builder.Eq{"repo_id": repoID})
  1585. // Delete comments and attachments
  1586. if _, err = sess.In("issue_id", deleteCond).
  1587. Delete(&Comment{}); err != nil {
  1588. return err
  1589. }
  1590. if _, err = sess.In("issue_id", deleteCond).
  1591. Delete(&IssueUser{}); err != nil {
  1592. return err
  1593. }
  1594. if _, err = sess.In("issue_id", deleteCond).
  1595. Delete(&Reaction{}); err != nil {
  1596. return err
  1597. }
  1598. if _, err = sess.In("issue_id", deleteCond).
  1599. Delete(&IssueWatch{}); err != nil {
  1600. return err
  1601. }
  1602. if _, err = sess.In("issue_id", deleteCond).
  1603. Delete(&Stopwatch{}); err != nil {
  1604. return err
  1605. }
  1606. attachmentPaths := make([]string, 0, 20)
  1607. attachments := make([]*Attachment, 0, len(attachmentPaths))
  1608. if err = sess.Join("INNER", "issue", "issue.id = attachment.issue_id").
  1609. Where("issue.repo_id = ?", repoID).
  1610. Find(&attachments); err != nil {
  1611. return err
  1612. }
  1613. for j := range attachments {
  1614. attachmentPaths = append(attachmentPaths, attachments[j].LocalPath())
  1615. }
  1616. if _, err = sess.In("issue_id", deleteCond).
  1617. Delete(&Attachment{}); err != nil {
  1618. return err
  1619. }
  1620. if _, err = sess.Delete(&Issue{RepoID: repoID}); err != nil {
  1621. return err
  1622. }
  1623. if _, err = sess.Where("repo_id = ?", repoID).Delete(new(RepoUnit)); err != nil {
  1624. return err
  1625. }
  1626. if repo.IsFork {
  1627. if _, err = sess.Exec("UPDATE `repository` SET num_forks=num_forks-1 WHERE id=?", repo.ForkID); err != nil {
  1628. return fmt.Errorf("decrease fork count: %v", err)
  1629. }
  1630. }
  1631. if _, err = sess.Exec("UPDATE `user` SET num_repos=num_repos-1 WHERE id=?", uid); err != nil {
  1632. return err
  1633. }
  1634. // FIXME: Remove repository files should be executed after transaction succeed.
  1635. repoPath := repo.repoPath(sess)
  1636. removeAllWithNotice(sess, "Delete repository files", repoPath)
  1637. err = repo.deleteWiki(sess)
  1638. if err != nil {
  1639. return err
  1640. }
  1641. // Remove attachment files.
  1642. for i := range attachmentPaths {
  1643. removeAllWithNotice(sess, "Delete attachment", attachmentPaths[i])
  1644. }
  1645. // Remove LFS objects
  1646. var lfsObjects []*LFSMetaObject
  1647. if err = sess.Where("repository_id=?", repoID).Find(&lfsObjects); err != nil {
  1648. return err
  1649. }
  1650. for _, v := range lfsObjects {
  1651. count, err := sess.Count(&LFSMetaObject{Oid: v.Oid})
  1652. if err != nil {
  1653. return err
  1654. }
  1655. if count > 1 {
  1656. continue
  1657. }
  1658. oidPath := filepath.Join(v.Oid[0:2], v.Oid[2:4], v.Oid[4:len(v.Oid)])
  1659. removeAllWithNotice(sess, "Delete orphaned LFS file", oidPath)
  1660. }
  1661. if _, err := sess.Delete(&LFSMetaObject{RepositoryID: repoID}); err != nil {
  1662. return err
  1663. }
  1664. if repo.NumForks > 0 {
  1665. if _, err = sess.Exec("UPDATE `repository` SET fork_id=0,is_fork=? WHERE fork_id=?", false, repo.ID); err != nil {
  1666. log.Error("reset 'fork_id' and 'is_fork': %v", err)
  1667. }
  1668. }
  1669. if err = sess.Commit(); err != nil {
  1670. if len(deployKeys) > 0 {
  1671. // We need to rewrite the public keys because the commit failed
  1672. if err2 := RewriteAllPublicKeys(); err2 != nil {
  1673. return fmt.Errorf("Commit: %v SSH Keys: %v", err, err2)
  1674. }
  1675. }
  1676. return fmt.Errorf("Commit: %v", err)
  1677. }
  1678. if org.IsOrganization() {
  1679. if err = PrepareWebhooks(repo, HookEventRepository, &api.RepositoryPayload{
  1680. Action: api.HookRepoDeleted,
  1681. Repository: repo.APIFormat(AccessModeOwner),
  1682. Organization: org.APIFormat(),
  1683. Sender: doer.APIFormat(),
  1684. }); err != nil {
  1685. return err
  1686. }
  1687. go HookQueue.Add(repo.ID)
  1688. }
  1689. if len(repo.Avatar) > 0 {
  1690. avatarPath := repo.CustomAvatarPath()
  1691. if com.IsExist(avatarPath) {
  1692. if err := os.Remove(avatarPath); err != nil {
  1693. return fmt.Errorf("Failed to remove %s: %v", avatarPath, err)
  1694. }
  1695. }
  1696. }
  1697. DeleteRepoFromIndexer(repo)
  1698. return nil
  1699. }
  1700. // GetRepositoryByOwnerAndName returns the repository by given ownername and reponame.
  1701. func GetRepositoryByOwnerAndName(ownerName, repoName string) (*Repository, error) {
  1702. return getRepositoryByOwnerAndName(x, ownerName, repoName)
  1703. }
  1704. func getRepositoryByOwnerAndName(e Engine, ownerName, repoName string) (*Repository, error) {
  1705. var repo Repository
  1706. has, err := e.Table("repository").Select("repository.*").
  1707. Join("INNER", "`user`", "`user`.id = repository.owner_id").
  1708. Where("repository.lower_name = ?", strings.ToLower(repoName)).
  1709. And("`user`.lower_name = ?", strings.ToLower(ownerName)).
  1710. Get(&repo)
  1711. if err != nil {
  1712. return nil, err
  1713. } else if !has {
  1714. return nil, ErrRepoNotExist{0, 0, ownerName, repoName}
  1715. }
  1716. return &repo, nil
  1717. }
  1718. // GetRepositoryByName returns the repository by given name under user if exists.
  1719. func GetRepositoryByName(ownerID int64, name string) (*Repository, error) {
  1720. repo := &Repository{
  1721. OwnerID: ownerID,
  1722. LowerName: strings.ToLower(name),
  1723. }
  1724. has, err := x.Get(repo)
  1725. if err != nil {
  1726. return nil, err
  1727. } else if !has {
  1728. return nil, ErrRepoNotExist{0, ownerID, "", name}
  1729. }
  1730. return repo, err
  1731. }
  1732. func getRepositoryByID(e Engine, id int64) (*Repository, error) {
  1733. repo := new(Repository)
  1734. has, err := e.ID(id).Get(repo)
  1735. if err != nil {
  1736. return nil, err
  1737. } else if !has {
  1738. return nil, ErrRepoNotExist{id, 0, "", ""}
  1739. }
  1740. return repo, nil
  1741. }
  1742. // GetRepositoryByID returns the repository by given id if exists.
  1743. func GetRepositoryByID(id int64) (*Repository, error) {
  1744. return getRepositoryByID(x, id)
  1745. }
  1746. // GetRepositoriesMapByIDs returns the repositories by given id slice.
  1747. func GetRepositoriesMapByIDs(ids []int64) (map[int64]*Repository, error) {
  1748. var repos = make(map[int64]*Repository, len(ids))
  1749. return repos, x.In("id", ids).Find(&repos)
  1750. }
  1751. // GetUserRepositories returns a list of repositories of given user.
  1752. func GetUserRepositories(userID int64, private bool, page, pageSize int, orderBy string) ([]*Repository, error) {
  1753. if len(orderBy) == 0 {
  1754. orderBy = "updated_unix DESC"
  1755. }
  1756. sess := x.
  1757. Where("owner_id = ?", userID).
  1758. OrderBy(orderBy)
  1759. if !private {
  1760. sess.And("is_private=?", false)
  1761. }
  1762. if page <= 0 {
  1763. page = 1
  1764. }
  1765. sess.Limit(pageSize, (page-1)*pageSize)
  1766. repos := make([]*Repository, 0, pageSize)
  1767. return repos, sess.Find(&repos)
  1768. }
  1769. // GetUserMirrorRepositories returns a list of mirror repositories of given user.
  1770. func GetUserMirrorRepositories(userID int64) ([]*Repository, error) {
  1771. repos := make([]*Repository, 0, 10)
  1772. return repos, x.
  1773. Where("owner_id = ?", userID).
  1774. And("is_mirror = ?", true).
  1775. Find(&repos)
  1776. }
  1777. func getRepositoryCount(e Engine, u *User) (int64, error) {
  1778. return e.Count(&Repository{OwnerID: u.ID})
  1779. }
  1780. func getPublicRepositoryCount(e Engine, u *User) (int64, error) {
  1781. return e.Where("is_private = ?", false).Count(&Repository{OwnerID: u.ID})
  1782. }
  1783. func getPrivateRepositoryCount(e Engine, u *User) (int64, error) {
  1784. return e.Where("is_private = ?", true).Count(&Repository{OwnerID: u.ID})
  1785. }
  1786. // GetRepositoryCount returns the total number of repositories of user.
  1787. func GetRepositoryCount(u *User) (int64, error) {
  1788. return getRepositoryCount(x, u)
  1789. }
  1790. // GetPublicRepositoryCount returns the total number of public repositories of user.
  1791. func GetPublicRepositoryCount(u *User) (int64, error) {
  1792. return getPublicRepositoryCount(x, u)
  1793. }
  1794. // GetPrivateRepositoryCount returns the total number of private repositories of user.
  1795. func GetPrivateRepositoryCount(u *User) (int64, error) {
  1796. return getPrivateRepositoryCount(x, u)
  1797. }
  1798. // DeleteRepositoryArchives deletes all repositories' archives.
  1799. func DeleteRepositoryArchives() error {
  1800. return x.
  1801. Where("id > 0").
  1802. Iterate(new(Repository),
  1803. func(idx int, bean interface{}) error {
  1804. repo := bean.(*Repository)
  1805. return os.RemoveAll(filepath.Join(repo.RepoPath(), "archives"))
  1806. })
  1807. }
  1808. // DeleteOldRepositoryArchives deletes old repository archives.
  1809. func DeleteOldRepositoryArchives() {
  1810. log.Trace("Doing: ArchiveCleanup")
  1811. if err := x.Where("id > 0").Iterate(new(Repository), deleteOldRepositoryArchives); err != nil {
  1812. log.Error("ArchiveClean: %v", err)
  1813. }
  1814. }
  1815. func deleteOldRepositoryArchives(idx int, bean interface{}) error {
  1816. repo := bean.(*Repository)
  1817. basePath := filepath.Join(repo.RepoPath(), "archives")
  1818. for _, ty := range []string{"zip", "targz"} {
  1819. path := filepath.Join(basePath, ty)
  1820. file, err := os.Open(path)
  1821. if err != nil {
  1822. if !os.IsNotExist(err) {
  1823. log.Warn("Unable to open directory %s: %v", path, err)
  1824. return err
  1825. }
  1826. // If the directory doesn't exist, that's okay.
  1827. continue
  1828. }
  1829. files, err := file.Readdir(0)
  1830. file.Close()
  1831. if err != nil {
  1832. log.Warn("Unable to read directory %s: %v", path, err)
  1833. return err
  1834. }
  1835. minimumOldestTime := time.Now().Add(-setting.Cron.ArchiveCleanup.OlderThan)
  1836. for _, info := range files {
  1837. if info.ModTime().Before(minimumOldestTime) && !info.IsDir() {
  1838. toDelete := filepath.Join(path, info.Name())
  1839. // This is a best-effort purge, so we do not check error codes to confirm removal.
  1840. if err = os.Remove(toDelete); err != nil {
  1841. log.Trace("Unable to delete %s, but proceeding: %v", toDelete, err)
  1842. }
  1843. }
  1844. }
  1845. }
  1846. return nil
  1847. }
  1848. func gatherMissingRepoRecords() ([]*Repository, error) {
  1849. repos := make([]*Repository, 0, 10)
  1850. if err := x.
  1851. Where("id > 0").
  1852. Iterate(new(Repository),
  1853. func(idx int, bean interface{}) error {
  1854. repo := bean.(*Repository)
  1855. if !com.IsDir(repo.RepoPath()) {
  1856. repos = append(repos, repo)
  1857. }
  1858. return nil
  1859. }); err != nil {
  1860. if err2 := CreateRepositoryNotice(fmt.Sprintf("gatherMissingRepoRecords: %v", err)); err2 != nil {
  1861. return nil, fmt.Errorf("CreateRepositoryNotice: %v", err)
  1862. }
  1863. }
  1864. return repos, nil
  1865. }
  1866. // DeleteMissingRepositories deletes all repository records that lost Git files.
  1867. func DeleteMissingRepositories(doer *User) error {
  1868. repos, err := gatherMissingRepoRecords()
  1869. if err != nil {
  1870. return fmt.Errorf("gatherMissingRepoRecords: %v", err)
  1871. }
  1872. if len(repos) == 0 {
  1873. return nil
  1874. }
  1875. for _, repo := range repos {
  1876. log.Trace("Deleting %d/%d...", repo.OwnerID, repo.ID)
  1877. if err := DeleteRepository(doer, repo.OwnerID, repo.ID); err != nil {
  1878. if err2 := CreateRepositoryNotice(fmt.Sprintf("DeleteRepository [%d]: %v", repo.ID, err)); err2 != nil {
  1879. return fmt.Errorf("CreateRepositoryNotice: %v", err)
  1880. }
  1881. }
  1882. }
  1883. return nil
  1884. }
  1885. // ReinitMissingRepositories reinitializes all repository records that lost Git files.
  1886. func ReinitMissingRepositories() error {
  1887. repos, err := gatherMissingRepoRecords()
  1888. if err != nil {
  1889. return fmt.Errorf("gatherMissingRepoRecords: %v", err)
  1890. }
  1891. if len(repos) == 0 {
  1892. return nil
  1893. }
  1894. for _, repo := range repos {
  1895. log.Trace("Initializing %d/%d...", repo.OwnerID, repo.ID)
  1896. if err := git.InitRepository(repo.RepoPath(), true); err != nil {
  1897. if err2 := CreateRepositoryNotice(fmt.Sprintf("InitRepository [%d]: %v", repo.ID, err)); err2 != nil {
  1898. return fmt.Errorf("CreateRepositoryNotice: %v", err)
  1899. }
  1900. }
  1901. }
  1902. return nil
  1903. }
  1904. // SyncRepositoryHooks rewrites all repositories' pre-receive, update and post-receive hooks
  1905. // to make sure the binary and custom conf path are up-to-date.
  1906. func SyncRepositoryHooks() error {
  1907. return x.Cols("owner_id", "name").Where("id > 0").Iterate(new(Repository),
  1908. func(idx int, bean interface{}) error {
  1909. if err := createDelegateHooks(bean.(*Repository).RepoPath()); err != nil {
  1910. return fmt.Errorf("SyncRepositoryHook: %v", err)
  1911. }
  1912. if bean.(*Repository).HasWiki() {
  1913. if err := createDelegateHooks(bean.(*Repository).WikiPath()); err != nil {
  1914. return fmt.Errorf("SyncRepositoryHook: %v", err)
  1915. }
  1916. }
  1917. return nil
  1918. })
  1919. }
  1920. // GitFsck calls 'git fsck' to check repository health.
  1921. func GitFsck() {
  1922. log.Trace("Doing: GitFsck")
  1923. if err := x.
  1924. Where("id>0 AND is_fsck_enabled=?", true).BufferSize(setting.Database.IterateBufferSize).
  1925. Iterate(new(Repository),
  1926. func(idx int, bean interface{}) error {
  1927. repo := bean.(*Repository)
  1928. repoPath := repo.RepoPath()
  1929. log.Trace("Running health check on repository %s", repoPath)
  1930. if err := git.Fsck(repoPath, setting.Cron.RepoHealthCheck.Timeout, setting.Cron.RepoHealthCheck.Args...); err != nil {
  1931. desc := fmt.Sprintf("Failed to health check repository (%s): %v", repoPath, err)
  1932. log.Warn(desc)
  1933. if err = CreateRepositoryNotice(desc); err != nil {
  1934. log.Error("CreateRepositoryNotice: %v", err)
  1935. }
  1936. }
  1937. return nil
  1938. }); err != nil {
  1939. log.Error("GitFsck: %v", err)
  1940. }
  1941. log.Trace("Finished: GitFsck")
  1942. }
  1943. // GitGcRepos calls 'git gc' to remove unnecessary files and optimize the local repository
  1944. func GitGcRepos() error {
  1945. args := append([]string{"gc"}, setting.Git.GCArgs...)
  1946. return x.
  1947. Where("id > 0").BufferSize(setting.Database.IterateBufferSize).
  1948. Iterate(new(Repository),
  1949. func(idx int, bean interface{}) error {
  1950. repo := bean.(*Repository)
  1951. if err := repo.GetOwner(); err != nil {
  1952. return err
  1953. }
  1954. _, stderr, err := process.GetManager().ExecDir(
  1955. time.Duration(setting.Git.Timeout.GC)*time.Second,
  1956. RepoPath(repo.Owner.Name, repo.Name), "Repository garbage collection",
  1957. git.GitExecutable, args...)
  1958. if err != nil {
  1959. return fmt.Errorf("%v: %v", err, stderr)
  1960. }
  1961. return nil
  1962. })
  1963. }
  1964. type repoChecker struct {
  1965. querySQL, correctSQL string
  1966. desc string
  1967. }
  1968. func repoStatsCheck(checker *repoChecker) {
  1969. results, err := x.Query(checker.querySQL)
  1970. if err != nil {
  1971. log.Error("Select %s: %v", checker.desc, err)
  1972. return
  1973. }
  1974. for _, result := range results {
  1975. id := com.StrTo(result["id"]).MustInt64()
  1976. log.Trace("Updating %s: %d", checker.desc, id)
  1977. _, err = x.Exec(checker.correctSQL, id, id)
  1978. if err != nil {
  1979. log.Error("Update %s[%d]: %v", checker.desc, id, err)
  1980. }
  1981. }
  1982. }
  1983. // CheckRepoStats checks the repository stats
  1984. func CheckRepoStats() {
  1985. log.Trace("Doing: CheckRepoStats")
  1986. checkers := []*repoChecker{
  1987. // Repository.NumWatches
  1988. {
  1989. "SELECT repo.id FROM `repository` repo WHERE repo.num_watches!=(SELECT COUNT(*) FROM `watch` WHERE repo_id=repo.id)",
  1990. "UPDATE `repository` SET num_watches=(SELECT COUNT(*) FROM `watch` WHERE repo_id=?) WHERE id=?",
  1991. "repository count 'num_watches'",
  1992. },
  1993. // Repository.NumStars
  1994. {
  1995. "SELECT repo.id FROM `repository` repo WHERE repo.num_stars!=(SELECT COUNT(*) FROM `star` WHERE repo_id=repo.id)",
  1996. "UPDATE `repository` SET num_stars=(SELECT COUNT(*) FROM `star` WHERE repo_id=?) WHERE id=?",
  1997. "repository count 'num_stars'",
  1998. },
  1999. // Label.NumIssues
  2000. {
  2001. "SELECT label.id FROM `label` WHERE label.num_issues!=(SELECT COUNT(*) FROM `issue_label` WHERE label_id=label.id)",
  2002. "UPDATE `label` SET num_issues=(SELECT COUNT(*) FROM `issue_label` WHERE label_id=?) WHERE id=?",
  2003. "label count 'num_issues'",
  2004. },
  2005. // User.NumRepos
  2006. {
  2007. "SELECT `user`.id FROM `user` WHERE `user`.num_repos!=(SELECT COUNT(*) FROM `repository` WHERE owner_id=`user`.id)",
  2008. "UPDATE `user` SET num_repos=(SELECT COUNT(*) FROM `repository` WHERE owner_id=?) WHERE id=?",
  2009. "user count 'num_repos'",
  2010. },
  2011. // Issue.NumComments
  2012. {
  2013. "SELECT `issue`.id FROM `issue` WHERE `issue`.num_comments!=(SELECT COUNT(*) FROM `comment` WHERE issue_id=`issue`.id AND type=0)",
  2014. "UPDATE `issue` SET num_comments=(SELECT COUNT(*) FROM `comment` WHERE issue_id=? AND type=0) WHERE id=?",
  2015. "issue count 'num_comments'",
  2016. },
  2017. }
  2018. for i := range checkers {
  2019. repoStatsCheck(checkers[i])
  2020. }
  2021. // ***** START: Repository.NumClosedIssues *****
  2022. desc := "repository count 'num_closed_issues'"
  2023. 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)
  2024. if err != nil {
  2025. log.Error("Select %s: %v", desc, err)
  2026. } else {
  2027. for _, result := range results {
  2028. id := com.StrTo(result["id"]).MustInt64()
  2029. log.Trace("Updating %s: %d", desc, id)
  2030. _, 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)
  2031. if err != nil {
  2032. log.Error("Update %s[%d]: %v", desc, id, err)
  2033. }
  2034. }
  2035. }
  2036. // ***** END: Repository.NumClosedIssues *****
  2037. // ***** START: Repository.NumClosedPulls *****
  2038. desc = "repository count 'num_closed_pulls'"
  2039. 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)
  2040. if err != nil {
  2041. log.Error("Select %s: %v", desc, err)
  2042. } else {
  2043. for _, result := range results {
  2044. id := com.StrTo(result["id"]).MustInt64()
  2045. log.Trace("Updating %s: %d", desc, id)
  2046. _, 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)
  2047. if err != nil {
  2048. log.Error("Update %s[%d]: %v", desc, id, err)
  2049. }
  2050. }
  2051. }
  2052. // ***** END: Repository.NumClosedPulls *****
  2053. // FIXME: use checker when stop supporting old fork repo format.
  2054. // ***** START: Repository.NumForks *****
  2055. results, err = x.Query("SELECT repo.id FROM `repository` repo WHERE repo.num_forks!=(SELECT COUNT(*) FROM `repository` WHERE fork_id=repo.id)")
  2056. if err != nil {
  2057. log.Error("Select repository count 'num_forks': %v", err)
  2058. } else {
  2059. for _, result := range results {
  2060. id := com.StrTo(result["id"]).MustInt64()
  2061. log.Trace("Updating repository count 'num_forks': %d", id)
  2062. repo, err := GetRepositoryByID(id)
  2063. if err != nil {
  2064. log.Error("GetRepositoryByID[%d]: %v", id, err)
  2065. continue
  2066. }
  2067. rawResult, err := x.Query("SELECT COUNT(*) FROM `repository` WHERE fork_id=?", repo.ID)
  2068. if err != nil {
  2069. log.Error("Select count of forks[%d]: %v", repo.ID, err)
  2070. continue
  2071. }
  2072. repo.NumForks = int(parseCountResult(rawResult))
  2073. if err = UpdateRepository(repo, false); err != nil {
  2074. log.Error("UpdateRepository[%d]: %v", id, err)
  2075. continue
  2076. }
  2077. }
  2078. }
  2079. // ***** END: Repository.NumForks *****
  2080. }
  2081. // SetArchiveRepoState sets if a repo is archived
  2082. func (repo *Repository) SetArchiveRepoState(isArchived bool) (err error) {
  2083. repo.IsArchived = isArchived
  2084. _, err = x.Where("id = ?", repo.ID).Cols("is_archived").Update(repo)
  2085. return
  2086. }
  2087. // ___________ __
  2088. // \_ _____/__________| | __
  2089. // | __)/ _ \_ __ \ |/ /
  2090. // | \( <_> ) | \/ <
  2091. // \___ / \____/|__| |__|_ \
  2092. // \/ \/
  2093. // HasForkedRepo checks if given user has already forked a repository with given ID.
  2094. func HasForkedRepo(ownerID, repoID int64) (*Repository, bool) {
  2095. repo := new(Repository)
  2096. has, _ := x.
  2097. Where("owner_id=? AND fork_id=?", ownerID, repoID).
  2098. Get(repo)
  2099. return repo, has
  2100. }
  2101. // ForkRepository forks a repository
  2102. func ForkRepository(doer, u *User, oldRepo *Repository, name, desc string) (_ *Repository, err error) {
  2103. forkedRepo, err := oldRepo.GetUserFork(u.ID)
  2104. if err != nil {
  2105. return nil, err
  2106. }
  2107. if forkedRepo != nil {
  2108. return nil, ErrForkAlreadyExist{
  2109. Uname: u.Name,
  2110. RepoName: oldRepo.FullName(),
  2111. ForkName: forkedRepo.FullName(),
  2112. }
  2113. }
  2114. repo := &Repository{
  2115. OwnerID: u.ID,
  2116. Owner: u,
  2117. Name: name,
  2118. LowerName: strings.ToLower(name),
  2119. Description: desc,
  2120. DefaultBranch: oldRepo.DefaultBranch,
  2121. IsPrivate: oldRepo.IsPrivate,
  2122. IsEmpty: oldRepo.IsEmpty,
  2123. IsFork: true,
  2124. ForkID: oldRepo.ID,
  2125. }
  2126. sess := x.NewSession()
  2127. defer sess.Close()
  2128. if err = sess.Begin(); err != nil {
  2129. return nil, err
  2130. }
  2131. if err = createRepository(sess, doer, u, repo); err != nil {
  2132. return nil, err
  2133. }
  2134. if _, err = sess.Exec("UPDATE `repository` SET num_forks=num_forks+1 WHERE id=?", oldRepo.ID); err != nil {
  2135. return nil, err
  2136. }
  2137. repoPath := RepoPath(u.Name, repo.Name)
  2138. _, stderr, err := process.GetManager().ExecTimeout(10*time.Minute,
  2139. fmt.Sprintf("ForkRepository(git clone): %s/%s", u.Name, repo.Name),
  2140. git.GitExecutable, "clone", "--bare", oldRepo.repoPath(sess), repoPath)
  2141. if err != nil {
  2142. return nil, fmt.Errorf("git clone: %v", stderr)
  2143. }
  2144. _, stderr, err = process.GetManager().ExecDir(-1,
  2145. repoPath, fmt.Sprintf("ForkRepository(git update-server-info): %s", repoPath),
  2146. git.GitExecutable, "update-server-info")
  2147. if err != nil {
  2148. return nil, fmt.Errorf("git update-server-info: %v", stderr)
  2149. }
  2150. if err = createDelegateHooks(repoPath); err != nil {
  2151. return nil, fmt.Errorf("createDelegateHooks: %v", err)
  2152. }
  2153. //Commit repo to get Fork ID
  2154. err = sess.Commit()
  2155. if err != nil {
  2156. return nil, err
  2157. }
  2158. oldMode, _ := AccessLevel(doer, oldRepo)
  2159. mode, _ := AccessLevel(doer, repo)
  2160. if err = PrepareWebhooks(oldRepo, HookEventFork, &api.ForkPayload{
  2161. Forkee: oldRepo.APIFormat(oldMode),
  2162. Repo: repo.APIFormat(mode),
  2163. Sender: doer.APIFormat(),
  2164. }); err != nil {
  2165. log.Error("PrepareWebhooks [repo_id: %d]: %v", oldRepo.ID, err)
  2166. } else {
  2167. go HookQueue.Add(oldRepo.ID)
  2168. }
  2169. // Add to hook queue for created repo after session commit.
  2170. if u.IsOrganization() {
  2171. go HookQueue.Add(repo.ID)
  2172. }
  2173. if err = repo.UpdateSize(); err != nil {
  2174. log.Error("Failed to update size for repository: %v", err)
  2175. }
  2176. // Copy LFS meta objects in new session
  2177. sess2 := x.NewSession()
  2178. defer sess2.Close()
  2179. if err = sess2.Begin(); err != nil {
  2180. return nil, err
  2181. }
  2182. var lfsObjects []*LFSMetaObject
  2183. if err = sess2.Where("repository_id=?", oldRepo.ID).Find(&lfsObjects); err != nil {
  2184. return nil, err
  2185. }
  2186. for _, v := range lfsObjects {
  2187. v.ID = 0
  2188. v.RepositoryID = repo.ID
  2189. if _, err = sess2.Insert(v); err != nil {
  2190. return nil, err
  2191. }
  2192. }
  2193. return repo, sess2.Commit()
  2194. }
  2195. // GetForks returns all the forks of the repository
  2196. func (repo *Repository) GetForks() ([]*Repository, error) {
  2197. forks := make([]*Repository, 0, repo.NumForks)
  2198. return forks, x.Find(&forks, &Repository{ForkID: repo.ID})
  2199. }
  2200. // GetUserFork return user forked repository from this repository, if not forked return nil
  2201. func (repo *Repository) GetUserFork(userID int64) (*Repository, error) {
  2202. var forkedRepo Repository
  2203. has, err := x.Where("fork_id = ?", repo.ID).And("owner_id = ?", userID).Get(&forkedRepo)
  2204. if err != nil {
  2205. return nil, err
  2206. }
  2207. if !has {
  2208. return nil, nil
  2209. }
  2210. return &forkedRepo, nil
  2211. }
  2212. // CustomAvatarPath returns repository custom avatar file path.
  2213. func (repo *Repository) CustomAvatarPath() string {
  2214. // Avatar empty by default
  2215. if len(repo.Avatar) == 0 {
  2216. return ""
  2217. }
  2218. return filepath.Join(setting.RepositoryAvatarUploadPath, repo.Avatar)
  2219. }
  2220. // generateRandomAvatar generates a random avatar for repository.
  2221. func (repo *Repository) generateRandomAvatar(e Engine) error {
  2222. idToString := fmt.Sprintf("%d", repo.ID)
  2223. seed := idToString
  2224. img, err := avatar.RandomImage([]byte(seed))
  2225. if err != nil {
  2226. return fmt.Errorf("RandomImage: %v", err)
  2227. }
  2228. repo.Avatar = idToString
  2229. if err = os.MkdirAll(filepath.Dir(repo.CustomAvatarPath()), os.ModePerm); err != nil {
  2230. return fmt.Errorf("MkdirAll: %v", err)
  2231. }
  2232. fw, err := os.Create(repo.CustomAvatarPath())
  2233. if err != nil {
  2234. return fmt.Errorf("Create: %v", err)
  2235. }
  2236. defer fw.Close()
  2237. if err = png.Encode(fw, img); err != nil {
  2238. return fmt.Errorf("Encode: %v", err)
  2239. }
  2240. log.Info("New random avatar created for repository: %d", repo.ID)
  2241. if _, err := e.ID(repo.ID).Cols("avatar").NoAutoTime().Update(repo); err != nil {
  2242. return err
  2243. }
  2244. return nil
  2245. }
  2246. // RemoveRandomAvatars removes the randomly generated avatars that were created for repositories
  2247. func RemoveRandomAvatars() error {
  2248. return x.
  2249. Where("id > 0").BufferSize(setting.Database.IterateBufferSize).
  2250. Iterate(new(Repository),
  2251. func(idx int, bean interface{}) error {
  2252. repository := bean.(*Repository)
  2253. stringifiedID := strconv.FormatInt(repository.ID, 10)
  2254. if repository.Avatar == stringifiedID {
  2255. return repository.DeleteAvatar()
  2256. }
  2257. return nil
  2258. })
  2259. }
  2260. // RelAvatarLink returns a relative link to the repository's avatar.
  2261. func (repo *Repository) RelAvatarLink() string {
  2262. return repo.relAvatarLink(x)
  2263. }
  2264. func (repo *Repository) relAvatarLink(e Engine) string {
  2265. // If no avatar - path is empty
  2266. avatarPath := repo.CustomAvatarPath()
  2267. if len(avatarPath) == 0 || !com.IsFile(avatarPath) {
  2268. switch mode := setting.RepositoryAvatarFallback; mode {
  2269. case "image":
  2270. return setting.RepositoryAvatarFallbackImage
  2271. case "random":
  2272. if err := repo.generateRandomAvatar(e); err != nil {
  2273. log.Error("generateRandomAvatar: %v", err)
  2274. }
  2275. default:
  2276. // default behaviour: do not display avatar
  2277. return ""
  2278. }
  2279. }
  2280. return setting.AppSubURL + "/repo-avatars/" + repo.Avatar
  2281. }
  2282. // avatarLink returns user avatar absolute link.
  2283. func (repo *Repository) avatarLink(e Engine) string {
  2284. link := repo.relAvatarLink(e)
  2285. // link may be empty!
  2286. if len(link) > 0 {
  2287. if link[0] == '/' && link[1] != '/' {
  2288. return setting.AppURL + strings.TrimPrefix(link, setting.AppSubURL)[1:]
  2289. }
  2290. }
  2291. return link
  2292. }
  2293. // UploadAvatar saves custom avatar for repository.
  2294. // FIXME: split uploads to different subdirs in case we have massive number of repos.
  2295. func (repo *Repository) UploadAvatar(data []byte) error {
  2296. m, err := avatar.Prepare(data)
  2297. if err != nil {
  2298. return err
  2299. }
  2300. sess := x.NewSession()
  2301. defer sess.Close()
  2302. if err = sess.Begin(); err != nil {
  2303. return err
  2304. }
  2305. oldAvatarPath := repo.CustomAvatarPath()
  2306. // Users can upload the same image to other repo - prefix it with ID
  2307. // Then repo will be removed - only it avatar file will be removed
  2308. repo.Avatar = fmt.Sprintf("%d-%x", repo.ID, md5.Sum(data))
  2309. if _, err := sess.ID(repo.ID).Cols("avatar").Update(repo); err != nil {
  2310. return fmt.Errorf("UploadAvatar: Update repository avatar: %v", err)
  2311. }
  2312. if err := os.MkdirAll(setting.RepositoryAvatarUploadPath, os.ModePerm); err != nil {
  2313. return fmt.Errorf("UploadAvatar: Failed to create dir %s: %v", setting.RepositoryAvatarUploadPath, err)
  2314. }
  2315. fw, err := os.Create(repo.CustomAvatarPath())
  2316. if err != nil {
  2317. return fmt.Errorf("UploadAvatar: Create file: %v", err)
  2318. }
  2319. defer fw.Close()
  2320. if err = png.Encode(fw, *m); err != nil {
  2321. return fmt.Errorf("UploadAvatar: Encode png: %v", err)
  2322. }
  2323. if len(oldAvatarPath) > 0 && oldAvatarPath != repo.CustomAvatarPath() {
  2324. if err := os.Remove(oldAvatarPath); err != nil {
  2325. return fmt.Errorf("UploadAvatar: Failed to remove old repo avatar %s: %v", oldAvatarPath, err)
  2326. }
  2327. }
  2328. return sess.Commit()
  2329. }
  2330. // DeleteAvatar deletes the repos's custom avatar.
  2331. func (repo *Repository) DeleteAvatar() error {
  2332. // Avatar not exists
  2333. if len(repo.Avatar) == 0 {
  2334. return nil
  2335. }
  2336. avatarPath := repo.CustomAvatarPath()
  2337. log.Trace("DeleteAvatar[%d]: %s", repo.ID, avatarPath)
  2338. sess := x.NewSession()
  2339. defer sess.Close()
  2340. if err := sess.Begin(); err != nil {
  2341. return err
  2342. }
  2343. repo.Avatar = ""
  2344. if _, err := sess.ID(repo.ID).Cols("avatar").Update(repo); err != nil {
  2345. return fmt.Errorf("DeleteAvatar: Update repository avatar: %v", err)
  2346. }
  2347. if _, err := os.Stat(avatarPath); err == nil {
  2348. if err := os.Remove(avatarPath); err != nil {
  2349. return fmt.Errorf("DeleteAvatar: Failed to remove %s: %v", avatarPath, err)
  2350. }
  2351. } else {
  2352. // // Schrodinger: file may or may not exist. See err for details.
  2353. log.Trace("DeleteAvatar[%d]: %v", err)
  2354. }
  2355. return sess.Commit()
  2356. }
  2357. // GetOriginalURLHostname returns the hostname of a URL or the URL
  2358. func (repo *Repository) GetOriginalURLHostname() string {
  2359. u, err := url.Parse(repo.OriginalURL)
  2360. if err != nil {
  2361. return repo.OriginalURL
  2362. }
  2363. return u.Host
  2364. }