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.

routes.go 42 kB

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
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
Repository avatars (#6986) * Repository avatars - first variant of code from old work for gogs - add migration 87 - add new option in app.ini - add en-US locale string - add new class in repository.less * Add changed index.css, remove unused template name * Update en-us doc about configuration options * Add comments to new functions, add new option to docker app.ini * Add comment for lint * Remove variable, not needed * Fix formatting * Update swagger api template * Check if avatar exists * Fix avatar link/path checks * Typo * TEXT column can't have a default value * Fixes: - remove old avatar file on upload - use ID in name of avatar file - users may upload same files - add simple tests * Fix fmt check * Generate PNG instead of "static" GIF * More informative comment * Fix error message * Update avatar upload checks: - add file size check - add new option - update config docs - add new string to en-us locale * Fixes: - use FileHEader field for check file size - add new test - upload big image * Fix formatting * Update comments * Update log message * Removed wrong style - not needed * Use Sync2 to migrate * Update repos list view - bigger avatar - fix html blocks alignment * A little adjust avatar size * Use small icons for explore/repo list * Use new cool avatar preparation func by @lafriks * Missing changes for new function * Remove unused import, move imports * Missed new option definition in app.ini Add file size check in user/profile avatar upload * Use smaller field length for Avatar * Use session to update repo DB data, update DeleteAvatar - use session too * Fix err variable definition * As suggested @lafriks - return as soon as possible, code readability
6 years ago
Repository avatars (#6986) * Repository avatars - first variant of code from old work for gogs - add migration 87 - add new option in app.ini - add en-US locale string - add new class in repository.less * Add changed index.css, remove unused template name * Update en-us doc about configuration options * Add comments to new functions, add new option to docker app.ini * Add comment for lint * Remove variable, not needed * Fix formatting * Update swagger api template * Check if avatar exists * Fix avatar link/path checks * Typo * TEXT column can't have a default value * Fixes: - remove old avatar file on upload - use ID in name of avatar file - users may upload same files - add simple tests * Fix fmt check * Generate PNG instead of "static" GIF * More informative comment * Fix error message * Update avatar upload checks: - add file size check - add new option - update config docs - add new string to en-us locale * Fixes: - use FileHEader field for check file size - add new test - upload big image * Fix formatting * Update comments * Update log message * Removed wrong style - not needed * Use Sync2 to migrate * Update repos list view - bigger avatar - fix html blocks alignment * A little adjust avatar size * Use small icons for explore/repo list * Use new cool avatar preparation func by @lafriks * Missing changes for new function * Remove unused import, move imports * Missed new option definition in app.ini Add file size check in user/profile avatar upload * Use smaller field length for Avatar * Use session to update repo DB data, update DeleteAvatar - use session too * Fix err variable definition * As suggested @lafriks - return as soon as possible, code readability
6 years ago
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
Graceful Queues: Issue Indexing and Tasks (#9363) * Queue: Add generic graceful queues with settings * Queue & Setting: Add worker pool implementation * Queue: Add worker settings * Queue: Make resizing worker pools * Queue: Add name variable to queues * Queue: Add monitoring * Queue: Improve logging * Issues: Gracefulise the issues indexer Remove the old now unused specific queues * Task: Move to generic queue and gracefulise * Issues: Standardise the issues indexer queue settings * Fix test * Queue: Allow Redis to connect to unix * Prevent deadlock during early shutdown of issue indexer * Add MaxWorker settings to queues * Merge branch 'master' into graceful-queues * Update modules/indexer/issues/indexer.go Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> * Update modules/indexer/issues/indexer.go Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> * Update modules/queue/queue_channel.go Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> * Update modules/queue/queue_disk.go * Update modules/queue/queue_disk_channel.go Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> * Rename queue.Description to queue.ManagedQueue as per @guillep2k * Cancel pool workers when removed * Remove dependency on queue from setting * Update modules/queue/queue_redis.go Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> * As per @guillep2k add mutex locks on shutdown/terminate * move unlocking out of setInternal * Add warning if number of workers < 0 * Small changes as per @guillep2k * No redis host specified not found * Clean up documentation for queues * Update docs/content/doc/advanced/config-cheat-sheet.en-us.md * Update modules/indexer/issues/indexer_test.go * Ensure that persistable channel queue is added to manager * Rename QUEUE_NAME REDIS_QUEUE_NAME * Revert "Rename QUEUE_NAME REDIS_QUEUE_NAME" This reverts commit 1f83b4fc9b9dabda186257b38c265fe7012f90df. Co-authored-by: guillep2k <18600385+guillep2k@users.noreply.github.com> Co-authored-by: Lauris BH <lauris@nix.lv> Co-authored-by: techknowlogick <matti@mdranta.net> Co-authored-by: Lunny Xiao <xiaolunwen@gmail.com>
5 years ago
Graceful Queues: Issue Indexing and Tasks (#9363) * Queue: Add generic graceful queues with settings * Queue & Setting: Add worker pool implementation * Queue: Add worker settings * Queue: Make resizing worker pools * Queue: Add name variable to queues * Queue: Add monitoring * Queue: Improve logging * Issues: Gracefulise the issues indexer Remove the old now unused specific queues * Task: Move to generic queue and gracefulise * Issues: Standardise the issues indexer queue settings * Fix test * Queue: Allow Redis to connect to unix * Prevent deadlock during early shutdown of issue indexer * Add MaxWorker settings to queues * Merge branch 'master' into graceful-queues * Update modules/indexer/issues/indexer.go Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> * Update modules/indexer/issues/indexer.go Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> * Update modules/queue/queue_channel.go Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> * Update modules/queue/queue_disk.go * Update modules/queue/queue_disk_channel.go Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> * Rename queue.Description to queue.ManagedQueue as per @guillep2k * Cancel pool workers when removed * Remove dependency on queue from setting * Update modules/queue/queue_redis.go Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> * As per @guillep2k add mutex locks on shutdown/terminate * move unlocking out of setInternal * Add warning if number of workers < 0 * Small changes as per @guillep2k * No redis host specified not found * Clean up documentation for queues * Update docs/content/doc/advanced/config-cheat-sheet.en-us.md * Update modules/indexer/issues/indexer_test.go * Ensure that persistable channel queue is added to manager * Rename QUEUE_NAME REDIS_QUEUE_NAME * Revert "Rename QUEUE_NAME REDIS_QUEUE_NAME" This reverts commit 1f83b4fc9b9dabda186257b38c265fe7012f90df. Co-authored-by: guillep2k <18600385+guillep2k@users.noreply.github.com> Co-authored-by: Lauris BH <lauris@nix.lv> Co-authored-by: techknowlogick <matti@mdranta.net> Co-authored-by: Lunny Xiao <xiaolunwen@gmail.com>
5 years ago
Repository avatars (#6986) * Repository avatars - first variant of code from old work for gogs - add migration 87 - add new option in app.ini - add en-US locale string - add new class in repository.less * Add changed index.css, remove unused template name * Update en-us doc about configuration options * Add comments to new functions, add new option to docker app.ini * Add comment for lint * Remove variable, not needed * Fix formatting * Update swagger api template * Check if avatar exists * Fix avatar link/path checks * Typo * TEXT column can't have a default value * Fixes: - remove old avatar file on upload - use ID in name of avatar file - users may upload same files - add simple tests * Fix fmt check * Generate PNG instead of "static" GIF * More informative comment * Fix error message * Update avatar upload checks: - add file size check - add new option - update config docs - add new string to en-us locale * Fixes: - use FileHEader field for check file size - add new test - upload big image * Fix formatting * Update comments * Update log message * Removed wrong style - not needed * Use Sync2 to migrate * Update repos list view - bigger avatar - fix html blocks alignment * A little adjust avatar size * Use small icons for explore/repo list * Use new cool avatar preparation func by @lafriks * Missing changes for new function * Remove unused import, move imports * Missed new option definition in app.ini Add file size check in user/profile avatar upload * Use smaller field length for Avatar * Use session to update repo DB data, update DeleteAvatar - use session too * Fix err variable definition * As suggested @lafriks - return as soon as possible, code readability
6 years ago
Feature: Timetracking (#2211) * Added comment's hashtag to url for mail notifications. * Added explanation to return statement + documentation. * Replacing in-line link generation with HTMLURL. (+gofmt) * Replaced action-based model with nil-based model. (+gofmt) * Replaced mailIssueActionToParticipants with mailIssueCommentToParticipants. * Updating comment for mailIssueCommentToParticipants * Added link to comment in "Dashboard" * Deleting feed entry if a comment is going to be deleted * Added migration * Added improved migration to add a CommentID column to action. * Added improved links to comments in feed entries. * Fixes #1956 by filtering for deleted comments that are referenced in actions. * Introducing "IsDeleted" column to action. * Adding design draft (not functional) * Adding database models for stopwatches and trackedtimes * See go-gitea/gitea#967 * Adding design draft (not functional) * Adding translations and improving design * Implementing stopwatch (for timetracking) * Make UI functional * Add hints in timeline for time tracking events * Implementing timetracking feature * Adding "Add time manual" option * Improved stopwatch * Created report of total spent time by user * Only showing total time spent if theire is something to show. * Adding license headers. * Improved error handling for "Add Time Manual" * Adding @sapks 's changes, refactoring * Adding API for feature tracking * Adding unit test * Adding DISABLE/ENABLE option to Repository settings page * Improving translations * Applying @sapk 's changes * Removing repo_unit and using IssuesSetting for disabling/enabling timetracker * Adding DEFAULT_ENABLE_TIMETRACKER to config, installation and admin menu * Improving documentation * Fixing vendor/ folder * Changing timtracking routes by adding subgroups /times and /times/stopwatch (Proposed by @lafriks ) * Restricting write access to timetracking based on the repo settings (Proposed by @lafriks ) * Fixed minor permissions bug. * Adding CanUseTimetracker and IsTimetrackerEnabled in ctx.Repo * Allow assignees and authors to track there time too. * Fixed some build-time-errors + logical errors. * Removing unused Get...ByID functions * Moving IsTimetrackerEnabled from context.Repository to models.Repository * Adding a seperate file for issue related repo functions * Adding license headers * Fixed GetUserByParams return 404 * Moving /users/:username/times to /repos/:username/:reponame/times/:username for security reasons * Adding /repos/:username/times to get all tracked times of the repo * Updating sdk-dependency * Updating swagger.v1.json * Adding warning if user has already a running stopwatch (auto-timetracker) * Replacing GetTrackedTimesBy... with GetTrackedTimes(options FindTrackedTimesOptions) * Changing code.gitea.io/sdk back to code.gitea.io/sdk * Correcting spelling mistake * Updating vendor.json * Changing GET stopwatch/toggle to POST stopwatch/toggle * Changing GET stopwatch/cancel to POST stopwatch/cancel * Added migration for stopwatches/timetracking * Fixed some access bugs for read-only users * Added default allow only contributors to track time value to config * Fixed migration by chaging x.Iterate to x.Find * Resorted imports * Moved Add Time Manually form to repo_form.go * Removed "Seconds" field from Add Time Manually * Resorted imports * Improved permission checking * Fixed some bugs * Added integration test * gofmt * Adding integration test by @lafriks * Added created_unix to comment fixtures * Using last event instead of a fixed event * Adding another integration test by @lafriks * Fixing bug Timetracker enabled causing error 500 at sidebar.tpl * Fixed a refactoring bug that resulted in hiding "HasUserStopwatch" warning. * Returning TrackedTime instead of AddTimeOption at AddTime. * Updating SDK from go-gitea/go-sdk#69 * Resetting Go-SDK back to default repository * Fixing test-vendor by changing ini back to original repository * Adding "tags" to swagger spec * govendor sync * Removed duplicate * Formatting templates * Adding IsTimetrackingEnabled checks to API * Improving translations / english texts * Improving documentation * Updating swagger spec * Fixing integration test caused be translation-changes * Removed encoding issues in local_en-US.ini. * "Added" copyright line * Moved unit.IssuesConfig().EnableTimetracker into a != nil check * Removed some other encoding issues in local_en-US.ini * Improved javascript by checking if data-context exists * Replaced manual comment creation with CreateComment * Removed unnecessary code * Improved error checking * Small cosmetic changes * Replaced int>string>duration parsing with int>duration parsing * Fixed encoding issues * Removed unused imports Signed-off-by: Jonas Franz <info@jonasfranz.software>
8 years ago
Compare branches, commits and tags with each other (#6991) * Supports tags when comparing commits or branches Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Hide headline when only comparing and don't load unused data Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Merges compare logics to allow comparing branches, commits and tags with eachother Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Display branch or tag instead of commit when used for comparing Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Show pull request form after click on button Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Transfers relevant pull.go changes from master to compare.go Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Fixes error when comparing forks against a commit or tag Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Removes console.log from JavaScript file Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Show icon next to commit reference when comparing branch or tag Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Updates css file Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Fixes import order * Renames template variable * Update routers/repo/compare.go Co-Authored-By: zeripath <art27@cantab.net> * Update from master Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Allow short-shas in compare * Renames prInfo to compareInfo Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Check PR permissions only if compare is pull request Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Adjusts comment Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Use compareInfo instead of prInfo
6 years ago
Change target branch for pull request (#6488) * Adds functionality to change target branch of created pull requests Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Use const instead of var in JavaScript additions Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Check if branches are equal and if PR already exists before changing target branch Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Make sure to check all commits Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Print error messages for user as error flash message Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Disallow changing target branch of closed or merged pull requests Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Resolve conflicts after merge of upstream/master Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Change order of branch select fields Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Removes duplicate check Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Use ctx.Tr for translations Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Recompile JS Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Use correct translation namespace Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Remove redundant if condition Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Moves most change branch logic into pull service Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Completes comment Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Add Ref to ChangesPayload for logging changed target branches instead of creating a new struct Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Revert changes to go.mod Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Directly use createComment method Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Return 404 if pull request is not found. Move written check up Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Remove variable declaration Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Return client errors on change pull request target errors Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Return error in commit.HasPreviousCommit Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Adds blank line Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Test patch before persisting new target branch Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Update patch before testing (not working) Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Removes patch calls when changeing pull request target Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Removes unneeded check for base name Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Moves ChangeTargetBranch completely to pull service. Update patch status. Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Set webhook mode after errors were validated Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Update PR in one transaction Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Move logic for check if head is equal with branch to pull model Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Adds missing comment and simplify return Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Adjust CreateComment method call Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com>
6 years ago
Pull request review/approval and comment on code (#3748) * Initial ui components for pull request review * Add Review Add IssueComment types Signed-off-by: Jonas Franz <info@jonasfranz.software> (cherry picked from commit 2b4daab) Signed-off-by: Jonas Franz <info@jonasfranz.software> * Replace ReviewComment with Content Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add load functions Add ReviewID to findComments Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add create review comment implementation Add migration for review Other small changes Signed-off-by: Jonas Franz <info@jonasfranz.software> * Simplified create and find functions for review Signed-off-by: Jonas Franz <info@jonasfranz.software> * Moved "Pending" to first position Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add GetCurrentReview to simplify fetching current review Signed-off-by: Jonas Franz <info@jonasfranz.software> * Preview for listing comments Signed-off-by: Jonas Franz <info@jonasfranz.software> * Move new comment form to its own file Signed-off-by: Jonas Franz <info@jonasfranz.software> * Implement Review form Show Review comments on comment stream Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add support for single comments Showing buttons in context Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add pending tag to pending review comments Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add unit tests for Review Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fetch all review ids at once Add unit tests Signed-off-by: Jonas Franz <info@jonasfranz.software> * gofmt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Improved comment rendering in "Files" view by adding Comments to DiffLine Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add support for invalidating comments Signed-off-by: Jonas Franz <info@jonasfranz.software> * Switched back to code.gitea.io/git Signed-off-by: Jonas Franz <info@jonasfranz.software> * Moved review migration from v64 to v65 Signed-off-by: Jonas Franz <info@jonasfranz.software> * Rebuild css Signed-off-by: Jonas Franz <info@jonasfranz.software> * gofmt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Improve translations Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix unit tests by updating fixtures and updating outdated test Signed-off-by: Jonas Franz <info@jonasfranz.software> * Comments will be shown at the right place now Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add support for deleting CodeComments Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix problems caused by files in subdirectories Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add support for showing code comments of reviews in conversation Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add support for "Show/Hide outdated" Signed-off-by: Jonas Franz <info@jonasfranz.software> * Update code.gitea.io/git Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add support for new webhooks Signed-off-by: Jonas Franz <info@jonasfranz.software> * Update comparison Signed-off-by: Jonas Franz <info@jonasfranz.software> * Resolve conflicts Signed-off-by: Jonas Franz <info@jonasfranz.software> * Minor UI improvements * update code.gitea.io/git * Fix ui bug reported by @lunny causing wrong position of add button Add functionality to "Cancel" button Add scale effects to add button Hide "Cancel" button for existing comments Signed-off-by: Jonas Franz <info@jonasfranz.software> * Prepare solving conflicts Signed-off-by: Jonas Franz <info@jonasfranz.software> * Show add button only if no comments already exist for the line Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add missing vendor files Signed-off-by: Jonas Franz <info@jonasfranz.software> * Check if reviewer is nil Signed-off-by: Jonas Franz <info@jonasfranz.software> * Show forms only to users who are logged in Signed-off-by: Jonas Franz <info@jonasfranz.software> * Revert "Show forms only to users who are logged in" This reverts commit c083682 Signed-off-by: Jonas Franz <info@jonasfranz.software> * Save patch in comment Render patch for code comments Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add link to comment in code Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add reply form to comment list Show forms only to signed in users Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add 'Reply' as translatable Add CODE_COMMENT_LINES setting Signed-off-by: Jonas Franz <info@jonasfranz.software> * gofmt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix problems introduced by checking for singed in user Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add v70 Signed-off-by: Jonas Franz <info@jonasfranz.software> * Update generated stylesheet Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix preview Beginn with new review comment patch system Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add new algo to generate diff for line range Remove old algo used for cutting big diffs (it was very buggy) * Add documentation and example for CutDiffAroundLine * Fix example of CutDiffAroundLine * Fix some comment UI rendering bugs * Add code comment edit mode * Send notifications / actions to users until review gets published Fix diff generation bug Fix wrong hashtag * Fix vet errors * Send notifications also for single comments * Fix some notification bugs, fix link * Fix: add comment icon is only shown on code lines * Add lint comment * Add unit tests for git diff * Add more error messages * Regenerated css Signed-off-by: Jonas Franz <info@jonasfranz.software> * fmt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Regenerated CSS with latest less version Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix test by updating comment type to new ID Signed-off-by: Jonas Franz <info@jonasfranz.software> * Introducing CodeComments as type for map[string]map[int64][]*Comment Other minor code improvements Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix data-tab issues Signed-off-by: Jonas Franz <info@jonasfranz.software> * Remove unnecessary change Signed-off-by: Jonas Franz <info@jonasfranz.software> * refactored checkForInvalidation Signed-off-by: Jonas Franz <info@jonasfranz.software> * Append comments instead of setting Signed-off-by: Jonas Franz <info@jonasfranz.software> * Use HeadRepo instead of BaseRepo Signed-off-by: Jonas Franz <info@jonasfranz.software> * Update migration Signed-off-by: Jonas Franz <info@jonasfranz.de> * Regenerated CSS Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add copyright Signed-off-by: Jonas Franz <info@jonasfranz.software> * Update index.css Signed-off-by: Jonas Franz <info@jonasfranz.software>
7 years ago
Pull request review/approval and comment on code (#3748) * Initial ui components for pull request review * Add Review Add IssueComment types Signed-off-by: Jonas Franz <info@jonasfranz.software> (cherry picked from commit 2b4daab) Signed-off-by: Jonas Franz <info@jonasfranz.software> * Replace ReviewComment with Content Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add load functions Add ReviewID to findComments Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add create review comment implementation Add migration for review Other small changes Signed-off-by: Jonas Franz <info@jonasfranz.software> * Simplified create and find functions for review Signed-off-by: Jonas Franz <info@jonasfranz.software> * Moved "Pending" to first position Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add GetCurrentReview to simplify fetching current review Signed-off-by: Jonas Franz <info@jonasfranz.software> * Preview for listing comments Signed-off-by: Jonas Franz <info@jonasfranz.software> * Move new comment form to its own file Signed-off-by: Jonas Franz <info@jonasfranz.software> * Implement Review form Show Review comments on comment stream Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add support for single comments Showing buttons in context Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add pending tag to pending review comments Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add unit tests for Review Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fetch all review ids at once Add unit tests Signed-off-by: Jonas Franz <info@jonasfranz.software> * gofmt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Improved comment rendering in "Files" view by adding Comments to DiffLine Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add support for invalidating comments Signed-off-by: Jonas Franz <info@jonasfranz.software> * Switched back to code.gitea.io/git Signed-off-by: Jonas Franz <info@jonasfranz.software> * Moved review migration from v64 to v65 Signed-off-by: Jonas Franz <info@jonasfranz.software> * Rebuild css Signed-off-by: Jonas Franz <info@jonasfranz.software> * gofmt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Improve translations Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix unit tests by updating fixtures and updating outdated test Signed-off-by: Jonas Franz <info@jonasfranz.software> * Comments will be shown at the right place now Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add support for deleting CodeComments Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix problems caused by files in subdirectories Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add support for showing code comments of reviews in conversation Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add support for "Show/Hide outdated" Signed-off-by: Jonas Franz <info@jonasfranz.software> * Update code.gitea.io/git Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add support for new webhooks Signed-off-by: Jonas Franz <info@jonasfranz.software> * Update comparison Signed-off-by: Jonas Franz <info@jonasfranz.software> * Resolve conflicts Signed-off-by: Jonas Franz <info@jonasfranz.software> * Minor UI improvements * update code.gitea.io/git * Fix ui bug reported by @lunny causing wrong position of add button Add functionality to "Cancel" button Add scale effects to add button Hide "Cancel" button for existing comments Signed-off-by: Jonas Franz <info@jonasfranz.software> * Prepare solving conflicts Signed-off-by: Jonas Franz <info@jonasfranz.software> * Show add button only if no comments already exist for the line Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add missing vendor files Signed-off-by: Jonas Franz <info@jonasfranz.software> * Check if reviewer is nil Signed-off-by: Jonas Franz <info@jonasfranz.software> * Show forms only to users who are logged in Signed-off-by: Jonas Franz <info@jonasfranz.software> * Revert "Show forms only to users who are logged in" This reverts commit c083682 Signed-off-by: Jonas Franz <info@jonasfranz.software> * Save patch in comment Render patch for code comments Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add link to comment in code Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add reply form to comment list Show forms only to signed in users Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add 'Reply' as translatable Add CODE_COMMENT_LINES setting Signed-off-by: Jonas Franz <info@jonasfranz.software> * gofmt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix problems introduced by checking for singed in user Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add v70 Signed-off-by: Jonas Franz <info@jonasfranz.software> * Update generated stylesheet Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix preview Beginn with new review comment patch system Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add new algo to generate diff for line range Remove old algo used for cutting big diffs (it was very buggy) * Add documentation and example for CutDiffAroundLine * Fix example of CutDiffAroundLine * Fix some comment UI rendering bugs * Add code comment edit mode * Send notifications / actions to users until review gets published Fix diff generation bug Fix wrong hashtag * Fix vet errors * Send notifications also for single comments * Fix some notification bugs, fix link * Fix: add comment icon is only shown on code lines * Add lint comment * Add unit tests for git diff * Add more error messages * Regenerated css Signed-off-by: Jonas Franz <info@jonasfranz.software> * fmt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Regenerated CSS with latest less version Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix test by updating comment type to new ID Signed-off-by: Jonas Franz <info@jonasfranz.software> * Introducing CodeComments as type for map[string]map[int64][]*Comment Other minor code improvements Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix data-tab issues Signed-off-by: Jonas Franz <info@jonasfranz.software> * Remove unnecessary change Signed-off-by: Jonas Franz <info@jonasfranz.software> * refactored checkForInvalidation Signed-off-by: Jonas Franz <info@jonasfranz.software> * Append comments instead of setting Signed-off-by: Jonas Franz <info@jonasfranz.software> * Use HeadRepo instead of BaseRepo Signed-off-by: Jonas Franz <info@jonasfranz.software> * Update migration Signed-off-by: Jonas Franz <info@jonasfranz.de> * Regenerated CSS Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add copyright Signed-off-by: Jonas Franz <info@jonasfranz.software> * Update index.css Signed-off-by: Jonas Franz <info@jonasfranz.software>
7 years ago
Pull request review/approval and comment on code (#3748) * Initial ui components for pull request review * Add Review Add IssueComment types Signed-off-by: Jonas Franz <info@jonasfranz.software> (cherry picked from commit 2b4daab) Signed-off-by: Jonas Franz <info@jonasfranz.software> * Replace ReviewComment with Content Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add load functions Add ReviewID to findComments Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add create review comment implementation Add migration for review Other small changes Signed-off-by: Jonas Franz <info@jonasfranz.software> * Simplified create and find functions for review Signed-off-by: Jonas Franz <info@jonasfranz.software> * Moved "Pending" to first position Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add GetCurrentReview to simplify fetching current review Signed-off-by: Jonas Franz <info@jonasfranz.software> * Preview for listing comments Signed-off-by: Jonas Franz <info@jonasfranz.software> * Move new comment form to its own file Signed-off-by: Jonas Franz <info@jonasfranz.software> * Implement Review form Show Review comments on comment stream Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add support for single comments Showing buttons in context Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add pending tag to pending review comments Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add unit tests for Review Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fetch all review ids at once Add unit tests Signed-off-by: Jonas Franz <info@jonasfranz.software> * gofmt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Improved comment rendering in "Files" view by adding Comments to DiffLine Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add support for invalidating comments Signed-off-by: Jonas Franz <info@jonasfranz.software> * Switched back to code.gitea.io/git Signed-off-by: Jonas Franz <info@jonasfranz.software> * Moved review migration from v64 to v65 Signed-off-by: Jonas Franz <info@jonasfranz.software> * Rebuild css Signed-off-by: Jonas Franz <info@jonasfranz.software> * gofmt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Improve translations Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix unit tests by updating fixtures and updating outdated test Signed-off-by: Jonas Franz <info@jonasfranz.software> * Comments will be shown at the right place now Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add support for deleting CodeComments Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix problems caused by files in subdirectories Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add support for showing code comments of reviews in conversation Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add support for "Show/Hide outdated" Signed-off-by: Jonas Franz <info@jonasfranz.software> * Update code.gitea.io/git Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add support for new webhooks Signed-off-by: Jonas Franz <info@jonasfranz.software> * Update comparison Signed-off-by: Jonas Franz <info@jonasfranz.software> * Resolve conflicts Signed-off-by: Jonas Franz <info@jonasfranz.software> * Minor UI improvements * update code.gitea.io/git * Fix ui bug reported by @lunny causing wrong position of add button Add functionality to "Cancel" button Add scale effects to add button Hide "Cancel" button for existing comments Signed-off-by: Jonas Franz <info@jonasfranz.software> * Prepare solving conflicts Signed-off-by: Jonas Franz <info@jonasfranz.software> * Show add button only if no comments already exist for the line Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add missing vendor files Signed-off-by: Jonas Franz <info@jonasfranz.software> * Check if reviewer is nil Signed-off-by: Jonas Franz <info@jonasfranz.software> * Show forms only to users who are logged in Signed-off-by: Jonas Franz <info@jonasfranz.software> * Revert "Show forms only to users who are logged in" This reverts commit c083682 Signed-off-by: Jonas Franz <info@jonasfranz.software> * Save patch in comment Render patch for code comments Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add link to comment in code Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add reply form to comment list Show forms only to signed in users Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add 'Reply' as translatable Add CODE_COMMENT_LINES setting Signed-off-by: Jonas Franz <info@jonasfranz.software> * gofmt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix problems introduced by checking for singed in user Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add v70 Signed-off-by: Jonas Franz <info@jonasfranz.software> * Update generated stylesheet Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix preview Beginn with new review comment patch system Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add new algo to generate diff for line range Remove old algo used for cutting big diffs (it was very buggy) * Add documentation and example for CutDiffAroundLine * Fix example of CutDiffAroundLine * Fix some comment UI rendering bugs * Add code comment edit mode * Send notifications / actions to users until review gets published Fix diff generation bug Fix wrong hashtag * Fix vet errors * Send notifications also for single comments * Fix some notification bugs, fix link * Fix: add comment icon is only shown on code lines * Add lint comment * Add unit tests for git diff * Add more error messages * Regenerated css Signed-off-by: Jonas Franz <info@jonasfranz.software> * fmt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Regenerated CSS with latest less version Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix test by updating comment type to new ID Signed-off-by: Jonas Franz <info@jonasfranz.software> * Introducing CodeComments as type for map[string]map[int64][]*Comment Other minor code improvements Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix data-tab issues Signed-off-by: Jonas Franz <info@jonasfranz.software> * Remove unnecessary change Signed-off-by: Jonas Franz <info@jonasfranz.software> * refactored checkForInvalidation Signed-off-by: Jonas Franz <info@jonasfranz.software> * Append comments instead of setting Signed-off-by: Jonas Franz <info@jonasfranz.software> * Use HeadRepo instead of BaseRepo Signed-off-by: Jonas Franz <info@jonasfranz.software> * Update migration Signed-off-by: Jonas Franz <info@jonasfranz.de> * Regenerated CSS Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add copyright Signed-off-by: Jonas Franz <info@jonasfranz.software> * Update index.css Signed-off-by: Jonas Franz <info@jonasfranz.software>
7 years ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036
  1. // Copyright 2017 The Gitea Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package routes
  5. import (
  6. "bytes"
  7. "encoding/gob"
  8. "net/http"
  9. "path"
  10. "text/template"
  11. "time"
  12. "code.gitea.io/gitea/models"
  13. "code.gitea.io/gitea/modules/auth"
  14. "code.gitea.io/gitea/modules/context"
  15. "code.gitea.io/gitea/modules/lfs"
  16. "code.gitea.io/gitea/modules/log"
  17. "code.gitea.io/gitea/modules/metrics"
  18. "code.gitea.io/gitea/modules/options"
  19. "code.gitea.io/gitea/modules/public"
  20. "code.gitea.io/gitea/modules/setting"
  21. "code.gitea.io/gitea/modules/templates"
  22. "code.gitea.io/gitea/modules/validation"
  23. "code.gitea.io/gitea/routers"
  24. "code.gitea.io/gitea/routers/admin"
  25. apiv1 "code.gitea.io/gitea/routers/api/v1"
  26. "code.gitea.io/gitea/routers/dev"
  27. "code.gitea.io/gitea/routers/org"
  28. "code.gitea.io/gitea/routers/private"
  29. "code.gitea.io/gitea/routers/repo"
  30. "code.gitea.io/gitea/routers/user"
  31. userSetting "code.gitea.io/gitea/routers/user/setting"
  32. "code.gitea.io/gitea/services/mailer"
  33. // to registers all internal adapters
  34. _ "code.gitea.io/gitea/modules/session"
  35. "gitea.com/macaron/binding"
  36. "gitea.com/macaron/cache"
  37. "gitea.com/macaron/captcha"
  38. "gitea.com/macaron/cors"
  39. "gitea.com/macaron/csrf"
  40. "gitea.com/macaron/gzip"
  41. "gitea.com/macaron/i18n"
  42. "gitea.com/macaron/macaron"
  43. "gitea.com/macaron/session"
  44. "gitea.com/macaron/toolbox"
  45. "github.com/prometheus/client_golang/prometheus"
  46. "github.com/tstranex/u2f"
  47. )
  48. type routerLoggerOptions struct {
  49. Ctx *macaron.Context
  50. Identity *string
  51. Start *time.Time
  52. ResponseWriter *macaron.ResponseWriter
  53. }
  54. func setupAccessLogger(m *macaron.Macaron) {
  55. logger := log.GetLogger("access")
  56. logTemplate, _ := template.New("log").Parse(setting.AccessLogTemplate)
  57. m.Use(func(ctx *macaron.Context) {
  58. start := time.Now()
  59. ctx.Next()
  60. identity := "-"
  61. if val, ok := ctx.Data["SignedUserName"]; ok {
  62. if stringVal, ok := val.(string); ok && stringVal != "" {
  63. identity = stringVal
  64. }
  65. }
  66. rw := ctx.Resp.(macaron.ResponseWriter)
  67. buf := bytes.NewBuffer([]byte{})
  68. err := logTemplate.Execute(buf, routerLoggerOptions{
  69. Ctx: ctx,
  70. Identity: &identity,
  71. Start: &start,
  72. ResponseWriter: &rw,
  73. })
  74. if err != nil {
  75. log.Error("Could not set up macaron access logger: %v", err.Error())
  76. }
  77. err = logger.SendLog(log.INFO, "", "", 0, buf.String(), "")
  78. if err != nil {
  79. log.Error("Could not set up macaron access logger: %v", err.Error())
  80. }
  81. })
  82. }
  83. // RouterHandler is a macaron handler that will log the routing to the default gitea log
  84. func RouterHandler(level log.Level) func(ctx *macaron.Context) {
  85. return func(ctx *macaron.Context) {
  86. start := time.Now()
  87. _ = log.GetLogger("router").Log(0, level, "Started %s %s for %s", log.ColoredMethod(ctx.Req.Method), ctx.Req.URL.RequestURI(), ctx.RemoteAddr())
  88. rw := ctx.Resp.(macaron.ResponseWriter)
  89. ctx.Next()
  90. status := rw.Status()
  91. _ = log.GetLogger("router").Log(0, level, "Completed %s %s %v %s in %v", log.ColoredMethod(ctx.Req.Method), ctx.Req.URL.RequestURI(), log.ColoredStatus(status), log.ColoredStatus(status, http.StatusText(rw.Status())), log.ColoredTime(time.Since(start)))
  92. }
  93. }
  94. // NewMacaron initializes Macaron instance.
  95. func NewMacaron() *macaron.Macaron {
  96. gob.Register(&u2f.Challenge{})
  97. var m *macaron.Macaron
  98. if setting.RedirectMacaronLog {
  99. loggerAsWriter := log.NewLoggerAsWriter("INFO", log.GetLogger("macaron"))
  100. m = macaron.NewWithLogger(loggerAsWriter)
  101. if !setting.DisableRouterLog && setting.RouterLogLevel != log.NONE {
  102. if log.GetLogger("router").GetLevel() <= setting.RouterLogLevel {
  103. m.Use(RouterHandler(setting.RouterLogLevel))
  104. }
  105. }
  106. } else {
  107. m = macaron.New()
  108. if !setting.DisableRouterLog {
  109. m.Use(macaron.Logger())
  110. }
  111. }
  112. // Access Logger is similar to Router Log but more configurable and by default is more like the NCSA Common Log format
  113. if setting.EnableAccessLog {
  114. setupAccessLogger(m)
  115. }
  116. m.Use(macaron.Recovery())
  117. if setting.EnableGzip {
  118. m.Use(gzip.Middleware())
  119. }
  120. if setting.Protocol == setting.FCGI || setting.Protocol == setting.FCGIUnix {
  121. m.SetURLPrefix(setting.AppSubURL)
  122. }
  123. m.Use(public.Custom(
  124. &public.Options{
  125. SkipLogging: setting.DisableRouterLog,
  126. ExpiresAfter: setting.StaticCacheTime,
  127. },
  128. ))
  129. m.Use(public.Static(
  130. &public.Options{
  131. Directory: path.Join(setting.StaticRootPath, "public"),
  132. SkipLogging: setting.DisableRouterLog,
  133. ExpiresAfter: setting.StaticCacheTime,
  134. },
  135. ))
  136. m.Use(public.StaticHandler(
  137. setting.AvatarUploadPath,
  138. &public.Options{
  139. Prefix: "avatars",
  140. SkipLogging: setting.DisableRouterLog,
  141. ExpiresAfter: setting.StaticCacheTime,
  142. },
  143. ))
  144. m.Use(public.StaticHandler(
  145. setting.RepositoryAvatarUploadPath,
  146. &public.Options{
  147. Prefix: "repo-avatars",
  148. SkipLogging: setting.DisableRouterLog,
  149. ExpiresAfter: setting.StaticCacheTime,
  150. },
  151. ))
  152. m.Use(templates.HTMLRenderer())
  153. mailer.InitMailRender(templates.Mailer())
  154. localeNames, err := options.Dir("locale")
  155. if err != nil {
  156. log.Fatal("Failed to list locale files: %v", err)
  157. }
  158. localFiles := make(map[string][]byte)
  159. for _, name := range localeNames {
  160. localFiles[name], err = options.Locale(name)
  161. if err != nil {
  162. log.Fatal("Failed to load %s locale file. %v", name, err)
  163. }
  164. }
  165. m.Use(i18n.I18n(i18n.Options{
  166. SubURL: setting.AppSubURL,
  167. Files: localFiles,
  168. Langs: setting.Langs,
  169. Names: setting.Names,
  170. DefaultLang: "en-US",
  171. Redirect: false,
  172. CookieDomain: setting.SessionConfig.Domain,
  173. }))
  174. m.Use(cache.Cacher(cache.Options{
  175. Adapter: setting.CacheService.Adapter,
  176. AdapterConfig: setting.CacheService.Conn,
  177. Interval: setting.CacheService.Interval,
  178. }))
  179. m.Use(captcha.Captchaer(captcha.Options{
  180. SubURL: setting.AppSubURL,
  181. }))
  182. m.Use(session.Sessioner(session.Options{
  183. Provider: setting.SessionConfig.Provider,
  184. ProviderConfig: setting.SessionConfig.ProviderConfig,
  185. CookieName: setting.SessionConfig.CookieName,
  186. CookiePath: setting.SessionConfig.CookiePath,
  187. Gclifetime: setting.SessionConfig.Gclifetime,
  188. Maxlifetime: setting.SessionConfig.Maxlifetime,
  189. Secure: setting.SessionConfig.Secure,
  190. Domain: setting.SessionConfig.Domain,
  191. }))
  192. m.Use(csrf.Csrfer(csrf.Options{
  193. Secret: setting.SecretKey,
  194. Cookie: setting.CSRFCookieName,
  195. SetCookie: true,
  196. Secure: setting.SessionConfig.Secure,
  197. CookieHttpOnly: setting.CSRFCookieHTTPOnly,
  198. Header: "X-Csrf-Token",
  199. CookieDomain: setting.SessionConfig.Domain,
  200. CookiePath: setting.AppSubURL,
  201. }))
  202. m.Use(toolbox.Toolboxer(m, toolbox.Options{
  203. HealthCheckFuncs: []*toolbox.HealthCheckFuncDesc{
  204. {
  205. Desc: "Database connection",
  206. Func: models.Ping,
  207. },
  208. },
  209. DisableDebug: !setting.EnablePprof,
  210. }))
  211. m.Use(context.Contexter())
  212. // OK we are now set-up enough to allow us to create a nicer recovery than
  213. // the default macaron recovery
  214. m.Use(context.Recovery())
  215. m.SetAutoHead(true)
  216. return m
  217. }
  218. // RegisterRoutes routes routes to Macaron
  219. func RegisterRoutes(m *macaron.Macaron) {
  220. reqSignIn := context.Toggle(&context.ToggleOptions{SignInRequired: true})
  221. ignSignIn := context.Toggle(&context.ToggleOptions{SignInRequired: setting.Service.RequireSignInView})
  222. ignSignInAndCsrf := context.Toggle(&context.ToggleOptions{DisableCSRF: true})
  223. reqSignOut := context.Toggle(&context.ToggleOptions{SignOutRequired: true})
  224. bindIgnErr := binding.BindIgnErr
  225. validation.AddBindingRules()
  226. openIDSignInEnabled := func(ctx *context.Context) {
  227. if !setting.Service.EnableOpenIDSignIn {
  228. ctx.Error(403)
  229. return
  230. }
  231. }
  232. openIDSignUpEnabled := func(ctx *context.Context) {
  233. if !setting.Service.EnableOpenIDSignUp {
  234. ctx.Error(403)
  235. return
  236. }
  237. }
  238. reqMilestonesDashboardPageEnabled := func(ctx *context.Context) {
  239. if !setting.Service.ShowMilestonesDashboardPage {
  240. ctx.Error(403)
  241. return
  242. }
  243. }
  244. m.Use(user.GetNotificationCount)
  245. m.Use(func(ctx *context.Context) {
  246. ctx.Data["UnitWikiGlobalDisabled"] = models.UnitTypeWiki.UnitGlobalDisabled()
  247. ctx.Data["UnitIssuesGlobalDisabled"] = models.UnitTypeIssues.UnitGlobalDisabled()
  248. ctx.Data["UnitPullsGlobalDisabled"] = models.UnitTypePullRequests.UnitGlobalDisabled()
  249. })
  250. // FIXME: not all routes need go through same middlewares.
  251. // Especially some AJAX requests, we can reduce middleware number to improve performance.
  252. // Routers.
  253. // for health check
  254. m.Head("/", func() string {
  255. return ""
  256. })
  257. m.Get("/", routers.Home)
  258. m.Group("/explore", func() {
  259. m.Get("", func(ctx *context.Context) {
  260. ctx.Redirect(setting.AppSubURL + "/explore/repos")
  261. })
  262. m.Get("/repos", routers.ExploreRepos)
  263. m.Get("/users", routers.ExploreUsers)
  264. m.Get("/organizations", routers.ExploreOrganizations)
  265. m.Get("/code", routers.ExploreCode)
  266. }, ignSignIn)
  267. m.Combo("/install", routers.InstallInit).Get(routers.Install).
  268. Post(bindIgnErr(auth.InstallForm{}), routers.InstallPost)
  269. m.Get("/^:type(issues|pulls)$", reqSignIn, user.Issues)
  270. m.Get("/milestones", reqSignIn, reqMilestonesDashboardPageEnabled, user.Milestones)
  271. // ***** START: User *****
  272. m.Group("/user", func() {
  273. m.Get("/login", user.SignIn)
  274. m.Post("/login", bindIgnErr(auth.SignInForm{}), user.SignInPost)
  275. m.Group("", func() {
  276. m.Combo("/login/openid").
  277. Get(user.SignInOpenID).
  278. Post(bindIgnErr(auth.SignInOpenIDForm{}), user.SignInOpenIDPost)
  279. }, openIDSignInEnabled)
  280. m.Group("/openid", func() {
  281. m.Combo("/connect").
  282. Get(user.ConnectOpenID).
  283. Post(bindIgnErr(auth.ConnectOpenIDForm{}), user.ConnectOpenIDPost)
  284. m.Group("/register", func() {
  285. m.Combo("").
  286. Get(user.RegisterOpenID, openIDSignUpEnabled).
  287. Post(bindIgnErr(auth.SignUpOpenIDForm{}), user.RegisterOpenIDPost)
  288. }, openIDSignUpEnabled)
  289. }, openIDSignInEnabled)
  290. m.Get("/sign_up", user.SignUp)
  291. m.Post("/sign_up", bindIgnErr(auth.RegisterForm{}), user.SignUpPost)
  292. m.Group("/oauth2", func() {
  293. m.Get("/:provider", user.SignInOAuth)
  294. m.Get("/:provider/callback", user.SignInOAuthCallback)
  295. })
  296. m.Get("/link_account", user.LinkAccount)
  297. m.Post("/link_account_signin", bindIgnErr(auth.SignInForm{}), user.LinkAccountPostSignIn)
  298. m.Post("/link_account_signup", bindIgnErr(auth.RegisterForm{}), user.LinkAccountPostRegister)
  299. m.Group("/two_factor", func() {
  300. m.Get("", user.TwoFactor)
  301. m.Post("", bindIgnErr(auth.TwoFactorAuthForm{}), user.TwoFactorPost)
  302. m.Get("/scratch", user.TwoFactorScratch)
  303. m.Post("/scratch", bindIgnErr(auth.TwoFactorScratchAuthForm{}), user.TwoFactorScratchPost)
  304. })
  305. m.Group("/u2f", func() {
  306. m.Get("", user.U2F)
  307. m.Get("/challenge", user.U2FChallenge)
  308. m.Post("/sign", bindIgnErr(u2f.SignResponse{}), user.U2FSign)
  309. })
  310. }, reqSignOut)
  311. m.Group("/login/oauth", func() {
  312. m.Get("/authorize", bindIgnErr(auth.AuthorizationForm{}), user.AuthorizeOAuth)
  313. m.Post("/grant", bindIgnErr(auth.GrantApplicationForm{}), user.GrantApplicationOAuth)
  314. // TODO manage redirection
  315. m.Post("/authorize", bindIgnErr(auth.AuthorizationForm{}), user.AuthorizeOAuth)
  316. }, ignSignInAndCsrf, reqSignIn)
  317. m.Post("/login/oauth/access_token", bindIgnErr(auth.AccessTokenForm{}), ignSignInAndCsrf, user.AccessTokenOAuth)
  318. m.Group("/user/settings", func() {
  319. m.Get("", userSetting.Profile)
  320. m.Post("", bindIgnErr(auth.UpdateProfileForm{}), userSetting.ProfilePost)
  321. m.Get("/change_password", user.MustChangePassword)
  322. m.Post("/change_password", bindIgnErr(auth.MustChangePasswordForm{}), user.MustChangePasswordPost)
  323. m.Post("/avatar", binding.MultipartForm(auth.AvatarForm{}), userSetting.AvatarPost)
  324. m.Post("/avatar/delete", userSetting.DeleteAvatar)
  325. m.Group("/account", func() {
  326. m.Combo("").Get(userSetting.Account).Post(bindIgnErr(auth.ChangePasswordForm{}), userSetting.AccountPost)
  327. m.Post("/email", bindIgnErr(auth.AddEmailForm{}), userSetting.EmailPost)
  328. m.Post("/email/delete", userSetting.DeleteEmail)
  329. m.Post("/delete", userSetting.DeleteAccount)
  330. m.Post("/theme", bindIgnErr(auth.UpdateThemeForm{}), userSetting.UpdateUIThemePost)
  331. })
  332. m.Group("/security", func() {
  333. m.Get("", userSetting.Security)
  334. m.Group("/two_factor", func() {
  335. m.Post("/regenerate_scratch", userSetting.RegenerateScratchTwoFactor)
  336. m.Post("/disable", userSetting.DisableTwoFactor)
  337. m.Get("/enroll", userSetting.EnrollTwoFactor)
  338. m.Post("/enroll", bindIgnErr(auth.TwoFactorAuthForm{}), userSetting.EnrollTwoFactorPost)
  339. })
  340. m.Group("/u2f", func() {
  341. m.Post("/request_register", bindIgnErr(auth.U2FRegistrationForm{}), userSetting.U2FRegister)
  342. m.Post("/register", bindIgnErr(u2f.RegisterResponse{}), userSetting.U2FRegisterPost)
  343. m.Post("/delete", bindIgnErr(auth.U2FDeleteForm{}), userSetting.U2FDelete)
  344. })
  345. m.Group("/openid", func() {
  346. m.Post("", bindIgnErr(auth.AddOpenIDForm{}), userSetting.OpenIDPost)
  347. m.Post("/delete", userSetting.DeleteOpenID)
  348. m.Post("/toggle_visibility", userSetting.ToggleOpenIDVisibility)
  349. }, openIDSignInEnabled)
  350. m.Post("/account_link", userSetting.DeleteAccountLink)
  351. })
  352. m.Group("/applications/oauth2", func() {
  353. m.Get("/:id", userSetting.OAuth2ApplicationShow)
  354. m.Post("/:id", bindIgnErr(auth.EditOAuth2ApplicationForm{}), userSetting.OAuthApplicationsEdit)
  355. m.Post("/:id/regenerate_secret", userSetting.OAuthApplicationsRegenerateSecret)
  356. m.Post("", bindIgnErr(auth.EditOAuth2ApplicationForm{}), userSetting.OAuthApplicationsPost)
  357. m.Post("/delete", userSetting.DeleteOAuth2Application)
  358. m.Post("/revoke", userSetting.RevokeOAuth2Grant)
  359. })
  360. m.Combo("/applications").Get(userSetting.Applications).
  361. Post(bindIgnErr(auth.NewAccessTokenForm{}), userSetting.ApplicationsPost)
  362. m.Post("/applications/delete", userSetting.DeleteApplication)
  363. m.Combo("/keys").Get(userSetting.Keys).
  364. Post(bindIgnErr(auth.AddKeyForm{}), userSetting.KeysPost)
  365. m.Post("/keys/delete", userSetting.DeleteKey)
  366. m.Get("/organization", userSetting.Organization)
  367. m.Get("/repos", userSetting.Repos)
  368. }, reqSignIn, func(ctx *context.Context) {
  369. ctx.Data["PageIsUserSettings"] = true
  370. ctx.Data["AllThemes"] = setting.UI.Themes
  371. })
  372. m.Group("/user", func() {
  373. // r.Get("/feeds", binding.Bind(auth.FeedsForm{}), user.Feeds)
  374. m.Any("/activate", user.Activate, reqSignIn)
  375. m.Any("/activate_email", user.ActivateEmail)
  376. m.Get("/avatar/:username/:size", user.Avatar)
  377. m.Get("/email2user", user.Email2User)
  378. m.Get("/recover_account", user.ResetPasswd)
  379. m.Post("/recover_account", user.ResetPasswdPost)
  380. m.Get("/forgot_password", user.ForgotPasswd)
  381. m.Post("/forgot_password", user.ForgotPasswdPost)
  382. m.Post("/logout", user.SignOut)
  383. })
  384. // ***** END: User *****
  385. m.Get("/avatar/:hash", user.AvatarByEmailHash)
  386. adminReq := context.Toggle(&context.ToggleOptions{SignInRequired: true, AdminRequired: true})
  387. // ***** START: Admin *****
  388. m.Group("/admin", func() {
  389. m.Get("", adminReq, admin.Dashboard)
  390. m.Post("", adminReq, bindIgnErr(auth.AdminDashboardForm{}), admin.DashboardPost)
  391. m.Get("/config", admin.Config)
  392. m.Post("/config/test_mail", admin.SendTestMail)
  393. m.Group("/monitor", func() {
  394. m.Get("", admin.Monitor)
  395. m.Post("/cancel/:pid", admin.MonitorCancel)
  396. m.Group("/queue/:qid", func() {
  397. m.Get("", admin.Queue)
  398. m.Post("/set", admin.SetQueueSettings)
  399. m.Post("/add", admin.AddWorkers)
  400. m.Post("/cancel/:pid", admin.WorkerCancel)
  401. m.Post("/flush", admin.Flush)
  402. })
  403. })
  404. m.Group("/users", func() {
  405. m.Get("", admin.Users)
  406. m.Combo("/new").Get(admin.NewUser).Post(bindIgnErr(auth.AdminCreateUserForm{}), admin.NewUserPost)
  407. m.Combo("/:userid").Get(admin.EditUser).Post(bindIgnErr(auth.AdminEditUserForm{}), admin.EditUserPost)
  408. m.Post("/:userid/delete", admin.DeleteUser)
  409. })
  410. m.Group("/emails", func() {
  411. m.Get("", admin.Emails)
  412. m.Post("/activate", admin.ActivateEmail)
  413. })
  414. m.Group("/orgs", func() {
  415. m.Get("", admin.Organizations)
  416. })
  417. m.Group("/repos", func() {
  418. m.Get("", admin.Repos)
  419. m.Post("/delete", admin.DeleteRepo)
  420. })
  421. m.Group("/^:configType(hooks|system-hooks)$", func() {
  422. m.Get("", admin.DefaultOrSystemWebhooks)
  423. m.Post("/delete", admin.DeleteDefaultOrSystemWebhook)
  424. m.Get("/:type/new", repo.WebhooksNew)
  425. m.Post("/gitea/new", bindIgnErr(auth.NewWebhookForm{}), repo.GiteaHooksNewPost)
  426. m.Post("/gogs/new", bindIgnErr(auth.NewGogshookForm{}), repo.GogsHooksNewPost)
  427. m.Post("/slack/new", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksNewPost)
  428. m.Post("/discord/new", bindIgnErr(auth.NewDiscordHookForm{}), repo.DiscordHooksNewPost)
  429. m.Post("/dingtalk/new", bindIgnErr(auth.NewDingtalkHookForm{}), repo.DingtalkHooksNewPost)
  430. m.Post("/telegram/new", bindIgnErr(auth.NewTelegramHookForm{}), repo.TelegramHooksNewPost)
  431. m.Post("/msteams/new", bindIgnErr(auth.NewMSTeamsHookForm{}), repo.MSTeamsHooksNewPost)
  432. m.Post("/feishu/new", bindIgnErr(auth.NewFeishuHookForm{}), repo.FeishuHooksNewPost)
  433. m.Get("/:id", repo.WebHooksEdit)
  434. m.Post("/gitea/:id", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksEditPost)
  435. m.Post("/gogs/:id", bindIgnErr(auth.NewGogshookForm{}), repo.GogsHooksEditPost)
  436. m.Post("/slack/:id", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksEditPost)
  437. m.Post("/discord/:id", bindIgnErr(auth.NewDiscordHookForm{}), repo.DiscordHooksEditPost)
  438. m.Post("/dingtalk/:id", bindIgnErr(auth.NewDingtalkHookForm{}), repo.DingtalkHooksEditPost)
  439. m.Post("/telegram/:id", bindIgnErr(auth.NewTelegramHookForm{}), repo.TelegramHooksEditPost)
  440. m.Post("/msteams/:id", bindIgnErr(auth.NewMSTeamsHookForm{}), repo.MSTeamsHooksEditPost)
  441. m.Post("/feishu/:id", bindIgnErr(auth.NewFeishuHookForm{}), repo.FeishuHooksEditPost)
  442. })
  443. m.Group("/auths", func() {
  444. m.Get("", admin.Authentications)
  445. m.Combo("/new").Get(admin.NewAuthSource).Post(bindIgnErr(auth.AuthenticationForm{}), admin.NewAuthSourcePost)
  446. m.Combo("/:authid").Get(admin.EditAuthSource).
  447. Post(bindIgnErr(auth.AuthenticationForm{}), admin.EditAuthSourcePost)
  448. m.Post("/:authid/delete", admin.DeleteAuthSource)
  449. })
  450. m.Group("/notices", func() {
  451. m.Get("", admin.Notices)
  452. m.Post("/delete", admin.DeleteNotices)
  453. m.Post("/empty", admin.EmptyNotices)
  454. })
  455. }, adminReq)
  456. // ***** END: Admin *****
  457. m.Group("", func() {
  458. m.Get("/:username", user.Profile)
  459. m.Get("/attachments/:uuid", repo.GetAttachment)
  460. }, ignSignIn)
  461. m.Group("/attachments", func() {
  462. m.Post("", repo.UploadAttachment)
  463. m.Post("/delete", repo.DeleteAttachment)
  464. }, reqSignIn)
  465. m.Group("/:username", func() {
  466. m.Post("/action/:action", user.Action)
  467. }, reqSignIn)
  468. if macaron.Env == macaron.DEV {
  469. m.Get("/template/*", dev.TemplatePreview)
  470. }
  471. reqRepoAdmin := context.RequireRepoAdmin()
  472. reqRepoCodeWriter := context.RequireRepoWriter(models.UnitTypeCode)
  473. reqRepoCodeReader := context.RequireRepoReader(models.UnitTypeCode)
  474. reqRepoReleaseWriter := context.RequireRepoWriter(models.UnitTypeReleases)
  475. reqRepoReleaseReader := context.RequireRepoReader(models.UnitTypeReleases)
  476. reqRepoWikiWriter := context.RequireRepoWriter(models.UnitTypeWiki)
  477. reqRepoIssueWriter := context.RequireRepoWriter(models.UnitTypeIssues)
  478. reqRepoIssueReader := context.RequireRepoReader(models.UnitTypeIssues)
  479. reqRepoPullsWriter := context.RequireRepoWriter(models.UnitTypePullRequests)
  480. reqRepoPullsReader := context.RequireRepoReader(models.UnitTypePullRequests)
  481. reqRepoIssuesOrPullsWriter := context.RequireRepoWriterOr(models.UnitTypeIssues, models.UnitTypePullRequests)
  482. reqRepoIssuesOrPullsReader := context.RequireRepoReaderOr(models.UnitTypeIssues, models.UnitTypePullRequests)
  483. // ***** START: Organization *****
  484. m.Group("/org", func() {
  485. m.Group("", func() {
  486. m.Get("/create", org.Create)
  487. m.Post("/create", bindIgnErr(auth.CreateOrgForm{}), org.CreatePost)
  488. })
  489. m.Group("/:org", func() {
  490. m.Get("/dashboard", user.Dashboard)
  491. m.Get("/^:type(issues|pulls)$", user.Issues)
  492. m.Get("/milestones", reqMilestonesDashboardPageEnabled, user.Milestones)
  493. m.Get("/members", org.Members)
  494. m.Post("/members/action/:action", org.MembersAction)
  495. m.Get("/teams", org.Teams)
  496. }, context.OrgAssignment(true))
  497. m.Group("/:org", func() {
  498. m.Get("/teams/:team", org.TeamMembers)
  499. m.Get("/teams/:team/repositories", org.TeamRepositories)
  500. m.Post("/teams/:team/action/:action", org.TeamsAction)
  501. m.Post("/teams/:team/action/repo/:action", org.TeamsRepoAction)
  502. }, context.OrgAssignment(true, false, true))
  503. m.Group("/:org", func() {
  504. m.Get("/teams/new", org.NewTeam)
  505. m.Post("/teams/new", bindIgnErr(auth.CreateTeamForm{}), org.NewTeamPost)
  506. m.Get("/teams/:team/edit", org.EditTeam)
  507. m.Post("/teams/:team/edit", bindIgnErr(auth.CreateTeamForm{}), org.EditTeamPost)
  508. m.Post("/teams/:team/delete", org.DeleteTeam)
  509. m.Group("/settings", func() {
  510. m.Combo("").Get(org.Settings).
  511. Post(bindIgnErr(auth.UpdateOrgSettingForm{}), org.SettingsPost)
  512. m.Post("/avatar", binding.MultipartForm(auth.AvatarForm{}), org.SettingsAvatar)
  513. m.Post("/avatar/delete", org.SettingsDeleteAvatar)
  514. m.Group("/hooks", func() {
  515. m.Get("", org.Webhooks)
  516. m.Post("/delete", org.DeleteWebhook)
  517. m.Get("/:type/new", repo.WebhooksNew)
  518. m.Post("/gitea/new", bindIgnErr(auth.NewWebhookForm{}), repo.GiteaHooksNewPost)
  519. m.Post("/gogs/new", bindIgnErr(auth.NewGogshookForm{}), repo.GogsHooksNewPost)
  520. m.Post("/slack/new", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksNewPost)
  521. m.Post("/discord/new", bindIgnErr(auth.NewDiscordHookForm{}), repo.DiscordHooksNewPost)
  522. m.Post("/dingtalk/new", bindIgnErr(auth.NewDingtalkHookForm{}), repo.DingtalkHooksNewPost)
  523. m.Post("/telegram/new", bindIgnErr(auth.NewTelegramHookForm{}), repo.TelegramHooksNewPost)
  524. m.Post("/msteams/new", bindIgnErr(auth.NewMSTeamsHookForm{}), repo.MSTeamsHooksNewPost)
  525. m.Post("/feishu/new", bindIgnErr(auth.NewFeishuHookForm{}), repo.FeishuHooksNewPost)
  526. m.Get("/:id", repo.WebHooksEdit)
  527. m.Post("/gitea/:id", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksEditPost)
  528. m.Post("/gogs/:id", bindIgnErr(auth.NewGogshookForm{}), repo.GogsHooksEditPost)
  529. m.Post("/slack/:id", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksEditPost)
  530. m.Post("/discord/:id", bindIgnErr(auth.NewDiscordHookForm{}), repo.DiscordHooksEditPost)
  531. m.Post("/dingtalk/:id", bindIgnErr(auth.NewDingtalkHookForm{}), repo.DingtalkHooksEditPost)
  532. m.Post("/telegram/:id", bindIgnErr(auth.NewTelegramHookForm{}), repo.TelegramHooksEditPost)
  533. m.Post("/msteams/:id", bindIgnErr(auth.NewMSTeamsHookForm{}), repo.MSTeamsHooksEditPost)
  534. m.Post("/feishu/:id", bindIgnErr(auth.NewFeishuHookForm{}), repo.FeishuHooksEditPost)
  535. })
  536. m.Route("/delete", "GET,POST", org.SettingsDelete)
  537. })
  538. }, context.OrgAssignment(true, true))
  539. }, reqSignIn)
  540. // ***** END: Organization *****
  541. // ***** START: Repository *****
  542. m.Group("/repo", func() {
  543. m.Get("/create", repo.Create)
  544. m.Post("/create", bindIgnErr(auth.CreateRepoForm{}), repo.CreatePost)
  545. m.Get("/migrate", repo.Migrate)
  546. m.Post("/migrate", bindIgnErr(auth.MigrateRepoForm{}), repo.MigratePost)
  547. m.Group("/fork", func() {
  548. m.Combo("/:repoid").Get(repo.Fork).
  549. Post(bindIgnErr(auth.CreateRepoForm{}), repo.ForkPost)
  550. }, context.RepoIDAssignment(), context.UnitTypes(), reqRepoCodeReader)
  551. }, reqSignIn)
  552. // ***** Release Attachment Download without Signin
  553. m.Get("/:username/:reponame/releases/download/:vTag/:fileName", ignSignIn, context.RepoAssignment(), repo.MustBeNotEmpty, repo.RedirectDownload)
  554. m.Group("/:username/:reponame", func() {
  555. m.Group("/settings", func() {
  556. m.Combo("").Get(repo.Settings).
  557. Post(bindIgnErr(auth.RepoSettingForm{}), repo.SettingsPost)
  558. m.Post("/avatar", binding.MultipartForm(auth.AvatarForm{}), repo.SettingsAvatar)
  559. m.Post("/avatar/delete", repo.SettingsDeleteAvatar)
  560. m.Group("/collaboration", func() {
  561. m.Combo("").Get(repo.Collaboration).Post(repo.CollaborationPost)
  562. m.Post("/access_mode", repo.ChangeCollaborationAccessMode)
  563. m.Post("/delete", repo.DeleteCollaboration)
  564. m.Group("/team", func() {
  565. m.Post("", repo.AddTeamPost)
  566. m.Post("/delete", repo.DeleteTeam)
  567. })
  568. })
  569. m.Group("/branches", func() {
  570. m.Combo("").Get(repo.ProtectedBranch).Post(repo.ProtectedBranchPost)
  571. m.Combo("/*").Get(repo.SettingsProtectedBranch).
  572. Post(bindIgnErr(auth.ProtectBranchForm{}), context.RepoMustNotBeArchived(), repo.SettingsProtectedBranchPost)
  573. }, repo.MustBeNotEmpty)
  574. m.Group("/hooks", func() {
  575. m.Get("", repo.Webhooks)
  576. m.Post("/delete", repo.DeleteWebhook)
  577. m.Get("/:type/new", repo.WebhooksNew)
  578. m.Post("/gitea/new", bindIgnErr(auth.NewWebhookForm{}), repo.GiteaHooksNewPost)
  579. m.Post("/gogs/new", bindIgnErr(auth.NewGogshookForm{}), repo.GogsHooksNewPost)
  580. m.Post("/slack/new", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksNewPost)
  581. m.Post("/discord/new", bindIgnErr(auth.NewDiscordHookForm{}), repo.DiscordHooksNewPost)
  582. m.Post("/dingtalk/new", bindIgnErr(auth.NewDingtalkHookForm{}), repo.DingtalkHooksNewPost)
  583. m.Post("/telegram/new", bindIgnErr(auth.NewTelegramHookForm{}), repo.TelegramHooksNewPost)
  584. m.Post("/msteams/new", bindIgnErr(auth.NewMSTeamsHookForm{}), repo.MSTeamsHooksNewPost)
  585. m.Post("/feishu/new", bindIgnErr(auth.NewFeishuHookForm{}), repo.FeishuHooksNewPost)
  586. m.Get("/:id", repo.WebHooksEdit)
  587. m.Post("/:id/test", repo.TestWebhook)
  588. m.Post("/gitea/:id", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksEditPost)
  589. m.Post("/gogs/:id", bindIgnErr(auth.NewGogshookForm{}), repo.GogsHooksEditPost)
  590. m.Post("/slack/:id", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksEditPost)
  591. m.Post("/discord/:id", bindIgnErr(auth.NewDiscordHookForm{}), repo.DiscordHooksEditPost)
  592. m.Post("/dingtalk/:id", bindIgnErr(auth.NewDingtalkHookForm{}), repo.DingtalkHooksEditPost)
  593. m.Post("/telegram/:id", bindIgnErr(auth.NewTelegramHookForm{}), repo.TelegramHooksEditPost)
  594. m.Post("/msteams/:id", bindIgnErr(auth.NewMSTeamsHookForm{}), repo.MSTeamsHooksEditPost)
  595. m.Post("/feishu/:id", bindIgnErr(auth.NewFeishuHookForm{}), repo.FeishuHooksEditPost)
  596. m.Group("/git", func() {
  597. m.Get("", repo.GitHooks)
  598. m.Combo("/:name").Get(repo.GitHooksEdit).
  599. Post(repo.GitHooksEditPost)
  600. }, context.GitHookService())
  601. })
  602. m.Group("/keys", func() {
  603. m.Combo("").Get(repo.DeployKeys).
  604. Post(bindIgnErr(auth.AddKeyForm{}), repo.DeployKeysPost)
  605. m.Post("/delete", repo.DeleteDeployKey)
  606. })
  607. m.Group("/lfs", func() {
  608. m.Get("", repo.LFSFiles)
  609. m.Get("/show/:oid", repo.LFSFileGet)
  610. m.Post("/delete/:oid", repo.LFSDelete)
  611. m.Get("/pointers", repo.LFSPointerFiles)
  612. m.Post("/pointers/associate", repo.LFSAutoAssociate)
  613. m.Get("/find", repo.LFSFileFind)
  614. m.Group("/locks", func() {
  615. m.Get("/", repo.LFSLocks)
  616. m.Post("/", repo.LFSLockFile)
  617. m.Post("/:lid/unlock", repo.LFSUnlock)
  618. })
  619. })
  620. }, func(ctx *context.Context) {
  621. ctx.Data["PageIsSettings"] = true
  622. ctx.Data["LFSStartServer"] = setting.LFS.StartServer
  623. })
  624. }, reqSignIn, context.RepoAssignment(), context.UnitTypes(), reqRepoAdmin, context.RepoRef())
  625. m.Post("/:username/:reponame/action/:action", reqSignIn, context.RepoAssignment(), context.UnitTypes(), repo.Action)
  626. m.Group("/:username/:reponame", func() {
  627. m.Group("/issues", func() {
  628. m.Combo("/new").Get(context.RepoRef(), repo.NewIssue).
  629. Post(bindIgnErr(auth.CreateIssueForm{}), repo.NewIssuePost)
  630. }, context.RepoMustNotBeArchived(), reqRepoIssueReader)
  631. // FIXME: should use different URLs but mostly same logic for comments of issue and pull reuqest.
  632. // So they can apply their own enable/disable logic on routers.
  633. m.Group("/issues", func() {
  634. m.Group("/:index", func() {
  635. m.Post("/title", repo.UpdateIssueTitle)
  636. m.Post("/content", repo.UpdateIssueContent)
  637. m.Post("/watch", repo.IssueWatch)
  638. m.Group("/dependency", func() {
  639. m.Post("/add", repo.AddDependency)
  640. m.Post("/delete", repo.RemoveDependency)
  641. })
  642. m.Combo("/comments").Post(repo.MustAllowUserComment, bindIgnErr(auth.CreateCommentForm{}), repo.NewComment)
  643. m.Group("/times", func() {
  644. m.Post("/add", bindIgnErr(auth.AddTimeManuallyForm{}), repo.AddTimeManually)
  645. m.Group("/stopwatch", func() {
  646. m.Post("/toggle", repo.IssueStopwatch)
  647. m.Post("/cancel", repo.CancelStopwatch)
  648. })
  649. })
  650. m.Post("/reactions/:action", bindIgnErr(auth.ReactionForm{}), repo.ChangeIssueReaction)
  651. m.Post("/lock", reqRepoIssueWriter, bindIgnErr(auth.IssueLockForm{}), repo.LockIssue)
  652. m.Post("/unlock", reqRepoIssueWriter, repo.UnlockIssue)
  653. m.Get("/attachments", repo.GetIssueAttachments)
  654. }, context.RepoMustNotBeArchived())
  655. m.Post("/labels", reqRepoIssuesOrPullsWriter, repo.UpdateIssueLabel)
  656. m.Post("/milestone", reqRepoIssuesOrPullsWriter, repo.UpdateIssueMilestone)
  657. m.Post("/assignee", reqRepoIssuesOrPullsWriter, repo.UpdateIssueAssignee)
  658. m.Post("/status", reqRepoIssuesOrPullsWriter, repo.UpdateIssueStatus)
  659. }, context.RepoMustNotBeArchived())
  660. m.Group("/comments/:id", func() {
  661. m.Post("", repo.UpdateCommentContent)
  662. m.Post("/delete", repo.DeleteComment)
  663. m.Post("/reactions/:action", bindIgnErr(auth.ReactionForm{}), repo.ChangeCommentReaction)
  664. m.Get("/attachments", repo.GetCommentAttachments)
  665. }, context.RepoMustNotBeArchived())
  666. m.Group("/labels", func() {
  667. m.Post("/new", bindIgnErr(auth.CreateLabelForm{}), repo.NewLabel)
  668. m.Post("/edit", bindIgnErr(auth.CreateLabelForm{}), repo.UpdateLabel)
  669. m.Post("/delete", repo.DeleteLabel)
  670. m.Post("/initialize", bindIgnErr(auth.InitializeLabelsForm{}), repo.InitializeLabels)
  671. }, context.RepoMustNotBeArchived(), reqRepoIssuesOrPullsWriter, context.RepoRef())
  672. m.Group("/milestones", func() {
  673. m.Combo("/new").Get(repo.NewMilestone).
  674. Post(bindIgnErr(auth.CreateMilestoneForm{}), repo.NewMilestonePost)
  675. m.Get("/:id/edit", repo.EditMilestone)
  676. m.Post("/:id/edit", bindIgnErr(auth.CreateMilestoneForm{}), repo.EditMilestonePost)
  677. m.Post("/:id/:action", repo.ChangeMilestonStatus)
  678. m.Post("/delete", repo.DeleteMilestone)
  679. }, context.RepoMustNotBeArchived(), reqRepoIssuesOrPullsWriter, context.RepoRef())
  680. m.Group("/milestone", func() {
  681. m.Get("/:id", repo.MilestoneIssuesAndPulls)
  682. }, reqRepoIssuesOrPullsReader, context.RepoRef())
  683. m.Combo("/compare/*", repo.MustBeNotEmpty, reqRepoCodeReader, repo.SetEditorconfigIfExists).
  684. Get(repo.SetDiffViewStyle, repo.CompareDiff).
  685. Post(context.RepoMustNotBeArchived(), reqRepoPullsReader, repo.MustAllowPulls, bindIgnErr(auth.CreateIssueForm{}), repo.CompareAndPullRequestPost)
  686. m.Group("/pull", func() {
  687. m.Post("/:index/target_branch", repo.UpdatePullRequestTarget)
  688. }, context.RepoMustNotBeArchived())
  689. m.Group("", func() {
  690. m.Group("", func() {
  691. m.Combo("/_edit/*").Get(repo.EditFile).
  692. Post(bindIgnErr(auth.EditRepoFileForm{}), repo.EditFilePost)
  693. m.Combo("/_new/*").Get(repo.NewFile).
  694. Post(bindIgnErr(auth.EditRepoFileForm{}), repo.NewFilePost)
  695. m.Post("/_preview/*", bindIgnErr(auth.EditPreviewDiffForm{}), repo.DiffPreviewPost)
  696. m.Combo("/_delete/*").Get(repo.DeleteFile).
  697. Post(bindIgnErr(auth.DeleteRepoFileForm{}), repo.DeleteFilePost)
  698. m.Combo("/_upload/*", repo.MustBeAbleToUpload).
  699. Get(repo.UploadFile).
  700. Post(bindIgnErr(auth.UploadRepoFileForm{}), repo.UploadFilePost)
  701. }, context.RepoRefByType(context.RepoRefBranch), repo.MustBeEditable)
  702. m.Group("", func() {
  703. m.Post("/upload-file", repo.UploadFileToServer)
  704. m.Post("/upload-remove", bindIgnErr(auth.RemoveUploadFileForm{}), repo.RemoveUploadFileFromServer)
  705. }, context.RepoRef(), repo.MustBeEditable, repo.MustBeAbleToUpload)
  706. }, context.RepoMustNotBeArchived(), reqRepoCodeWriter, repo.MustBeNotEmpty)
  707. m.Group("/branches", func() {
  708. m.Group("/_new/", func() {
  709. m.Post("/branch/*", context.RepoRefByType(context.RepoRefBranch), repo.CreateBranch)
  710. m.Post("/tag/*", context.RepoRefByType(context.RepoRefTag), repo.CreateBranch)
  711. m.Post("/commit/*", context.RepoRefByType(context.RepoRefCommit), repo.CreateBranch)
  712. }, bindIgnErr(auth.NewBranchForm{}))
  713. m.Post("/delete", repo.DeleteBranchPost)
  714. m.Post("/restore", repo.RestoreBranchPost)
  715. }, context.RepoMustNotBeArchived(), reqRepoCodeWriter, repo.MustBeNotEmpty)
  716. }, reqSignIn, context.RepoAssignment(), context.UnitTypes())
  717. // Releases
  718. m.Group("/:username/:reponame", func() {
  719. m.Group("/releases", func() {
  720. m.Get("/", repo.MustBeNotEmpty, repo.Releases)
  721. }, repo.MustBeNotEmpty, context.RepoRef())
  722. m.Group("/releases", func() {
  723. m.Get("/new", repo.NewRelease)
  724. m.Post("/new", bindIgnErr(auth.NewReleaseForm{}), repo.NewReleasePost)
  725. m.Post("/delete", repo.DeleteRelease)
  726. }, reqSignIn, repo.MustBeNotEmpty, context.RepoMustNotBeArchived(), reqRepoReleaseWriter, context.RepoRef())
  727. m.Group("/releases", func() {
  728. m.Get("/edit/*", repo.EditRelease)
  729. m.Post("/edit/*", bindIgnErr(auth.EditReleaseForm{}), repo.EditReleasePost)
  730. }, reqSignIn, repo.MustBeNotEmpty, context.RepoMustNotBeArchived(), reqRepoReleaseWriter, func(ctx *context.Context) {
  731. var err error
  732. ctx.Repo.Commit, err = ctx.Repo.GitRepo.GetBranchCommit(ctx.Repo.Repository.DefaultBranch)
  733. if err != nil {
  734. ctx.ServerError("GetBranchCommit", err)
  735. return
  736. }
  737. ctx.Repo.CommitsCount, err = ctx.Repo.GetCommitsCount()
  738. if err != nil {
  739. ctx.ServerError("GetCommitsCount", err)
  740. return
  741. }
  742. ctx.Data["CommitsCount"] = ctx.Repo.CommitsCount
  743. })
  744. }, ignSignIn, context.RepoAssignment(), context.UnitTypes(), reqRepoReleaseReader)
  745. m.Group("/:username/:reponame", func() {
  746. m.Post("/topics", repo.TopicsPost)
  747. }, context.RepoAssignment(), context.RepoMustNotBeArchived(), reqRepoAdmin)
  748. m.Group("/:username/:reponame", func() {
  749. m.Group("", func() {
  750. m.Get("/^:type(issues|pulls)$", repo.Issues)
  751. m.Get("/^:type(issues|pulls)$/:index", repo.ViewIssue)
  752. m.Get("/labels/", reqRepoIssuesOrPullsReader, repo.RetrieveLabels, repo.Labels)
  753. m.Get("/milestones", reqRepoIssuesOrPullsReader, repo.Milestones)
  754. }, context.RepoRef())
  755. m.Group("/wiki", func() {
  756. m.Get("/?:page", repo.Wiki)
  757. m.Get("/_pages", repo.WikiPages)
  758. m.Get("/:page/_revision", repo.WikiRevision)
  759. m.Group("", func() {
  760. m.Combo("/_new").Get(repo.NewWiki).
  761. Post(bindIgnErr(auth.NewWikiForm{}), repo.NewWikiPost)
  762. m.Combo("/:page/_edit").Get(repo.EditWiki).
  763. Post(bindIgnErr(auth.NewWikiForm{}), repo.EditWikiPost)
  764. m.Post("/:page/delete", repo.DeleteWikiPagePost)
  765. }, context.RepoMustNotBeArchived(), reqSignIn, reqRepoWikiWriter)
  766. }, repo.MustEnableWiki, context.RepoRef())
  767. m.Group("/wiki", func() {
  768. m.Get("/raw/*", repo.WikiRaw)
  769. }, repo.MustEnableWiki)
  770. m.Group("/activity", func() {
  771. m.Get("", repo.Activity)
  772. m.Get("/:period", repo.Activity)
  773. }, context.RepoRef(), repo.MustBeNotEmpty, context.RequireRepoReaderOr(models.UnitTypePullRequests, models.UnitTypeIssues, models.UnitTypeReleases))
  774. m.Group("/activity_author_data", func() {
  775. m.Get("", repo.ActivityAuthors)
  776. m.Get("/:period", repo.ActivityAuthors)
  777. }, context.RepoRef(), repo.MustBeNotEmpty, context.RequireRepoReaderOr(models.UnitTypeCode))
  778. m.Get("/archive/*", repo.MustBeNotEmpty, reqRepoCodeReader, repo.Download)
  779. m.Get("/status", reqRepoCodeReader, repo.Status)
  780. m.Group("/branches", func() {
  781. m.Get("", repo.Branches)
  782. }, repo.MustBeNotEmpty, context.RepoRef(), reqRepoCodeReader)
  783. m.Group("/blob_excerpt", func() {
  784. m.Get("/:sha", repo.SetEditorconfigIfExists, repo.SetDiffViewStyle, repo.ExcerptBlob)
  785. }, repo.MustBeNotEmpty, context.RepoRef(), reqRepoCodeReader)
  786. m.Group("/pulls/:index", func() {
  787. m.Get(".diff", repo.DownloadPullDiff)
  788. m.Get(".patch", repo.DownloadPullPatch)
  789. m.Get("/commits", context.RepoRef(), repo.ViewPullCommits)
  790. m.Post("/merge", context.RepoMustNotBeArchived(), reqRepoPullsWriter, bindIgnErr(auth.MergePullRequestForm{}), repo.MergePullRequest)
  791. m.Post("/update", repo.UpdatePullRequest)
  792. m.Post("/cleanup", context.RepoMustNotBeArchived(), context.RepoRef(), repo.CleanUpPullRequest)
  793. m.Group("/files", func() {
  794. m.Get("", context.RepoRef(), repo.SetEditorconfigIfExists, repo.SetDiffViewStyle, repo.SetWhitespaceBehavior, repo.ViewPullFiles)
  795. m.Group("/reviews", func() {
  796. m.Post("/comments", bindIgnErr(auth.CodeCommentForm{}), repo.CreateCodeComment)
  797. m.Post("/submit", bindIgnErr(auth.SubmitReviewForm{}), repo.SubmitReview)
  798. }, context.RepoMustNotBeArchived())
  799. })
  800. }, repo.MustAllowPulls)
  801. m.Group("/media", func() {
  802. m.Get("/branch/*", context.RepoRefByType(context.RepoRefBranch), repo.SingleDownloadOrLFS)
  803. m.Get("/tag/*", context.RepoRefByType(context.RepoRefTag), repo.SingleDownloadOrLFS)
  804. m.Get("/commit/*", context.RepoRefByType(context.RepoRefCommit), repo.SingleDownloadOrLFS)
  805. m.Get("/blob/:sha", context.RepoRefByType(context.RepoRefBlob), repo.DownloadByIDOrLFS)
  806. // "/*" route is deprecated, and kept for backward compatibility
  807. m.Get("/*", context.RepoRefByType(context.RepoRefLegacy), repo.SingleDownloadOrLFS)
  808. }, repo.MustBeNotEmpty, reqRepoCodeReader)
  809. m.Group("/raw", func() {
  810. m.Get("/branch/*", context.RepoRefByType(context.RepoRefBranch), repo.SingleDownload)
  811. m.Get("/tag/*", context.RepoRefByType(context.RepoRefTag), repo.SingleDownload)
  812. m.Get("/commit/*", context.RepoRefByType(context.RepoRefCommit), repo.SingleDownload)
  813. m.Get("/blob/:sha", context.RepoRefByType(context.RepoRefBlob), repo.DownloadByID)
  814. // "/*" route is deprecated, and kept for backward compatibility
  815. m.Get("/*", context.RepoRefByType(context.RepoRefLegacy), repo.SingleDownload)
  816. }, repo.MustBeNotEmpty, reqRepoCodeReader)
  817. m.Group("/commits", func() {
  818. m.Get("/branch/*", context.RepoRefByType(context.RepoRefBranch), repo.RefCommits)
  819. m.Get("/tag/*", context.RepoRefByType(context.RepoRefTag), repo.RefCommits)
  820. m.Get("/commit/*", context.RepoRefByType(context.RepoRefCommit), repo.RefCommits)
  821. // "/*" route is deprecated, and kept for backward compatibility
  822. m.Get("/*", context.RepoRefByType(context.RepoRefLegacy), repo.RefCommits)
  823. }, repo.MustBeNotEmpty, reqRepoCodeReader)
  824. m.Group("/blame", func() {
  825. m.Get("/branch/*", context.RepoRefByType(context.RepoRefBranch), repo.RefBlame)
  826. m.Get("/tag/*", context.RepoRefByType(context.RepoRefTag), repo.RefBlame)
  827. m.Get("/commit/*", context.RepoRefByType(context.RepoRefCommit), repo.RefBlame)
  828. }, repo.MustBeNotEmpty, reqRepoCodeReader)
  829. m.Group("", func() {
  830. m.Get("/graph", repo.Graph)
  831. m.Get("/commit/:sha([a-f0-9]{7,40})$", repo.SetEditorconfigIfExists, repo.SetDiffViewStyle, repo.Diff)
  832. }, repo.MustBeNotEmpty, context.RepoRef(), reqRepoCodeReader)
  833. m.Group("/src", func() {
  834. m.Get("/branch/*", context.RepoRefByType(context.RepoRefBranch), repo.Home)
  835. m.Get("/tag/*", context.RepoRefByType(context.RepoRefTag), repo.Home)
  836. m.Get("/commit/*", context.RepoRefByType(context.RepoRefCommit), repo.Home)
  837. // "/*" route is deprecated, and kept for backward compatibility
  838. m.Get("/*", context.RepoRefByType(context.RepoRefLegacy), repo.Home)
  839. }, repo.SetEditorconfigIfExists)
  840. m.Group("", func() {
  841. m.Get("/forks", repo.Forks)
  842. }, context.RepoRef(), reqRepoCodeReader)
  843. m.Get("/commit/:sha([a-f0-9]{7,40})\\.:ext(patch|diff)",
  844. repo.MustBeNotEmpty, reqRepoCodeReader, repo.RawDiff)
  845. }, ignSignIn, context.RepoAssignment(), context.UnitTypes())
  846. m.Group("/:username/:reponame", func() {
  847. m.Get("/stars", repo.Stars)
  848. m.Get("/watchers", repo.Watchers)
  849. m.Get("/search", reqRepoCodeReader, repo.Search)
  850. }, ignSignIn, context.RepoAssignment(), context.RepoRef(), context.UnitTypes())
  851. m.Group("/:username", func() {
  852. m.Group("/:reponame", func() {
  853. m.Get("", repo.SetEditorconfigIfExists, repo.Home)
  854. m.Get("\\.git$", repo.SetEditorconfigIfExists, repo.Home)
  855. }, ignSignIn, context.RepoAssignment(), context.RepoRef(), context.UnitTypes())
  856. m.Group("/:reponame", func() {
  857. m.Group("\\.git/info/lfs", func() {
  858. m.Post("/objects/batch", lfs.BatchHandler)
  859. m.Get("/objects/:oid/:filename", lfs.ObjectOidHandler)
  860. m.Any("/objects/:oid", lfs.ObjectOidHandler)
  861. m.Post("/objects", lfs.PostHandler)
  862. m.Post("/verify", lfs.VerifyHandler)
  863. m.Group("/locks", func() {
  864. m.Get("/", lfs.GetListLockHandler)
  865. m.Post("/", lfs.PostLockHandler)
  866. m.Post("/verify", lfs.VerifyLockHandler)
  867. m.Post("/:lid/unlock", lfs.UnLockHandler)
  868. })
  869. m.Any("/*", func(ctx *context.Context) {
  870. ctx.NotFound("", nil)
  871. })
  872. }, ignSignInAndCsrf)
  873. m.Any("/*", ignSignInAndCsrf, repo.HTTP)
  874. m.Head("/tasks/trigger", repo.TriggerTask)
  875. })
  876. })
  877. // ***** END: Repository *****
  878. m.Group("/notifications", func() {
  879. m.Get("", user.Notifications)
  880. m.Post("/status", user.NotificationStatusPost)
  881. m.Post("/purge", user.NotificationPurgePost)
  882. }, reqSignIn)
  883. if setting.API.EnableSwagger {
  884. m.Get("/swagger.v1.json", templates.JSONRenderer(), routers.SwaggerV1Json)
  885. }
  886. var handlers []macaron.Handler
  887. if setting.CORSConfig.Enabled {
  888. handlers = append(handlers, cors.CORS(cors.Options{
  889. Scheme: setting.CORSConfig.Scheme,
  890. AllowDomain: setting.CORSConfig.AllowDomain,
  891. AllowSubdomain: setting.CORSConfig.AllowSubdomain,
  892. Methods: setting.CORSConfig.Methods,
  893. MaxAgeSeconds: int(setting.CORSConfig.MaxAge.Seconds()),
  894. AllowCredentials: setting.CORSConfig.AllowCredentials,
  895. }))
  896. }
  897. handlers = append(handlers, ignSignIn)
  898. m.Group("/api", func() {
  899. apiv1.RegisterRoutes(m)
  900. }, handlers...)
  901. m.Group("/api/internal", func() {
  902. // package name internal is ideal but Golang is not allowed, so we use private as package name.
  903. private.RegisterRoutes(m)
  904. })
  905. // robots.txt
  906. m.Get("/robots.txt", func(ctx *context.Context) {
  907. if setting.HasRobotsTxt {
  908. ctx.ServeFileContent(path.Join(setting.CustomPath, "robots.txt"))
  909. } else {
  910. ctx.NotFound("", nil)
  911. }
  912. })
  913. m.Get("/apple-touch-icon.png", func(ctx *context.Context) {
  914. ctx.Redirect(path.Join(setting.StaticURLPrefix, "img/apple-touch-icon.png"), 301)
  915. })
  916. // Progressive Web App
  917. m.Get("/manifest.json", templates.JSONRenderer(), func(ctx *context.Context) {
  918. ctx.HTML(200, "pwa/manifest_json")
  919. })
  920. m.Get("/serviceworker.js", templates.JSRenderer(), func(ctx *context.Context) {
  921. ctx.HTML(200, "pwa/serviceworker_js")
  922. })
  923. // prometheus metrics endpoint
  924. if setting.Metrics.Enabled {
  925. c := metrics.NewCollector()
  926. prometheus.MustRegister(c)
  927. m.Get("/metrics", routers.Metrics)
  928. }
  929. // Not found handler.
  930. m.NotFound(routers.NotFound)
  931. }