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 72 kB

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