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

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