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
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
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
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Copyright 2017 The Gitea Authors. All rights reserved.
  3. // Use of this source code is governed by a MIT-style
  4. // license that can be found in the LICENSE file.
  5. package models
  6. import (
  7. "bytes"
  8. "crypto/md5"
  9. "errors"
  10. "fmt"
  11. "html/template"
  12. // Needed for jpeg support
  13. _ "image/jpeg"
  14. "image/png"
  15. "io/ioutil"
  16. "net/url"
  17. "os"
  18. "path"
  19. "path/filepath"
  20. "sort"
  21. "strconv"
  22. "strings"
  23. "time"
  24. "code.gitea.io/gitea/modules/avatar"
  25. "code.gitea.io/gitea/modules/git"
  26. "code.gitea.io/gitea/modules/log"
  27. "code.gitea.io/gitea/modules/markup"
  28. "code.gitea.io/gitea/modules/options"
  29. "code.gitea.io/gitea/modules/process"
  30. "code.gitea.io/gitea/modules/setting"
  31. api "code.gitea.io/gitea/modules/structs"
  32. "code.gitea.io/gitea/modules/sync"
  33. "code.gitea.io/gitea/modules/util"
  34. "github.com/Unknwon/com"
  35. "github.com/go-xorm/xorm"
  36. ini "gopkg.in/ini.v1"
  37. "xorm.io/builder"
  38. )
  39. var repoWorkingPool = sync.NewExclusivePool()
  40. var (
  41. // ErrMirrorNotExist mirror does not exist error
  42. ErrMirrorNotExist = errors.New("Mirror does not exist")
  43. // ErrNameEmpty name is empty error
  44. ErrNameEmpty = errors.New("Name is empty")
  45. )
  46. var (
  47. // Gitignores contains the gitiginore files
  48. Gitignores []string
  49. // Licenses contains the license files
  50. Licenses []string
  51. // Readmes contains the readme files
  52. Readmes []string
  53. // LabelTemplates contains the label template files
  54. LabelTemplates []string
  55. // ItemsPerPage maximum items per page in forks, watchers and stars of a repo
  56. ItemsPerPage = 40
  57. )
  58. // loadRepoConfig loads the repository config
  59. func loadRepoConfig() {
  60. // Load .gitignore and license files and readme templates.
  61. types := []string{"gitignore", "license", "readme", "label"}
  62. typeFiles := make([][]string, 4)
  63. for i, t := range types {
  64. files, err := options.Dir(t)
  65. if err != nil {
  66. log.Fatal("Failed to get %s files: %v", t, err)
  67. }
  68. customPath := path.Join(setting.CustomPath, "options", t)
  69. if com.IsDir(customPath) {
  70. customFiles, err := com.StatDir(customPath)
  71. if err != nil {
  72. log.Fatal("Failed to get custom %s files: %v", t, err)
  73. }
  74. for _, f := range customFiles {
  75. if !com.IsSliceContainsStr(files, f) {
  76. files = append(files, f)
  77. }
  78. }
  79. }
  80. typeFiles[i] = files
  81. }
  82. Gitignores = typeFiles[0]
  83. Licenses = typeFiles[1]
  84. Readmes = typeFiles[2]
  85. LabelTemplates = typeFiles[3]
  86. sort.Strings(Gitignores)
  87. sort.Strings(Licenses)
  88. sort.Strings(Readmes)
  89. sort.Strings(LabelTemplates)
  90. // Filter out invalid names and promote preferred licenses.
  91. sortedLicenses := make([]string, 0, len(Licenses))
  92. for _, name := range setting.Repository.PreferredLicenses {
  93. if com.IsSliceContainsStr(Licenses, name) {
  94. sortedLicenses = append(sortedLicenses, name)
  95. }
  96. }
  97. for _, name := range Licenses {
  98. if !com.IsSliceContainsStr(setting.Repository.PreferredLicenses, name) {
  99. sortedLicenses = append(sortedLicenses, name)
  100. }
  101. }
  102. Licenses = sortedLicenses
  103. }
  104. // NewRepoContext creates a new repository context
  105. func NewRepoContext() {
  106. loadRepoConfig()
  107. RemoveAllWithNotice("Clean up repository temporary data", filepath.Join(setting.AppDataPath, "tmp"))
  108. }
  109. // Repository represents a git repository.
  110. type Repository struct {
  111. ID int64 `xorm:"pk autoincr"`
  112. OwnerID int64 `xorm:"UNIQUE(s)"`
  113. OwnerName string `xorm:"-"`
  114. Owner *User `xorm:"-"`
  115. LowerName string `xorm:"UNIQUE(s) INDEX NOT NULL"`
  116. Name string `xorm:"INDEX NOT NULL"`
  117. Description string
  118. Website string
  119. OriginalURL 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(e),
  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. // DescriptionHTML does special handles to description and return HTML string.
  641. func (repo *Repository) DescriptionHTML() template.HTML {
  642. desc, err := markup.RenderDescriptionHTML([]byte(repo.Description), repo.HTMLURL(), repo.ComposeMetas())
  643. if err != nil {
  644. log.Error("Failed to render description for %s (ID: %d): %v", repo.Name, repo.ID, err)
  645. return template.HTML(markup.Sanitize(repo.Description))
  646. }
  647. return template.HTML(markup.Sanitize(string(desc)))
  648. }
  649. // PatchPath returns corresponding patch file path of repository by given issue ID.
  650. func (repo *Repository) PatchPath(index int64) (string, error) {
  651. return repo.patchPath(x, index)
  652. }
  653. func (repo *Repository) patchPath(e Engine, index int64) (string, error) {
  654. if err := repo.getOwner(e); err != nil {
  655. return "", err
  656. }
  657. return filepath.Join(RepoPath(repo.Owner.Name, repo.Name), "pulls", com.ToStr(index)+".patch"), nil
  658. }
  659. // SavePatch saves patch data to corresponding location by given issue ID.
  660. func (repo *Repository) SavePatch(index int64, patch []byte) error {
  661. return repo.savePatch(x, index, patch)
  662. }
  663. func (repo *Repository) savePatch(e Engine, index int64, patch []byte) error {
  664. patchPath, err := repo.patchPath(e, index)
  665. if err != nil {
  666. return fmt.Errorf("PatchPath: %v", err)
  667. }
  668. dir := filepath.Dir(patchPath)
  669. if err := os.MkdirAll(dir, os.ModePerm); err != nil {
  670. return fmt.Errorf("Failed to create dir %s: %v", dir, err)
  671. }
  672. if err = ioutil.WriteFile(patchPath, patch, 0644); err != nil {
  673. return fmt.Errorf("WriteFile: %v", err)
  674. }
  675. return nil
  676. }
  677. func isRepositoryExist(e Engine, u *User, repoName string) (bool, error) {
  678. has, err := e.Get(&Repository{
  679. OwnerID: u.ID,
  680. LowerName: strings.ToLower(repoName),
  681. })
  682. return has && com.IsDir(RepoPath(u.Name, repoName)), err
  683. }
  684. // IsRepositoryExist returns true if the repository with given name under user has already existed.
  685. func IsRepositoryExist(u *User, repoName string) (bool, error) {
  686. return isRepositoryExist(x, u, repoName)
  687. }
  688. // CloneLink represents different types of clone URLs of repository.
  689. type CloneLink struct {
  690. SSH string
  691. HTTPS string
  692. Git string
  693. }
  694. // ComposeHTTPSCloneURL returns HTTPS clone URL based on given owner and repository name.
  695. func ComposeHTTPSCloneURL(owner, repo string) string {
  696. return fmt.Sprintf("%s%s/%s.git", setting.AppURL, url.PathEscape(owner), url.PathEscape(repo))
  697. }
  698. func (repo *Repository) cloneLink(e Engine, isWiki bool) *CloneLink {
  699. repoName := repo.Name
  700. if isWiki {
  701. repoName += ".wiki"
  702. }
  703. sshUser := setting.RunUser
  704. if setting.SSH.StartBuiltinServer {
  705. sshUser = setting.SSH.BuiltinServerUser
  706. }
  707. repo.Owner = repo.mustOwner(e)
  708. cl := new(CloneLink)
  709. if setting.SSH.Port != 22 {
  710. cl.SSH = fmt.Sprintf("ssh://%s@%s:%d/%s/%s.git", sshUser, setting.SSH.Domain, setting.SSH.Port, repo.Owner.Name, repoName)
  711. } else if setting.Repository.UseCompatSSHURI {
  712. cl.SSH = fmt.Sprintf("ssh://%s@%s/%s/%s.git", sshUser, setting.SSH.Domain, repo.Owner.Name, repoName)
  713. } else {
  714. cl.SSH = fmt.Sprintf("%s@%s:%s/%s.git", sshUser, setting.SSH.Domain, repo.Owner.Name, repoName)
  715. }
  716. cl.HTTPS = ComposeHTTPSCloneURL(repo.Owner.Name, repoName)
  717. return cl
  718. }
  719. // CloneLink returns clone URLs of repository.
  720. func (repo *Repository) CloneLink() (cl *CloneLink) {
  721. return repo.cloneLink(x, false)
  722. }
  723. // MigrateRepoOptions contains the repository migrate options
  724. type MigrateRepoOptions struct {
  725. Name string
  726. Description string
  727. OriginalURL string
  728. IsPrivate bool
  729. IsMirror bool
  730. RemoteAddr string
  731. Wiki bool // include wiki repository
  732. SyncReleasesWithTags bool // sync releases from tags
  733. }
  734. /*
  735. GitHub, GitLab, Gogs: *.wiki.git
  736. BitBucket: *.git/wiki
  737. */
  738. var commonWikiURLSuffixes = []string{".wiki.git", ".git/wiki"}
  739. // wikiRemoteURL returns accessible repository URL for wiki if exists.
  740. // Otherwise, it returns an empty string.
  741. func wikiRemoteURL(remote string) string {
  742. remote = strings.TrimSuffix(remote, ".git")
  743. for _, suffix := range commonWikiURLSuffixes {
  744. wikiURL := remote + suffix
  745. if git.IsRepoURLAccessible(wikiURL) {
  746. return wikiURL
  747. }
  748. }
  749. return ""
  750. }
  751. // MigrateRepository migrates an existing repository from other project hosting.
  752. func MigrateRepository(doer, u *User, opts MigrateRepoOptions) (*Repository, error) {
  753. repo, err := CreateRepository(doer, u, CreateRepoOptions{
  754. Name: opts.Name,
  755. Description: opts.Description,
  756. OriginalURL: opts.OriginalURL,
  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. gitRepo, err := git.OpenRepository(repoPath)
  805. if err != nil {
  806. return repo, fmt.Errorf("OpenRepository: %v", err)
  807. }
  808. repo.IsEmpty, err = gitRepo.IsEmpty()
  809. if err != nil {
  810. return repo, fmt.Errorf("git.IsEmpty: %v", err)
  811. }
  812. if opts.SyncReleasesWithTags && !repo.IsEmpty {
  813. // Try to get HEAD branch and set it as default branch.
  814. headBranch, err := gitRepo.GetHEADBranch()
  815. if err != nil {
  816. return repo, fmt.Errorf("GetHEADBranch: %v", err)
  817. }
  818. if headBranch != nil {
  819. repo.DefaultBranch = headBranch.Name
  820. }
  821. if err = SyncReleasesWithTags(repo, gitRepo); err != nil {
  822. log.Error("Failed to synchronize tags to releases for repository: %v", err)
  823. }
  824. }
  825. if err = repo.UpdateSize(); err != nil {
  826. log.Error("Failed to update size for repository: %v", err)
  827. }
  828. if opts.IsMirror {
  829. if _, err = x.InsertOne(&Mirror{
  830. RepoID: repo.ID,
  831. Interval: setting.Mirror.DefaultInterval,
  832. EnablePrune: true,
  833. NextUpdateUnix: util.TimeStampNow().AddDuration(setting.Mirror.DefaultInterval),
  834. }); err != nil {
  835. return repo, fmt.Errorf("InsertOne: %v", err)
  836. }
  837. repo.IsMirror = true
  838. err = UpdateRepository(repo, false)
  839. } else {
  840. repo, err = CleanUpMigrateInfo(repo)
  841. }
  842. if err != nil && !repo.IsEmpty {
  843. UpdateRepoIndexer(repo)
  844. }
  845. return repo, err
  846. }
  847. // cleanUpMigrateGitConfig removes mirror info which prevents "push --all".
  848. // This also removes possible user credentials.
  849. func cleanUpMigrateGitConfig(configPath string) error {
  850. cfg, err := ini.Load(configPath)
  851. if err != nil {
  852. return fmt.Errorf("open config file: %v", err)
  853. }
  854. cfg.DeleteSection("remote \"origin\"")
  855. if err = cfg.SaveToIndent(configPath, "\t"); err != nil {
  856. return fmt.Errorf("save config file: %v", err)
  857. }
  858. return nil
  859. }
  860. // createDelegateHooks creates all the hooks scripts for the repo
  861. func createDelegateHooks(repoPath string) (err error) {
  862. var (
  863. hookNames = []string{"pre-receive", "update", "post-receive"}
  864. hookTpls = []string{
  865. 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),
  866. 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),
  867. 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),
  868. }
  869. giteaHookTpls = []string{
  870. fmt.Sprintf("#!/usr/bin/env %s\n\"%s\" hook --config='%s' pre-receive\n", setting.ScriptType, setting.AppPath, setting.CustomConf),
  871. fmt.Sprintf("#!/usr/bin/env %s\n\"%s\" hook --config='%s' update $1 $2 $3\n", setting.ScriptType, setting.AppPath, setting.CustomConf),
  872. fmt.Sprintf("#!/usr/bin/env %s\n\"%s\" hook --config='%s' post-receive\n", setting.ScriptType, setting.AppPath, setting.CustomConf),
  873. }
  874. )
  875. hookDir := filepath.Join(repoPath, "hooks")
  876. for i, hookName := range hookNames {
  877. oldHookPath := filepath.Join(hookDir, hookName)
  878. newHookPath := filepath.Join(hookDir, hookName+".d", "gitea")
  879. if err := os.MkdirAll(filepath.Join(hookDir, hookName+".d"), os.ModePerm); err != nil {
  880. return fmt.Errorf("create hooks dir '%s': %v", filepath.Join(hookDir, hookName+".d"), err)
  881. }
  882. // WARNING: This will override all old server-side hooks
  883. if err = ioutil.WriteFile(oldHookPath, []byte(hookTpls[i]), 0777); err != nil {
  884. return fmt.Errorf("write old hook file '%s': %v", oldHookPath, err)
  885. }
  886. if err = ioutil.WriteFile(newHookPath, []byte(giteaHookTpls[i]), 0777); err != nil {
  887. return fmt.Errorf("write new hook file '%s': %v", newHookPath, err)
  888. }
  889. }
  890. return nil
  891. }
  892. // CleanUpMigrateInfo finishes migrating repository and/or wiki with things that don't need to be done for mirrors.
  893. func CleanUpMigrateInfo(repo *Repository) (*Repository, error) {
  894. repoPath := repo.RepoPath()
  895. if err := createDelegateHooks(repoPath); err != nil {
  896. return repo, fmt.Errorf("createDelegateHooks: %v", err)
  897. }
  898. if repo.HasWiki() {
  899. if err := createDelegateHooks(repo.WikiPath()); err != nil {
  900. return repo, fmt.Errorf("createDelegateHooks.(wiki): %v", err)
  901. }
  902. }
  903. _, err := git.NewCommand("remote", "remove", "origin").RunInDir(repoPath)
  904. if err != nil && !strings.HasPrefix(err.Error(), "exit status 128 - fatal: No such remote ") {
  905. return repo, fmt.Errorf("CleanUpMigrateInfo: %v", err)
  906. }
  907. if repo.HasWiki() {
  908. if err := cleanUpMigrateGitConfig(path.Join(repo.WikiPath(), "config")); err != nil {
  909. return repo, fmt.Errorf("cleanUpMigrateGitConfig (wiki): %v", err)
  910. }
  911. }
  912. return repo, UpdateRepository(repo, false)
  913. }
  914. // initRepoCommit temporarily changes with work directory.
  915. func initRepoCommit(tmpPath string, sig *git.Signature) (err error) {
  916. var stderr string
  917. if _, stderr, err = process.GetManager().ExecDir(-1,
  918. tmpPath, fmt.Sprintf("initRepoCommit (git add): %s", tmpPath),
  919. git.GitExecutable, "add", "--all"); err != nil {
  920. return fmt.Errorf("git add: %s", stderr)
  921. }
  922. if _, stderr, err = process.GetManager().ExecDir(-1,
  923. tmpPath, fmt.Sprintf("initRepoCommit (git commit): %s", tmpPath),
  924. git.GitExecutable, "commit", fmt.Sprintf("--author='%s <%s>'", sig.Name, sig.Email),
  925. "-m", "Initial commit"); err != nil {
  926. return fmt.Errorf("git commit: %s", stderr)
  927. }
  928. if _, stderr, err = process.GetManager().ExecDir(-1,
  929. tmpPath, fmt.Sprintf("initRepoCommit (git push): %s", tmpPath),
  930. git.GitExecutable, "push", "origin", "master"); err != nil {
  931. return fmt.Errorf("git push: %s", stderr)
  932. }
  933. return nil
  934. }
  935. // CreateRepoOptions contains the create repository options
  936. type CreateRepoOptions struct {
  937. Name string
  938. Description string
  939. OriginalURL string
  940. Gitignores string
  941. License string
  942. Readme string
  943. IsPrivate bool
  944. IsMirror bool
  945. AutoInit bool
  946. }
  947. func getRepoInitFile(tp, name string) ([]byte, error) {
  948. cleanedName := strings.TrimLeft(path.Clean("/"+name), "/")
  949. relPath := path.Join("options", tp, cleanedName)
  950. // Use custom file when available.
  951. customPath := path.Join(setting.CustomPath, relPath)
  952. if com.IsFile(customPath) {
  953. return ioutil.ReadFile(customPath)
  954. }
  955. switch tp {
  956. case "readme":
  957. return options.Readme(cleanedName)
  958. case "gitignore":
  959. return options.Gitignore(cleanedName)
  960. case "license":
  961. return options.License(cleanedName)
  962. case "label":
  963. return options.Labels(cleanedName)
  964. default:
  965. return []byte{}, fmt.Errorf("Invalid init file type")
  966. }
  967. }
  968. func prepareRepoCommit(e Engine, repo *Repository, tmpDir, repoPath string, opts CreateRepoOptions) error {
  969. // Clone to temporary path and do the init commit.
  970. _, stderr, err := process.GetManager().Exec(
  971. fmt.Sprintf("initRepository(git clone): %s", repoPath),
  972. git.GitExecutable, "clone", repoPath, tmpDir,
  973. )
  974. if err != nil {
  975. return fmt.Errorf("git clone: %v - %s", err, stderr)
  976. }
  977. // README
  978. data, err := getRepoInitFile("readme", opts.Readme)
  979. if err != nil {
  980. return fmt.Errorf("getRepoInitFile[%s]: %v", opts.Readme, err)
  981. }
  982. cloneLink := repo.cloneLink(e, false)
  983. match := map[string]string{
  984. "Name": repo.Name,
  985. "Description": repo.Description,
  986. "CloneURL.SSH": cloneLink.SSH,
  987. "CloneURL.HTTPS": cloneLink.HTTPS,
  988. }
  989. if err = ioutil.WriteFile(filepath.Join(tmpDir, "README.md"),
  990. []byte(com.Expand(string(data), match)), 0644); err != nil {
  991. return fmt.Errorf("write README.md: %v", err)
  992. }
  993. // .gitignore
  994. if len(opts.Gitignores) > 0 {
  995. var buf bytes.Buffer
  996. names := strings.Split(opts.Gitignores, ",")
  997. for _, name := range names {
  998. data, err = getRepoInitFile("gitignore", name)
  999. if err != nil {
  1000. return fmt.Errorf("getRepoInitFile[%s]: %v", name, err)
  1001. }
  1002. buf.WriteString("# ---> " + name + "\n")
  1003. buf.Write(data)
  1004. buf.WriteString("\n")
  1005. }
  1006. if buf.Len() > 0 {
  1007. if err = ioutil.WriteFile(filepath.Join(tmpDir, ".gitignore"), buf.Bytes(), 0644); err != nil {
  1008. return fmt.Errorf("write .gitignore: %v", err)
  1009. }
  1010. }
  1011. }
  1012. // LICENSE
  1013. if len(opts.License) > 0 {
  1014. data, err = getRepoInitFile("license", opts.License)
  1015. if err != nil {
  1016. return fmt.Errorf("getRepoInitFile[%s]: %v", opts.License, err)
  1017. }
  1018. if err = ioutil.WriteFile(filepath.Join(tmpDir, "LICENSE"), data, 0644); err != nil {
  1019. return fmt.Errorf("write LICENSE: %v", err)
  1020. }
  1021. }
  1022. return nil
  1023. }
  1024. // InitRepository initializes README and .gitignore if needed.
  1025. func initRepository(e Engine, repoPath string, u *User, repo *Repository, opts CreateRepoOptions) (err error) {
  1026. // Somehow the directory could exist.
  1027. if com.IsExist(repoPath) {
  1028. return fmt.Errorf("initRepository: path already exists: %s", repoPath)
  1029. }
  1030. // Init git bare new repository.
  1031. if err = git.InitRepository(repoPath, true); err != nil {
  1032. return fmt.Errorf("InitRepository: %v", err)
  1033. } else if err = createDelegateHooks(repoPath); err != nil {
  1034. return fmt.Errorf("createDelegateHooks: %v", err)
  1035. }
  1036. tmpDir := filepath.Join(os.TempDir(), "gitea-"+repo.Name+"-"+com.ToStr(time.Now().Nanosecond()))
  1037. // Initialize repository according to user's choice.
  1038. if opts.AutoInit {
  1039. if err := os.MkdirAll(tmpDir, os.ModePerm); err != nil {
  1040. return fmt.Errorf("Failed to create dir %s: %v", tmpDir, err)
  1041. }
  1042. defer os.RemoveAll(tmpDir)
  1043. if err = prepareRepoCommit(e, repo, tmpDir, repoPath, opts); err != nil {
  1044. return fmt.Errorf("prepareRepoCommit: %v", err)
  1045. }
  1046. // Apply changes and commit.
  1047. if err = initRepoCommit(tmpDir, u.NewGitSig()); err != nil {
  1048. return fmt.Errorf("initRepoCommit: %v", err)
  1049. }
  1050. }
  1051. // Re-fetch the repository from database before updating it (else it would
  1052. // override changes that were done earlier with sql)
  1053. if repo, err = getRepositoryByID(e, repo.ID); err != nil {
  1054. return fmt.Errorf("getRepositoryByID: %v", err)
  1055. }
  1056. if !opts.AutoInit {
  1057. repo.IsEmpty = true
  1058. }
  1059. repo.DefaultBranch = "master"
  1060. if err = updateRepository(e, repo, false); err != nil {
  1061. return fmt.Errorf("updateRepository: %v", err)
  1062. }
  1063. return nil
  1064. }
  1065. var (
  1066. reservedRepoNames = []string{".", ".."}
  1067. reservedRepoPatterns = []string{"*.git", "*.wiki"}
  1068. )
  1069. // IsUsableRepoName returns true when repository is usable
  1070. func IsUsableRepoName(name string) error {
  1071. return isUsableName(reservedRepoNames, reservedRepoPatterns, name)
  1072. }
  1073. func createRepository(e *xorm.Session, doer, u *User, repo *Repository) (err error) {
  1074. if err = IsUsableRepoName(repo.Name); err != nil {
  1075. return err
  1076. }
  1077. has, err := isRepositoryExist(e, u, repo.Name)
  1078. if err != nil {
  1079. return fmt.Errorf("IsRepositoryExist: %v", err)
  1080. } else if has {
  1081. return ErrRepoAlreadyExist{u.Name, repo.Name}
  1082. }
  1083. if _, err = e.Insert(repo); err != nil {
  1084. return err
  1085. }
  1086. if err = deleteRepoRedirect(e, u.ID, repo.Name); err != nil {
  1087. return err
  1088. }
  1089. // insert units for repo
  1090. var units = make([]RepoUnit, 0, len(DefaultRepoUnits))
  1091. for _, tp := range DefaultRepoUnits {
  1092. if tp == UnitTypeIssues {
  1093. units = append(units, RepoUnit{
  1094. RepoID: repo.ID,
  1095. Type: tp,
  1096. Config: &IssuesConfig{
  1097. EnableTimetracker: setting.Service.DefaultEnableTimetracking,
  1098. AllowOnlyContributorsToTrackTime: setting.Service.DefaultAllowOnlyContributorsToTrackTime,
  1099. EnableDependencies: setting.Service.DefaultEnableDependencies,
  1100. },
  1101. })
  1102. } else if tp == UnitTypePullRequests {
  1103. units = append(units, RepoUnit{
  1104. RepoID: repo.ID,
  1105. Type: tp,
  1106. Config: &PullRequestsConfig{AllowMerge: true, AllowRebase: true, AllowRebaseMerge: true, AllowSquash: true},
  1107. })
  1108. } else {
  1109. units = append(units, RepoUnit{
  1110. RepoID: repo.ID,
  1111. Type: tp,
  1112. })
  1113. }
  1114. }
  1115. if _, err = e.Insert(&units); err != nil {
  1116. return err
  1117. }
  1118. u.NumRepos++
  1119. // Remember visibility preference.
  1120. u.LastRepoVisibility = repo.IsPrivate
  1121. if err = updateUser(e, u); err != nil {
  1122. return fmt.Errorf("updateUser: %v", err)
  1123. }
  1124. // Give access to all members in owner team.
  1125. if u.IsOrganization() {
  1126. t, err := u.getOwnerTeam(e)
  1127. if err != nil {
  1128. return fmt.Errorf("getOwnerTeam: %v", err)
  1129. } else if err = t.addRepository(e, repo); err != nil {
  1130. return fmt.Errorf("addRepository: %v", err)
  1131. } else if err = prepareWebhooks(e, repo, HookEventRepository, &api.RepositoryPayload{
  1132. Action: api.HookRepoCreated,
  1133. Repository: repo.innerAPIFormat(e, AccessModeOwner, false),
  1134. Organization: u.APIFormat(),
  1135. Sender: doer.APIFormat(),
  1136. }); err != nil {
  1137. return fmt.Errorf("prepareWebhooks: %v", err)
  1138. }
  1139. go HookQueue.Add(repo.ID)
  1140. } else if err = repo.recalculateAccesses(e); err != nil {
  1141. // Organization automatically called this in addRepository method.
  1142. return fmt.Errorf("recalculateAccesses: %v", err)
  1143. }
  1144. if setting.Service.AutoWatchNewRepos {
  1145. if err = watchRepo(e, doer.ID, repo.ID, true); err != nil {
  1146. return fmt.Errorf("watchRepo: %v", err)
  1147. }
  1148. }
  1149. if err = newRepoAction(e, doer, repo); err != nil {
  1150. return fmt.Errorf("newRepoAction: %v", err)
  1151. }
  1152. if err = copyDefaultWebhooksToRepo(e, repo.ID); err != nil {
  1153. return fmt.Errorf("copyDefaultWebhooksToRepo: %v", err)
  1154. }
  1155. return nil
  1156. }
  1157. // CreateRepository creates a repository for the user/organization.
  1158. func CreateRepository(doer, u *User, opts CreateRepoOptions) (_ *Repository, err error) {
  1159. if !doer.IsAdmin && !u.CanCreateRepo() {
  1160. return nil, ErrReachLimitOfRepo{u.MaxRepoCreation}
  1161. }
  1162. repo := &Repository{
  1163. OwnerID: u.ID,
  1164. Owner: u,
  1165. Name: opts.Name,
  1166. LowerName: strings.ToLower(opts.Name),
  1167. Description: opts.Description,
  1168. OriginalURL: opts.OriginalURL,
  1169. IsPrivate: opts.IsPrivate,
  1170. IsFsckEnabled: !opts.IsMirror,
  1171. CloseIssuesViaCommitInAnyBranch: setting.Repository.DefaultCloseIssuesViaCommitsInAnyBranch,
  1172. }
  1173. sess := x.NewSession()
  1174. defer sess.Close()
  1175. if err = sess.Begin(); err != nil {
  1176. return nil, err
  1177. }
  1178. if err = createRepository(sess, doer, u, repo); err != nil {
  1179. return nil, err
  1180. }
  1181. // No need for init mirror.
  1182. if !opts.IsMirror {
  1183. repoPath := RepoPath(u.Name, repo.Name)
  1184. if err = initRepository(sess, repoPath, u, repo, opts); err != nil {
  1185. if err2 := os.RemoveAll(repoPath); err2 != nil {
  1186. log.Error("initRepository: %v", err)
  1187. return nil, fmt.Errorf(
  1188. "delete repo directory %s/%s failed(2): %v", u.Name, repo.Name, err2)
  1189. }
  1190. return nil, fmt.Errorf("initRepository: %v", err)
  1191. }
  1192. _, stderr, err := process.GetManager().ExecDir(-1,
  1193. repoPath, fmt.Sprintf("CreateRepository(git update-server-info): %s", repoPath),
  1194. git.GitExecutable, "update-server-info")
  1195. if err != nil {
  1196. return nil, errors.New("CreateRepository(git update-server-info): " + stderr)
  1197. }
  1198. }
  1199. return repo, sess.Commit()
  1200. }
  1201. func countRepositories(userID int64, private bool) int64 {
  1202. sess := x.Where("id > 0")
  1203. if userID > 0 {
  1204. sess.And("owner_id = ?", userID)
  1205. }
  1206. if !private {
  1207. sess.And("is_private=?", false)
  1208. }
  1209. count, err := sess.Count(new(Repository))
  1210. if err != nil {
  1211. log.Error("countRepositories: %v", err)
  1212. }
  1213. return count
  1214. }
  1215. // CountRepositories returns number of repositories.
  1216. // Argument private only takes effect when it is false,
  1217. // set it true to count all repositories.
  1218. func CountRepositories(private bool) int64 {
  1219. return countRepositories(-1, private)
  1220. }
  1221. // CountUserRepositories returns number of repositories user owns.
  1222. // Argument private only takes effect when it is false,
  1223. // set it true to count all repositories.
  1224. func CountUserRepositories(userID int64, private bool) int64 {
  1225. return countRepositories(userID, private)
  1226. }
  1227. // RepoPath returns repository path by given user and repository name.
  1228. func RepoPath(userName, repoName string) string {
  1229. return filepath.Join(UserPath(userName), strings.ToLower(repoName)+".git")
  1230. }
  1231. // TransferOwnership transfers all corresponding setting from old user to new one.
  1232. func TransferOwnership(doer *User, newOwnerName string, repo *Repository) error {
  1233. newOwner, err := GetUserByName(newOwnerName)
  1234. if err != nil {
  1235. return fmt.Errorf("get new owner '%s': %v", newOwnerName, err)
  1236. }
  1237. // Check if new owner has repository with same name.
  1238. has, err := IsRepositoryExist(newOwner, repo.Name)
  1239. if err != nil {
  1240. return fmt.Errorf("IsRepositoryExist: %v", err)
  1241. } else if has {
  1242. return ErrRepoAlreadyExist{newOwnerName, repo.Name}
  1243. }
  1244. sess := x.NewSession()
  1245. defer sess.Close()
  1246. if err = sess.Begin(); err != nil {
  1247. return fmt.Errorf("sess.Begin: %v", err)
  1248. }
  1249. owner := repo.Owner
  1250. // Note: we have to set value here to make sure recalculate accesses is based on
  1251. // new owner.
  1252. repo.OwnerID = newOwner.ID
  1253. repo.Owner = newOwner
  1254. // Update repository.
  1255. if _, err := sess.ID(repo.ID).Update(repo); err != nil {
  1256. return fmt.Errorf("update owner: %v", err)
  1257. }
  1258. // Remove redundant collaborators.
  1259. collaborators, err := repo.getCollaborators(sess)
  1260. if err != nil {
  1261. return fmt.Errorf("getCollaborators: %v", err)
  1262. }
  1263. // Dummy object.
  1264. collaboration := &Collaboration{RepoID: repo.ID}
  1265. for _, c := range collaborators {
  1266. if c.ID != newOwner.ID {
  1267. isMember, err := isOrganizationMember(sess, newOwner.ID, c.ID)
  1268. if err != nil {
  1269. return fmt.Errorf("IsOrgMember: %v", err)
  1270. } else if !isMember {
  1271. continue
  1272. }
  1273. }
  1274. collaboration.UserID = c.ID
  1275. if _, err = sess.Delete(collaboration); err != nil {
  1276. return fmt.Errorf("remove collaborator '%d': %v", c.ID, err)
  1277. }
  1278. }
  1279. // Remove old team-repository relations.
  1280. if owner.IsOrganization() {
  1281. if err = owner.removeOrgRepo(sess, repo.ID); err != nil {
  1282. return fmt.Errorf("removeOrgRepo: %v", err)
  1283. }
  1284. }
  1285. if newOwner.IsOrganization() {
  1286. t, err := newOwner.getOwnerTeam(sess)
  1287. if err != nil {
  1288. return fmt.Errorf("getOwnerTeam: %v", err)
  1289. } else if err = t.addRepository(sess, repo); err != nil {
  1290. return fmt.Errorf("add to owner team: %v", err)
  1291. }
  1292. } else if err = repo.recalculateAccesses(sess); err != nil {
  1293. // Organization called this in addRepository method.
  1294. return fmt.Errorf("recalculateAccesses: %v", err)
  1295. }
  1296. // Update repository count.
  1297. if _, err = sess.Exec("UPDATE `user` SET num_repos=num_repos+1 WHERE id=?", newOwner.ID); err != nil {
  1298. return fmt.Errorf("increase new owner repository count: %v", err)
  1299. } else if _, err = sess.Exec("UPDATE `user` SET num_repos=num_repos-1 WHERE id=?", owner.ID); err != nil {
  1300. return fmt.Errorf("decrease old owner repository count: %v", err)
  1301. }
  1302. if err = watchRepo(sess, doer.ID, repo.ID, true); err != nil {
  1303. return fmt.Errorf("watchRepo: %v", err)
  1304. } else if err = transferRepoAction(sess, doer, owner, repo); err != nil {
  1305. return fmt.Errorf("transferRepoAction: %v", err)
  1306. }
  1307. // Rename remote repository to new path and delete local copy.
  1308. dir := UserPath(newOwner.Name)
  1309. if err := os.MkdirAll(dir, os.ModePerm); err != nil {
  1310. return fmt.Errorf("Failed to create dir %s: %v", dir, err)
  1311. }
  1312. if err = os.Rename(RepoPath(owner.Name, repo.Name), RepoPath(newOwner.Name, repo.Name)); err != nil {
  1313. return fmt.Errorf("rename repository directory: %v", err)
  1314. }
  1315. // Rename remote wiki repository to new path and delete local copy.
  1316. wikiPath := WikiPath(owner.Name, repo.Name)
  1317. if com.IsExist(wikiPath) {
  1318. if err = os.Rename(wikiPath, WikiPath(newOwner.Name, repo.Name)); err != nil {
  1319. return fmt.Errorf("rename repository wiki: %v", err)
  1320. }
  1321. }
  1322. // If there was previously a redirect at this location, remove it.
  1323. if err = deleteRepoRedirect(sess, newOwner.ID, repo.Name); err != nil {
  1324. return fmt.Errorf("delete repo redirect: %v", err)
  1325. }
  1326. return sess.Commit()
  1327. }
  1328. // ChangeRepositoryName changes all corresponding setting from old repository name to new one.
  1329. func ChangeRepositoryName(u *User, oldRepoName, newRepoName string) (err error) {
  1330. oldRepoName = strings.ToLower(oldRepoName)
  1331. newRepoName = strings.ToLower(newRepoName)
  1332. if err = IsUsableRepoName(newRepoName); err != nil {
  1333. return err
  1334. }
  1335. has, err := IsRepositoryExist(u, newRepoName)
  1336. if err != nil {
  1337. return fmt.Errorf("IsRepositoryExist: %v", err)
  1338. } else if has {
  1339. return ErrRepoAlreadyExist{u.Name, newRepoName}
  1340. }
  1341. repo, err := GetRepositoryByName(u.ID, oldRepoName)
  1342. if err != nil {
  1343. return fmt.Errorf("GetRepositoryByName: %v", err)
  1344. }
  1345. // Change repository directory name. We must lock the local copy of the
  1346. // repo so that we can atomically rename the repo path and updates the
  1347. // local copy's origin accordingly.
  1348. repoWorkingPool.CheckIn(com.ToStr(repo.ID))
  1349. defer repoWorkingPool.CheckOut(com.ToStr(repo.ID))
  1350. newRepoPath := RepoPath(u.Name, newRepoName)
  1351. if err = os.Rename(repo.RepoPath(), newRepoPath); err != nil {
  1352. return fmt.Errorf("rename repository directory: %v", err)
  1353. }
  1354. wikiPath := repo.WikiPath()
  1355. if com.IsExist(wikiPath) {
  1356. if err = os.Rename(wikiPath, WikiPath(u.Name, newRepoName)); err != nil {
  1357. return fmt.Errorf("rename repository wiki: %v", err)
  1358. }
  1359. }
  1360. sess := x.NewSession()
  1361. defer sess.Close()
  1362. if err = sess.Begin(); err != nil {
  1363. return fmt.Errorf("sess.Begin: %v", err)
  1364. }
  1365. // If there was previously a redirect at this location, remove it.
  1366. if err = deleteRepoRedirect(sess, u.ID, newRepoName); err != nil {
  1367. return fmt.Errorf("delete repo redirect: %v", err)
  1368. }
  1369. return sess.Commit()
  1370. }
  1371. func getRepositoriesByForkID(e Engine, forkID int64) ([]*Repository, error) {
  1372. repos := make([]*Repository, 0, 10)
  1373. return repos, e.
  1374. Where("fork_id=?", forkID).
  1375. Find(&repos)
  1376. }
  1377. // GetRepositoriesByForkID returns all repositories with given fork ID.
  1378. func GetRepositoriesByForkID(forkID int64) ([]*Repository, error) {
  1379. return getRepositoriesByForkID(x, forkID)
  1380. }
  1381. func updateRepository(e Engine, repo *Repository, visibilityChanged bool) (err error) {
  1382. repo.LowerName = strings.ToLower(repo.Name)
  1383. if len(repo.Description) > 255 {
  1384. repo.Description = repo.Description[:255]
  1385. }
  1386. if len(repo.Website) > 255 {
  1387. repo.Website = repo.Website[:255]
  1388. }
  1389. if _, err = e.ID(repo.ID).AllCols().Update(repo); err != nil {
  1390. return fmt.Errorf("update: %v", err)
  1391. }
  1392. if visibilityChanged {
  1393. if err = repo.getOwner(e); err != nil {
  1394. return fmt.Errorf("getOwner: %v", err)
  1395. }
  1396. if repo.Owner.IsOrganization() {
  1397. // Organization repository need to recalculate access table when visibility is changed.
  1398. if err = repo.recalculateTeamAccesses(e, 0); err != nil {
  1399. return fmt.Errorf("recalculateTeamAccesses: %v", err)
  1400. }
  1401. }
  1402. // If repo has become private, we need to set its actions to private.
  1403. if repo.IsPrivate {
  1404. _, err = e.Where("repo_id = ?", repo.ID).Cols("is_private").Update(&Action{
  1405. IsPrivate: true,
  1406. })
  1407. if err != nil {
  1408. return err
  1409. }
  1410. }
  1411. // Create/Remove git-daemon-export-ok for git-daemon...
  1412. daemonExportFile := path.Join(repo.repoPath(e), `git-daemon-export-ok`)
  1413. if repo.IsPrivate && com.IsExist(daemonExportFile) {
  1414. if err = os.Remove(daemonExportFile); err != nil {
  1415. log.Error("Failed to remove %s: %v", daemonExportFile, err)
  1416. }
  1417. } else if !repo.IsPrivate && !com.IsExist(daemonExportFile) {
  1418. if f, err := os.Create(daemonExportFile); err != nil {
  1419. log.Error("Failed to create %s: %v", daemonExportFile, err)
  1420. } else {
  1421. f.Close()
  1422. }
  1423. }
  1424. forkRepos, err := getRepositoriesByForkID(e, repo.ID)
  1425. if err != nil {
  1426. return fmt.Errorf("getRepositoriesByForkID: %v", err)
  1427. }
  1428. for i := range forkRepos {
  1429. forkRepos[i].IsPrivate = repo.IsPrivate
  1430. if err = updateRepository(e, forkRepos[i], true); err != nil {
  1431. return fmt.Errorf("updateRepository[%d]: %v", forkRepos[i].ID, err)
  1432. }
  1433. }
  1434. if err = repo.updateSize(e); err != nil {
  1435. log.Error("Failed to update size for repository: %v", err)
  1436. }
  1437. }
  1438. return nil
  1439. }
  1440. // UpdateRepository updates a repository
  1441. func UpdateRepository(repo *Repository, visibilityChanged bool) (err error) {
  1442. sess := x.NewSession()
  1443. defer sess.Close()
  1444. if err = sess.Begin(); err != nil {
  1445. return err
  1446. }
  1447. if err = updateRepository(sess, repo, visibilityChanged); err != nil {
  1448. return fmt.Errorf("updateRepository: %v", err)
  1449. }
  1450. return sess.Commit()
  1451. }
  1452. // UpdateRepositoryUnits updates a repository's units
  1453. func UpdateRepositoryUnits(repo *Repository, units []RepoUnit) (err error) {
  1454. sess := x.NewSession()
  1455. defer sess.Close()
  1456. if err = sess.Begin(); err != nil {
  1457. return err
  1458. }
  1459. if _, err = sess.Where("repo_id = ?", repo.ID).Delete(new(RepoUnit)); err != nil {
  1460. return err
  1461. }
  1462. if _, err = sess.Insert(units); err != nil {
  1463. return err
  1464. }
  1465. return sess.Commit()
  1466. }
  1467. // DeleteRepository deletes a repository for a user or organization.
  1468. func DeleteRepository(doer *User, uid, repoID int64) error {
  1469. // In case is a organization.
  1470. org, err := GetUserByID(uid)
  1471. if err != nil {
  1472. return err
  1473. }
  1474. if org.IsOrganization() {
  1475. if err = org.GetTeams(); err != nil {
  1476. return err
  1477. }
  1478. }
  1479. sess := x.NewSession()
  1480. defer sess.Close()
  1481. if err = sess.Begin(); err != nil {
  1482. return err
  1483. }
  1484. repo := &Repository{ID: repoID, OwnerID: uid}
  1485. has, err := sess.Get(repo)
  1486. if err != nil {
  1487. return err
  1488. } else if !has {
  1489. return ErrRepoNotExist{repoID, uid, "", ""}
  1490. }
  1491. // Delete Deploy Keys
  1492. deployKeys, err := listDeployKeys(sess, repo.ID)
  1493. if err != nil {
  1494. return fmt.Errorf("listDeployKeys: %v", err)
  1495. }
  1496. for _, dKey := range deployKeys {
  1497. if err := deleteDeployKey(sess, doer, dKey.ID); err != nil {
  1498. return fmt.Errorf("deleteDeployKeys: %v", err)
  1499. }
  1500. }
  1501. if cnt, err := sess.ID(repoID).Delete(&Repository{}); err != nil {
  1502. return err
  1503. } else if cnt != 1 {
  1504. return ErrRepoNotExist{repoID, uid, "", ""}
  1505. }
  1506. if org.IsOrganization() {
  1507. for _, t := range org.Teams {
  1508. if !t.hasRepository(sess, repoID) {
  1509. continue
  1510. } else if err = t.removeRepository(sess, repo, false); err != nil {
  1511. return err
  1512. }
  1513. }
  1514. }
  1515. if err = deleteBeans(sess,
  1516. &Access{RepoID: repo.ID},
  1517. &Action{RepoID: repo.ID},
  1518. &Watch{RepoID: repoID},
  1519. &Star{RepoID: repoID},
  1520. &Mirror{RepoID: repoID},
  1521. &Milestone{RepoID: repoID},
  1522. &Release{RepoID: repoID},
  1523. &Collaboration{RepoID: repoID},
  1524. &PullRequest{BaseRepoID: repoID},
  1525. &RepoUnit{RepoID: repoID},
  1526. &RepoRedirect{RedirectRepoID: repoID},
  1527. &Webhook{RepoID: repoID},
  1528. &HookTask{RepoID: repoID},
  1529. &Notification{RepoID: repoID},
  1530. &CommitStatus{RepoID: repoID},
  1531. ); err != nil {
  1532. return fmt.Errorf("deleteBeans: %v", err)
  1533. }
  1534. deleteCond := builder.Select("id").From("issue").Where(builder.Eq{"repo_id": repoID})
  1535. // Delete comments and attachments
  1536. if _, err = sess.In("issue_id", deleteCond).
  1537. Delete(&Comment{}); err != nil {
  1538. return err
  1539. }
  1540. if _, err = sess.In("issue_id", deleteCond).
  1541. Delete(&IssueUser{}); err != nil {
  1542. return err
  1543. }
  1544. if _, err = sess.In("issue_id", deleteCond).
  1545. Delete(&Reaction{}); err != nil {
  1546. return err
  1547. }
  1548. if _, err = sess.In("issue_id", deleteCond).
  1549. Delete(&IssueWatch{}); err != nil {
  1550. return err
  1551. }
  1552. if _, err = sess.In("issue_id", deleteCond).
  1553. Delete(&Stopwatch{}); err != nil {
  1554. return err
  1555. }
  1556. attachmentPaths := make([]string, 0, 20)
  1557. attachments := make([]*Attachment, 0, len(attachmentPaths))
  1558. if err = sess.Join("INNER", "issue", "issue.id = attachment.issue_id").
  1559. Where("issue.repo_id = ?", repoID).
  1560. Find(&attachments); err != nil {
  1561. return err
  1562. }
  1563. for j := range attachments {
  1564. attachmentPaths = append(attachmentPaths, attachments[j].LocalPath())
  1565. }
  1566. if _, err = sess.In("issue_id", deleteCond).
  1567. Delete(&Attachment{}); err != nil {
  1568. return err
  1569. }
  1570. if _, err = sess.Delete(&Issue{RepoID: repoID}); err != nil {
  1571. return err
  1572. }
  1573. if _, err = sess.Where("repo_id = ?", repoID).Delete(new(RepoUnit)); err != nil {
  1574. return err
  1575. }
  1576. if repo.IsFork {
  1577. if _, err = sess.Exec("UPDATE `repository` SET num_forks=num_forks-1 WHERE id=?", repo.ForkID); err != nil {
  1578. return fmt.Errorf("decrease fork count: %v", err)
  1579. }
  1580. }
  1581. if _, err = sess.Exec("UPDATE `user` SET num_repos=num_repos-1 WHERE id=?", uid); err != nil {
  1582. return err
  1583. }
  1584. // FIXME: Remove repository files should be executed after transaction succeed.
  1585. repoPath := repo.repoPath(sess)
  1586. removeAllWithNotice(sess, "Delete repository files", repoPath)
  1587. err = repo.deleteWiki(sess)
  1588. if err != nil {
  1589. return err
  1590. }
  1591. // Remove attachment files.
  1592. for i := range attachmentPaths {
  1593. removeAllWithNotice(sess, "Delete attachment", attachmentPaths[i])
  1594. }
  1595. // Remove LFS objects
  1596. var lfsObjects []*LFSMetaObject
  1597. if err = sess.Where("repository_id=?", repoID).Find(&lfsObjects); err != nil {
  1598. return err
  1599. }
  1600. for _, v := range lfsObjects {
  1601. count, err := sess.Count(&LFSMetaObject{Oid: v.Oid})
  1602. if err != nil {
  1603. return err
  1604. }
  1605. if count > 1 {
  1606. continue
  1607. }
  1608. oidPath := filepath.Join(v.Oid[0:2], v.Oid[2:4], v.Oid[4:len(v.Oid)])
  1609. removeAllWithNotice(sess, "Delete orphaned LFS file", oidPath)
  1610. }
  1611. if _, err := sess.Delete(&LFSMetaObject{RepositoryID: repoID}); err != nil {
  1612. return err
  1613. }
  1614. if repo.NumForks > 0 {
  1615. if _, err = sess.Exec("UPDATE `repository` SET fork_id=0,is_fork=? WHERE fork_id=?", false, repo.ID); err != nil {
  1616. log.Error("reset 'fork_id' and 'is_fork': %v", err)
  1617. }
  1618. }
  1619. if err = sess.Commit(); err != nil {
  1620. if len(deployKeys) > 0 {
  1621. // We need to rewrite the public keys because the commit failed
  1622. if err2 := RewriteAllPublicKeys(); err2 != nil {
  1623. return fmt.Errorf("Commit: %v SSH Keys: %v", err, err2)
  1624. }
  1625. }
  1626. return fmt.Errorf("Commit: %v", err)
  1627. }
  1628. if org.IsOrganization() {
  1629. if err = PrepareWebhooks(repo, HookEventRepository, &api.RepositoryPayload{
  1630. Action: api.HookRepoDeleted,
  1631. Repository: repo.APIFormat(AccessModeOwner),
  1632. Organization: org.APIFormat(),
  1633. Sender: doer.APIFormat(),
  1634. }); err != nil {
  1635. return err
  1636. }
  1637. go HookQueue.Add(repo.ID)
  1638. }
  1639. if len(repo.Avatar) > 0 {
  1640. avatarPath := repo.CustomAvatarPath()
  1641. if com.IsExist(avatarPath) {
  1642. if err := os.Remove(avatarPath); err != nil {
  1643. return fmt.Errorf("Failed to remove %s: %v", avatarPath, err)
  1644. }
  1645. }
  1646. }
  1647. DeleteRepoFromIndexer(repo)
  1648. return nil
  1649. }
  1650. // GetRepositoryByOwnerAndName returns the repository by given ownername and reponame.
  1651. func GetRepositoryByOwnerAndName(ownerName, repoName string) (*Repository, error) {
  1652. var repo Repository
  1653. has, err := x.Select("repository.*").
  1654. Join("INNER", "`user`", "`user`.id = repository.owner_id").
  1655. Where("repository.lower_name = ?", strings.ToLower(repoName)).
  1656. And("`user`.lower_name = ?", strings.ToLower(ownerName)).
  1657. Get(&repo)
  1658. if err != nil {
  1659. return nil, err
  1660. } else if !has {
  1661. return nil, ErrRepoNotExist{0, 0, ownerName, repoName}
  1662. }
  1663. return &repo, nil
  1664. }
  1665. // GetRepositoryByName returns the repository by given name under user if exists.
  1666. func GetRepositoryByName(ownerID int64, name string) (*Repository, error) {
  1667. repo := &Repository{
  1668. OwnerID: ownerID,
  1669. LowerName: strings.ToLower(name),
  1670. }
  1671. has, err := x.Get(repo)
  1672. if err != nil {
  1673. return nil, err
  1674. } else if !has {
  1675. return nil, ErrRepoNotExist{0, ownerID, "", name}
  1676. }
  1677. return repo, err
  1678. }
  1679. func getRepositoryByID(e Engine, id int64) (*Repository, error) {
  1680. repo := new(Repository)
  1681. has, err := e.ID(id).Get(repo)
  1682. if err != nil {
  1683. return nil, err
  1684. } else if !has {
  1685. return nil, ErrRepoNotExist{id, 0, "", ""}
  1686. }
  1687. return repo, nil
  1688. }
  1689. // GetRepositoryByID returns the repository by given id if exists.
  1690. func GetRepositoryByID(id int64) (*Repository, error) {
  1691. return getRepositoryByID(x, id)
  1692. }
  1693. // GetRepositoriesMapByIDs returns the repositories by given id slice.
  1694. func GetRepositoriesMapByIDs(ids []int64) (map[int64]*Repository, error) {
  1695. var repos = make(map[int64]*Repository, len(ids))
  1696. return repos, x.In("id", ids).Find(&repos)
  1697. }
  1698. // GetUserRepositories returns a list of repositories of given user.
  1699. func GetUserRepositories(userID int64, private bool, page, pageSize int, orderBy string) ([]*Repository, error) {
  1700. if len(orderBy) == 0 {
  1701. orderBy = "updated_unix DESC"
  1702. }
  1703. sess := x.
  1704. Where("owner_id = ?", userID).
  1705. OrderBy(orderBy)
  1706. if !private {
  1707. sess.And("is_private=?", false)
  1708. }
  1709. if page <= 0 {
  1710. page = 1
  1711. }
  1712. sess.Limit(pageSize, (page-1)*pageSize)
  1713. repos := make([]*Repository, 0, pageSize)
  1714. return repos, sess.Find(&repos)
  1715. }
  1716. // GetUserMirrorRepositories returns a list of mirror repositories of given user.
  1717. func GetUserMirrorRepositories(userID int64) ([]*Repository, error) {
  1718. repos := make([]*Repository, 0, 10)
  1719. return repos, x.
  1720. Where("owner_id = ?", userID).
  1721. And("is_mirror = ?", true).
  1722. Find(&repos)
  1723. }
  1724. func getRepositoryCount(e Engine, u *User) (int64, error) {
  1725. return e.Count(&Repository{OwnerID: u.ID})
  1726. }
  1727. func getPublicRepositoryCount(e Engine, u *User) (int64, error) {
  1728. return e.Where("is_private = ?", false).Count(&Repository{OwnerID: u.ID})
  1729. }
  1730. func getPrivateRepositoryCount(e Engine, u *User) (int64, error) {
  1731. return e.Where("is_private = ?", true).Count(&Repository{OwnerID: u.ID})
  1732. }
  1733. // GetRepositoryCount returns the total number of repositories of user.
  1734. func GetRepositoryCount(u *User) (int64, error) {
  1735. return getRepositoryCount(x, u)
  1736. }
  1737. // GetPublicRepositoryCount returns the total number of public repositories of user.
  1738. func GetPublicRepositoryCount(u *User) (int64, error) {
  1739. return getPublicRepositoryCount(x, u)
  1740. }
  1741. // GetPrivateRepositoryCount returns the total number of private repositories of user.
  1742. func GetPrivateRepositoryCount(u *User) (int64, error) {
  1743. return getPrivateRepositoryCount(x, u)
  1744. }
  1745. // DeleteRepositoryArchives deletes all repositories' archives.
  1746. func DeleteRepositoryArchives() error {
  1747. return x.
  1748. Where("id > 0").
  1749. Iterate(new(Repository),
  1750. func(idx int, bean interface{}) error {
  1751. repo := bean.(*Repository)
  1752. return os.RemoveAll(filepath.Join(repo.RepoPath(), "archives"))
  1753. })
  1754. }
  1755. // DeleteOldRepositoryArchives deletes old repository archives.
  1756. func DeleteOldRepositoryArchives() {
  1757. if !taskStatusTable.StartIfNotRunning(archiveCleanup) {
  1758. return
  1759. }
  1760. defer taskStatusTable.Stop(archiveCleanup)
  1761. log.Trace("Doing: ArchiveCleanup")
  1762. if err := x.Where("id > 0").Iterate(new(Repository), deleteOldRepositoryArchives); err != nil {
  1763. log.Error("ArchiveClean: %v", err)
  1764. }
  1765. }
  1766. func deleteOldRepositoryArchives(idx int, bean interface{}) error {
  1767. repo := bean.(*Repository)
  1768. basePath := filepath.Join(repo.RepoPath(), "archives")
  1769. for _, ty := range []string{"zip", "targz"} {
  1770. path := filepath.Join(basePath, ty)
  1771. file, err := os.Open(path)
  1772. if err != nil {
  1773. if !os.IsNotExist(err) {
  1774. log.Warn("Unable to open directory %s: %v", path, err)
  1775. return err
  1776. }
  1777. // If the directory doesn't exist, that's okay.
  1778. continue
  1779. }
  1780. files, err := file.Readdir(0)
  1781. file.Close()
  1782. if err != nil {
  1783. log.Warn("Unable to read directory %s: %v", path, err)
  1784. return err
  1785. }
  1786. minimumOldestTime := time.Now().Add(-setting.Cron.ArchiveCleanup.OlderThan)
  1787. for _, info := range files {
  1788. if info.ModTime().Before(minimumOldestTime) && !info.IsDir() {
  1789. toDelete := filepath.Join(path, info.Name())
  1790. // This is a best-effort purge, so we do not check error codes to confirm removal.
  1791. if err = os.Remove(toDelete); err != nil {
  1792. log.Trace("Unable to delete %s, but proceeding: %v", toDelete, err)
  1793. }
  1794. }
  1795. }
  1796. }
  1797. return nil
  1798. }
  1799. func gatherMissingRepoRecords() ([]*Repository, error) {
  1800. repos := make([]*Repository, 0, 10)
  1801. if err := x.
  1802. Where("id > 0").
  1803. Iterate(new(Repository),
  1804. func(idx int, bean interface{}) error {
  1805. repo := bean.(*Repository)
  1806. if !com.IsDir(repo.RepoPath()) {
  1807. repos = append(repos, repo)
  1808. }
  1809. return nil
  1810. }); err != nil {
  1811. if err2 := CreateRepositoryNotice(fmt.Sprintf("gatherMissingRepoRecords: %v", err)); err2 != nil {
  1812. return nil, fmt.Errorf("CreateRepositoryNotice: %v", err)
  1813. }
  1814. }
  1815. return repos, nil
  1816. }
  1817. // DeleteMissingRepositories deletes all repository records that lost Git files.
  1818. func DeleteMissingRepositories(doer *User) error {
  1819. repos, err := gatherMissingRepoRecords()
  1820. if err != nil {
  1821. return fmt.Errorf("gatherMissingRepoRecords: %v", err)
  1822. }
  1823. if len(repos) == 0 {
  1824. return nil
  1825. }
  1826. for _, repo := range repos {
  1827. log.Trace("Deleting %d/%d...", repo.OwnerID, repo.ID)
  1828. if err := DeleteRepository(doer, repo.OwnerID, repo.ID); err != nil {
  1829. if err2 := CreateRepositoryNotice(fmt.Sprintf("DeleteRepository [%d]: %v", repo.ID, err)); err2 != nil {
  1830. return fmt.Errorf("CreateRepositoryNotice: %v", err)
  1831. }
  1832. }
  1833. }
  1834. return nil
  1835. }
  1836. // ReinitMissingRepositories reinitializes all repository records that lost Git files.
  1837. func ReinitMissingRepositories() error {
  1838. repos, err := gatherMissingRepoRecords()
  1839. if err != nil {
  1840. return fmt.Errorf("gatherMissingRepoRecords: %v", err)
  1841. }
  1842. if len(repos) == 0 {
  1843. return nil
  1844. }
  1845. for _, repo := range repos {
  1846. log.Trace("Initializing %d/%d...", repo.OwnerID, repo.ID)
  1847. if err := git.InitRepository(repo.RepoPath(), true); err != nil {
  1848. if err2 := CreateRepositoryNotice(fmt.Sprintf("InitRepository [%d]: %v", repo.ID, err)); err2 != nil {
  1849. return fmt.Errorf("CreateRepositoryNotice: %v", err)
  1850. }
  1851. }
  1852. }
  1853. return nil
  1854. }
  1855. // SyncRepositoryHooks rewrites all repositories' pre-receive, update and post-receive hooks
  1856. // to make sure the binary and custom conf path are up-to-date.
  1857. func SyncRepositoryHooks() error {
  1858. return x.Cols("owner_id", "name").Where("id > 0").Iterate(new(Repository),
  1859. func(idx int, bean interface{}) error {
  1860. if err := createDelegateHooks(bean.(*Repository).RepoPath()); err != nil {
  1861. return fmt.Errorf("SyncRepositoryHook: %v", err)
  1862. }
  1863. if bean.(*Repository).HasWiki() {
  1864. if err := createDelegateHooks(bean.(*Repository).WikiPath()); err != nil {
  1865. return fmt.Errorf("SyncRepositoryHook: %v", err)
  1866. }
  1867. }
  1868. return nil
  1869. })
  1870. }
  1871. // Prevent duplicate running tasks.
  1872. var taskStatusTable = sync.NewStatusTable()
  1873. const (
  1874. mirrorUpdate = "mirror_update"
  1875. gitFsck = "git_fsck"
  1876. checkRepos = "check_repos"
  1877. archiveCleanup = "archive_cleanup"
  1878. )
  1879. // GitFsck calls 'git fsck' to check repository health.
  1880. func GitFsck() {
  1881. if !taskStatusTable.StartIfNotRunning(gitFsck) {
  1882. return
  1883. }
  1884. defer taskStatusTable.Stop(gitFsck)
  1885. log.Trace("Doing: GitFsck")
  1886. if err := x.
  1887. Where("id>0 AND is_fsck_enabled=?", true).BufferSize(setting.IterateBufferSize).
  1888. Iterate(new(Repository),
  1889. func(idx int, bean interface{}) error {
  1890. repo := bean.(*Repository)
  1891. repoPath := repo.RepoPath()
  1892. log.Trace("Running health check on repository %s", repoPath)
  1893. if err := git.Fsck(repoPath, setting.Cron.RepoHealthCheck.Timeout, setting.Cron.RepoHealthCheck.Args...); err != nil {
  1894. desc := fmt.Sprintf("Failed to health check repository (%s): %v", repoPath, err)
  1895. log.Warn(desc)
  1896. if err = CreateRepositoryNotice(desc); err != nil {
  1897. log.Error("CreateRepositoryNotice: %v", err)
  1898. }
  1899. }
  1900. return nil
  1901. }); err != nil {
  1902. log.Error("GitFsck: %v", err)
  1903. }
  1904. log.Trace("Finished: GitFsck")
  1905. }
  1906. // GitGcRepos calls 'git gc' to remove unnecessary files and optimize the local repository
  1907. func GitGcRepos() error {
  1908. args := append([]string{"gc"}, setting.Git.GCArgs...)
  1909. return x.
  1910. Where("id > 0").BufferSize(setting.IterateBufferSize).
  1911. Iterate(new(Repository),
  1912. func(idx int, bean interface{}) error {
  1913. repo := bean.(*Repository)
  1914. if err := repo.GetOwner(); err != nil {
  1915. return err
  1916. }
  1917. _, stderr, err := process.GetManager().ExecDir(
  1918. time.Duration(setting.Git.Timeout.GC)*time.Second,
  1919. RepoPath(repo.Owner.Name, repo.Name), "Repository garbage collection",
  1920. git.GitExecutable, args...)
  1921. if err != nil {
  1922. return fmt.Errorf("%v: %v", err, stderr)
  1923. }
  1924. return nil
  1925. })
  1926. }
  1927. type repoChecker struct {
  1928. querySQL, correctSQL string
  1929. desc string
  1930. }
  1931. func repoStatsCheck(checker *repoChecker) {
  1932. results, err := x.Query(checker.querySQL)
  1933. if err != nil {
  1934. log.Error("Select %s: %v", checker.desc, err)
  1935. return
  1936. }
  1937. for _, result := range results {
  1938. id := com.StrTo(result["id"]).MustInt64()
  1939. log.Trace("Updating %s: %d", checker.desc, id)
  1940. _, err = x.Exec(checker.correctSQL, id, id)
  1941. if err != nil {
  1942. log.Error("Update %s[%d]: %v", checker.desc, id, err)
  1943. }
  1944. }
  1945. }
  1946. // CheckRepoStats checks the repository stats
  1947. func CheckRepoStats() {
  1948. if !taskStatusTable.StartIfNotRunning(checkRepos) {
  1949. return
  1950. }
  1951. defer taskStatusTable.Stop(checkRepos)
  1952. log.Trace("Doing: CheckRepoStats")
  1953. checkers := []*repoChecker{
  1954. // Repository.NumWatches
  1955. {
  1956. "SELECT repo.id FROM `repository` repo WHERE repo.num_watches!=(SELECT COUNT(*) FROM `watch` WHERE repo_id=repo.id)",
  1957. "UPDATE `repository` SET num_watches=(SELECT COUNT(*) FROM `watch` WHERE repo_id=?) WHERE id=?",
  1958. "repository count 'num_watches'",
  1959. },
  1960. // Repository.NumStars
  1961. {
  1962. "SELECT repo.id FROM `repository` repo WHERE repo.num_stars!=(SELECT COUNT(*) FROM `star` WHERE repo_id=repo.id)",
  1963. "UPDATE `repository` SET num_stars=(SELECT COUNT(*) FROM `star` WHERE repo_id=?) WHERE id=?",
  1964. "repository count 'num_stars'",
  1965. },
  1966. // Label.NumIssues
  1967. {
  1968. "SELECT label.id FROM `label` WHERE label.num_issues!=(SELECT COUNT(*) FROM `issue_label` WHERE label_id=label.id)",
  1969. "UPDATE `label` SET num_issues=(SELECT COUNT(*) FROM `issue_label` WHERE label_id=?) WHERE id=?",
  1970. "label count 'num_issues'",
  1971. },
  1972. // User.NumRepos
  1973. {
  1974. "SELECT `user`.id FROM `user` WHERE `user`.num_repos!=(SELECT COUNT(*) FROM `repository` WHERE owner_id=`user`.id)",
  1975. "UPDATE `user` SET num_repos=(SELECT COUNT(*) FROM `repository` WHERE owner_id=?) WHERE id=?",
  1976. "user count 'num_repos'",
  1977. },
  1978. // Issue.NumComments
  1979. {
  1980. "SELECT `issue`.id FROM `issue` WHERE `issue`.num_comments!=(SELECT COUNT(*) FROM `comment` WHERE issue_id=`issue`.id AND type=0)",
  1981. "UPDATE `issue` SET num_comments=(SELECT COUNT(*) FROM `comment` WHERE issue_id=? AND type=0) WHERE id=?",
  1982. "issue count 'num_comments'",
  1983. },
  1984. }
  1985. for i := range checkers {
  1986. repoStatsCheck(checkers[i])
  1987. }
  1988. // ***** START: Repository.NumClosedIssues *****
  1989. desc := "repository count 'num_closed_issues'"
  1990. 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)
  1991. if err != nil {
  1992. log.Error("Select %s: %v", desc, err)
  1993. } else {
  1994. for _, result := range results {
  1995. id := com.StrTo(result["id"]).MustInt64()
  1996. log.Trace("Updating %s: %d", desc, id)
  1997. _, 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)
  1998. if err != nil {
  1999. log.Error("Update %s[%d]: %v", desc, id, err)
  2000. }
  2001. }
  2002. }
  2003. // ***** END: Repository.NumClosedIssues *****
  2004. // FIXME: use checker when stop supporting old fork repo format.
  2005. // ***** START: Repository.NumForks *****
  2006. results, err = x.Query("SELECT repo.id FROM `repository` repo WHERE repo.num_forks!=(SELECT COUNT(*) FROM `repository` WHERE fork_id=repo.id)")
  2007. if err != nil {
  2008. log.Error("Select repository count 'num_forks': %v", err)
  2009. } else {
  2010. for _, result := range results {
  2011. id := com.StrTo(result["id"]).MustInt64()
  2012. log.Trace("Updating repository count 'num_forks': %d", id)
  2013. repo, err := GetRepositoryByID(id)
  2014. if err != nil {
  2015. log.Error("GetRepositoryByID[%d]: %v", id, err)
  2016. continue
  2017. }
  2018. rawResult, err := x.Query("SELECT COUNT(*) FROM `repository` WHERE fork_id=?", repo.ID)
  2019. if err != nil {
  2020. log.Error("Select count of forks[%d]: %v", repo.ID, err)
  2021. continue
  2022. }
  2023. repo.NumForks = int(parseCountResult(rawResult))
  2024. if err = UpdateRepository(repo, false); err != nil {
  2025. log.Error("UpdateRepository[%d]: %v", id, err)
  2026. continue
  2027. }
  2028. }
  2029. }
  2030. // ***** END: Repository.NumForks *****
  2031. }
  2032. // SetArchiveRepoState sets if a repo is archived
  2033. func (repo *Repository) SetArchiveRepoState(isArchived bool) (err error) {
  2034. repo.IsArchived = isArchived
  2035. _, err = x.Where("id = ?", repo.ID).Cols("is_archived").Update(repo)
  2036. return
  2037. }
  2038. // ___________ __
  2039. // \_ _____/__________| | __
  2040. // | __)/ _ \_ __ \ |/ /
  2041. // | \( <_> ) | \/ <
  2042. // \___ / \____/|__| |__|_ \
  2043. // \/ \/
  2044. // HasForkedRepo checks if given user has already forked a repository with given ID.
  2045. func HasForkedRepo(ownerID, repoID int64) (*Repository, bool) {
  2046. repo := new(Repository)
  2047. has, _ := x.
  2048. Where("owner_id=? AND fork_id=?", ownerID, repoID).
  2049. Get(repo)
  2050. return repo, has
  2051. }
  2052. // ForkRepository forks a repository
  2053. func ForkRepository(doer, u *User, oldRepo *Repository, name, desc string) (_ *Repository, err error) {
  2054. forkedRepo, err := oldRepo.GetUserFork(u.ID)
  2055. if err != nil {
  2056. return nil, err
  2057. }
  2058. if forkedRepo != nil {
  2059. return nil, ErrForkAlreadyExist{
  2060. Uname: u.Name,
  2061. RepoName: oldRepo.FullName(),
  2062. ForkName: forkedRepo.FullName(),
  2063. }
  2064. }
  2065. repo := &Repository{
  2066. OwnerID: u.ID,
  2067. Owner: u,
  2068. Name: name,
  2069. LowerName: strings.ToLower(name),
  2070. Description: desc,
  2071. DefaultBranch: oldRepo.DefaultBranch,
  2072. IsPrivate: oldRepo.IsPrivate,
  2073. IsEmpty: oldRepo.IsEmpty,
  2074. IsFork: true,
  2075. ForkID: oldRepo.ID,
  2076. }
  2077. sess := x.NewSession()
  2078. defer sess.Close()
  2079. if err = sess.Begin(); err != nil {
  2080. return nil, err
  2081. }
  2082. if err = createRepository(sess, doer, u, repo); err != nil {
  2083. return nil, err
  2084. }
  2085. if _, err = sess.Exec("UPDATE `repository` SET num_forks=num_forks+1 WHERE id=?", oldRepo.ID); err != nil {
  2086. return nil, err
  2087. }
  2088. repoPath := RepoPath(u.Name, repo.Name)
  2089. _, stderr, err := process.GetManager().ExecTimeout(10*time.Minute,
  2090. fmt.Sprintf("ForkRepository(git clone): %s/%s", u.Name, repo.Name),
  2091. git.GitExecutable, "clone", "--bare", oldRepo.repoPath(sess), repoPath)
  2092. if err != nil {
  2093. return nil, fmt.Errorf("git clone: %v", stderr)
  2094. }
  2095. _, stderr, err = process.GetManager().ExecDir(-1,
  2096. repoPath, fmt.Sprintf("ForkRepository(git update-server-info): %s", repoPath),
  2097. git.GitExecutable, "update-server-info")
  2098. if err != nil {
  2099. return nil, fmt.Errorf("git update-server-info: %v", stderr)
  2100. }
  2101. if err = createDelegateHooks(repoPath); err != nil {
  2102. return nil, fmt.Errorf("createDelegateHooks: %v", err)
  2103. }
  2104. //Commit repo to get Fork ID
  2105. err = sess.Commit()
  2106. if err != nil {
  2107. return nil, err
  2108. }
  2109. oldMode, _ := AccessLevel(doer, oldRepo)
  2110. mode, _ := AccessLevel(doer, repo)
  2111. if err = PrepareWebhooks(oldRepo, HookEventFork, &api.ForkPayload{
  2112. Forkee: oldRepo.APIFormat(oldMode),
  2113. Repo: repo.APIFormat(mode),
  2114. Sender: doer.APIFormat(),
  2115. }); err != nil {
  2116. log.Error("PrepareWebhooks [repo_id: %d]: %v", oldRepo.ID, err)
  2117. } else {
  2118. go HookQueue.Add(oldRepo.ID)
  2119. }
  2120. if err = repo.UpdateSize(); err != nil {
  2121. log.Error("Failed to update size for repository: %v", err)
  2122. }
  2123. // Copy LFS meta objects in new session
  2124. sess2 := x.NewSession()
  2125. defer sess2.Close()
  2126. if err = sess2.Begin(); err != nil {
  2127. return nil, err
  2128. }
  2129. var lfsObjects []*LFSMetaObject
  2130. if err = sess2.Where("repository_id=?", oldRepo.ID).Find(&lfsObjects); err != nil {
  2131. return nil, err
  2132. }
  2133. for _, v := range lfsObjects {
  2134. v.ID = 0
  2135. v.RepositoryID = repo.ID
  2136. if _, err = sess2.Insert(v); err != nil {
  2137. return nil, err
  2138. }
  2139. }
  2140. return repo, sess2.Commit()
  2141. }
  2142. // GetForks returns all the forks of the repository
  2143. func (repo *Repository) GetForks() ([]*Repository, error) {
  2144. forks := make([]*Repository, 0, repo.NumForks)
  2145. return forks, x.Find(&forks, &Repository{ForkID: repo.ID})
  2146. }
  2147. // GetUserFork return user forked repository from this repository, if not forked return nil
  2148. func (repo *Repository) GetUserFork(userID int64) (*Repository, error) {
  2149. var forkedRepo Repository
  2150. has, err := x.Where("fork_id = ?", repo.ID).And("owner_id = ?", userID).Get(&forkedRepo)
  2151. if err != nil {
  2152. return nil, err
  2153. }
  2154. if !has {
  2155. return nil, nil
  2156. }
  2157. return &forkedRepo, nil
  2158. }
  2159. // CustomAvatarPath returns repository custom avatar file path.
  2160. func (repo *Repository) CustomAvatarPath() string {
  2161. // Avatar empty by default
  2162. if len(repo.Avatar) == 0 {
  2163. return ""
  2164. }
  2165. return filepath.Join(setting.RepositoryAvatarUploadPath, repo.Avatar)
  2166. }
  2167. // generateRandomAvatar generates a random avatar for repository.
  2168. func (repo *Repository) generateRandomAvatar(e Engine) error {
  2169. idToString := fmt.Sprintf("%d", repo.ID)
  2170. seed := idToString
  2171. img, err := avatar.RandomImage([]byte(seed))
  2172. if err != nil {
  2173. return fmt.Errorf("RandomImage: %v", err)
  2174. }
  2175. repo.Avatar = idToString
  2176. if err = os.MkdirAll(filepath.Dir(repo.CustomAvatarPath()), os.ModePerm); err != nil {
  2177. return fmt.Errorf("MkdirAll: %v", err)
  2178. }
  2179. fw, err := os.Create(repo.CustomAvatarPath())
  2180. if err != nil {
  2181. return fmt.Errorf("Create: %v", err)
  2182. }
  2183. defer fw.Close()
  2184. if err = png.Encode(fw, img); err != nil {
  2185. return fmt.Errorf("Encode: %v", err)
  2186. }
  2187. log.Info("New random avatar created for repository: %d", repo.ID)
  2188. if _, err := e.ID(repo.ID).Cols("avatar").NoAutoTime().Update(repo); err != nil {
  2189. return err
  2190. }
  2191. return nil
  2192. }
  2193. // RemoveRandomAvatars removes the randomly generated avatars that were created for repositories
  2194. func RemoveRandomAvatars() error {
  2195. return x.
  2196. Where("id > 0").BufferSize(setting.IterateBufferSize).
  2197. Iterate(new(Repository),
  2198. func(idx int, bean interface{}) error {
  2199. repository := bean.(*Repository)
  2200. stringifiedID := strconv.FormatInt(repository.ID, 10)
  2201. if repository.Avatar == stringifiedID {
  2202. return repository.DeleteAvatar()
  2203. }
  2204. return nil
  2205. })
  2206. }
  2207. // RelAvatarLink returns a relative link to the repository's avatar.
  2208. func (repo *Repository) RelAvatarLink() string {
  2209. return repo.relAvatarLink(x)
  2210. }
  2211. func (repo *Repository) relAvatarLink(e Engine) string {
  2212. // If no avatar - path is empty
  2213. avatarPath := repo.CustomAvatarPath()
  2214. if len(avatarPath) == 0 || !com.IsFile(avatarPath) {
  2215. switch mode := setting.RepositoryAvatarFallback; mode {
  2216. case "image":
  2217. return setting.RepositoryAvatarFallbackImage
  2218. case "random":
  2219. if err := repo.generateRandomAvatar(e); err != nil {
  2220. log.Error("generateRandomAvatar: %v", err)
  2221. }
  2222. default:
  2223. // default behaviour: do not display avatar
  2224. return ""
  2225. }
  2226. }
  2227. return setting.AppSubURL + "/repo-avatars/" + repo.Avatar
  2228. }
  2229. // avatarLink returns user avatar absolute link.
  2230. func (repo *Repository) avatarLink(e Engine) string {
  2231. link := repo.relAvatarLink(e)
  2232. // link may be empty!
  2233. if len(link) > 0 {
  2234. if link[0] == '/' && link[1] != '/' {
  2235. return setting.AppURL + strings.TrimPrefix(link, setting.AppSubURL)[1:]
  2236. }
  2237. }
  2238. return link
  2239. }
  2240. // UploadAvatar saves custom avatar for repository.
  2241. // FIXME: split uploads to different subdirs in case we have massive number of repos.
  2242. func (repo *Repository) UploadAvatar(data []byte) error {
  2243. m, err := avatar.Prepare(data)
  2244. if err != nil {
  2245. return err
  2246. }
  2247. sess := x.NewSession()
  2248. defer sess.Close()
  2249. if err = sess.Begin(); err != nil {
  2250. return err
  2251. }
  2252. oldAvatarPath := repo.CustomAvatarPath()
  2253. // Users can upload the same image to other repo - prefix it with ID
  2254. // Then repo will be removed - only it avatar file will be removed
  2255. repo.Avatar = fmt.Sprintf("%d-%x", repo.ID, md5.Sum(data))
  2256. if _, err := sess.ID(repo.ID).Cols("avatar").Update(repo); err != nil {
  2257. return fmt.Errorf("UploadAvatar: Update repository avatar: %v", err)
  2258. }
  2259. if err := os.MkdirAll(setting.RepositoryAvatarUploadPath, os.ModePerm); err != nil {
  2260. return fmt.Errorf("UploadAvatar: Failed to create dir %s: %v", setting.RepositoryAvatarUploadPath, err)
  2261. }
  2262. fw, err := os.Create(repo.CustomAvatarPath())
  2263. if err != nil {
  2264. return fmt.Errorf("UploadAvatar: Create file: %v", err)
  2265. }
  2266. defer fw.Close()
  2267. if err = png.Encode(fw, *m); err != nil {
  2268. return fmt.Errorf("UploadAvatar: Encode png: %v", err)
  2269. }
  2270. if len(oldAvatarPath) > 0 && oldAvatarPath != repo.CustomAvatarPath() {
  2271. if err := os.Remove(oldAvatarPath); err != nil {
  2272. return fmt.Errorf("UploadAvatar: Failed to remove old repo avatar %s: %v", oldAvatarPath, err)
  2273. }
  2274. }
  2275. return sess.Commit()
  2276. }
  2277. // DeleteAvatar deletes the repos's custom avatar.
  2278. func (repo *Repository) DeleteAvatar() error {
  2279. // Avatar not exists
  2280. if len(repo.Avatar) == 0 {
  2281. return nil
  2282. }
  2283. avatarPath := repo.CustomAvatarPath()
  2284. log.Trace("DeleteAvatar[%d]: %s", repo.ID, avatarPath)
  2285. sess := x.NewSession()
  2286. defer sess.Close()
  2287. if err := sess.Begin(); err != nil {
  2288. return err
  2289. }
  2290. repo.Avatar = ""
  2291. if _, err := sess.ID(repo.ID).Cols("avatar").Update(repo); err != nil {
  2292. return fmt.Errorf("DeleteAvatar: Update repository avatar: %v", err)
  2293. }
  2294. if _, err := os.Stat(avatarPath); err == nil {
  2295. if err := os.Remove(avatarPath); err != nil {
  2296. return fmt.Errorf("DeleteAvatar: Failed to remove %s: %v", avatarPath, err)
  2297. }
  2298. } else {
  2299. // // Schrodinger: file may or may not exist. See err for details.
  2300. log.Trace("DeleteAvatar[%d]: %v", err)
  2301. }
  2302. return sess.Commit()
  2303. }
  2304. // GetOriginalURLHostname returns the hostname of a URL or the URL
  2305. func (repo *Repository) GetOriginalURLHostname() string {
  2306. u, err := url.Parse(repo.OriginalURL)
  2307. if err != nil {
  2308. return repo.OriginalURL
  2309. }
  2310. return u.Host
  2311. }