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