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