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

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