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 41 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
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>
7 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
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>
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>
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>
6 years ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030
  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. "os"
  10. "path"
  11. "text/template"
  12. "time"
  13. "code.gitea.io/gitea/models"
  14. "code.gitea.io/gitea/modules/auth"
  15. "code.gitea.io/gitea/modules/context"
  16. "code.gitea.io/gitea/modules/lfs"
  17. "code.gitea.io/gitea/modules/log"
  18. "code.gitea.io/gitea/modules/metrics"
  19. "code.gitea.io/gitea/modules/options"
  20. "code.gitea.io/gitea/modules/public"
  21. "code.gitea.io/gitea/modules/setting"
  22. "code.gitea.io/gitea/modules/templates"
  23. "code.gitea.io/gitea/modules/validation"
  24. "code.gitea.io/gitea/routers"
  25. "code.gitea.io/gitea/routers/admin"
  26. apiv1 "code.gitea.io/gitea/routers/api/v1"
  27. "code.gitea.io/gitea/routers/dev"
  28. "code.gitea.io/gitea/routers/org"
  29. "code.gitea.io/gitea/routers/private"
  30. "code.gitea.io/gitea/routers/repo"
  31. "code.gitea.io/gitea/routers/user"
  32. userSetting "code.gitea.io/gitea/routers/user/setting"
  33. "code.gitea.io/gitea/services/mailer"
  34. // to registers all internal adapters
  35. _ "code.gitea.io/gitea/modules/session"
  36. "gitea.com/macaron/binding"
  37. "gitea.com/macaron/cache"
  38. "gitea.com/macaron/captcha"
  39. "gitea.com/macaron/cors"
  40. "gitea.com/macaron/csrf"
  41. "gitea.com/macaron/gzip"
  42. "gitea.com/macaron/i18n"
  43. "gitea.com/macaron/macaron"
  44. "gitea.com/macaron/session"
  45. "gitea.com/macaron/toolbox"
  46. "github.com/prometheus/client_golang/prometheus"
  47. "github.com/tstranex/u2f"
  48. )
  49. type routerLoggerOptions struct {
  50. Ctx *macaron.Context
  51. Identity *string
  52. Start *time.Time
  53. ResponseWriter *macaron.ResponseWriter
  54. }
  55. func setupAccessLogger(m *macaron.Macaron) {
  56. logger := log.GetLogger("access")
  57. logTemplate, _ := template.New("log").Parse(setting.AccessLogTemplate)
  58. m.Use(func(ctx *macaron.Context) {
  59. start := time.Now()
  60. ctx.Next()
  61. identity := "-"
  62. if val, ok := ctx.Data["SignedUserName"]; ok {
  63. if stringVal, ok := val.(string); ok && stringVal != "" {
  64. identity = stringVal
  65. }
  66. }
  67. rw := ctx.Resp.(macaron.ResponseWriter)
  68. buf := bytes.NewBuffer([]byte{})
  69. err := logTemplate.Execute(buf, routerLoggerOptions{
  70. Ctx: ctx,
  71. Identity: &identity,
  72. Start: &start,
  73. ResponseWriter: &rw,
  74. })
  75. if err != nil {
  76. log.Error("Could not set up macaron access logger: %v", err.Error())
  77. }
  78. err = logger.SendLog(log.INFO, "", "", 0, buf.String(), "")
  79. if err != nil {
  80. log.Error("Could not set up macaron access logger: %v", err.Error())
  81. }
  82. })
  83. }
  84. // RouterHandler is a macaron handler that will log the routing to the default gitea log
  85. func RouterHandler(level log.Level) func(ctx *macaron.Context) {
  86. return func(ctx *macaron.Context) {
  87. start := time.Now()
  88. _ = log.GetLogger("router").Log(0, level, "Started %s %s for %s", log.ColoredMethod(ctx.Req.Method), ctx.Req.RequestURI, ctx.RemoteAddr())
  89. rw := ctx.Resp.(macaron.ResponseWriter)
  90. ctx.Next()
  91. status := rw.Status()
  92. _ = log.GetLogger("router").Log(0, level, "Completed %s %s %v %s in %v", log.ColoredMethod(ctx.Req.Method), ctx.Req.RequestURI, log.ColoredStatus(status), log.ColoredStatus(status, http.StatusText(rw.Status())), log.ColoredTime(time.Since(start)))
  93. }
  94. }
  95. // NewMacaron initializes Macaron instance.
  96. func NewMacaron() *macaron.Macaron {
  97. gob.Register(&u2f.Challenge{})
  98. var m *macaron.Macaron
  99. if setting.RedirectMacaronLog {
  100. loggerAsWriter := log.NewLoggerAsWriter("INFO", log.GetLogger("macaron"))
  101. m = macaron.NewWithLogger(loggerAsWriter)
  102. if !setting.DisableRouterLog && setting.RouterLogLevel != log.NONE {
  103. if log.GetLogger("router").GetLevel() <= setting.RouterLogLevel {
  104. m.Use(RouterHandler(setting.RouterLogLevel))
  105. }
  106. }
  107. } else {
  108. m = macaron.New()
  109. if !setting.DisableRouterLog {
  110. m.Use(macaron.Logger())
  111. }
  112. }
  113. // Access Logger is similar to Router Log but more configurable and by default is more like the NCSA Common Log format
  114. if setting.EnableAccessLog {
  115. setupAccessLogger(m)
  116. }
  117. m.Use(macaron.Recovery())
  118. if setting.EnableGzip {
  119. m.Use(gzip.Middleware())
  120. }
  121. if setting.Protocol == setting.FCGI || setting.Protocol == setting.FCGIUnix {
  122. m.SetURLPrefix(setting.AppSubURL)
  123. }
  124. m.Use(public.Custom(
  125. &public.Options{
  126. SkipLogging: setting.DisableRouterLog,
  127. ExpiresAfter: setting.StaticCacheTime,
  128. },
  129. ))
  130. m.Use(public.Static(
  131. &public.Options{
  132. Directory: path.Join(setting.StaticRootPath, "public"),
  133. SkipLogging: setting.DisableRouterLog,
  134. ExpiresAfter: setting.StaticCacheTime,
  135. },
  136. ))
  137. m.Use(public.StaticHandler(
  138. setting.AvatarUploadPath,
  139. &public.Options{
  140. Prefix: "avatars",
  141. SkipLogging: setting.DisableRouterLog,
  142. ExpiresAfter: setting.StaticCacheTime,
  143. },
  144. ))
  145. m.Use(public.StaticHandler(
  146. setting.RepositoryAvatarUploadPath,
  147. &public.Options{
  148. Prefix: "repo-avatars",
  149. SkipLogging: setting.DisableRouterLog,
  150. ExpiresAfter: setting.StaticCacheTime,
  151. },
  152. ))
  153. m.Use(templates.HTMLRenderer())
  154. mailer.InitMailRender(templates.Mailer())
  155. localeNames, err := options.Dir("locale")
  156. if err != nil {
  157. log.Fatal("Failed to list locale files: %v", err)
  158. }
  159. localFiles := make(map[string][]byte)
  160. for _, name := range localeNames {
  161. localFiles[name], err = options.Locale(name)
  162. if err != nil {
  163. log.Fatal("Failed to load %s locale file. %v", name, err)
  164. }
  165. }
  166. m.Use(i18n.I18n(i18n.Options{
  167. SubURL: setting.AppSubURL,
  168. Files: localFiles,
  169. Langs: setting.Langs,
  170. Names: setting.Names,
  171. DefaultLang: "en-US",
  172. Redirect: false,
  173. CookieDomain: setting.SessionConfig.Domain,
  174. }))
  175. m.Use(cache.Cacher(cache.Options{
  176. Adapter: setting.CacheService.Adapter,
  177. AdapterConfig: setting.CacheService.Conn,
  178. Interval: setting.CacheService.Interval,
  179. }))
  180. m.Use(captcha.Captchaer(captcha.Options{
  181. SubURL: setting.AppSubURL,
  182. }))
  183. m.Use(session.Sessioner(setting.SessionConfig))
  184. m.Use(csrf.Csrfer(csrf.Options{
  185. Secret: setting.SecretKey,
  186. Cookie: setting.CSRFCookieName,
  187. SetCookie: true,
  188. Secure: setting.SessionConfig.Secure,
  189. CookieHttpOnly: setting.CSRFCookieHTTPOnly,
  190. Header: "X-Csrf-Token",
  191. CookieDomain: setting.SessionConfig.Domain,
  192. CookiePath: setting.AppSubURL,
  193. }))
  194. m.Use(toolbox.Toolboxer(m, toolbox.Options{
  195. HealthCheckFuncs: []*toolbox.HealthCheckFuncDesc{
  196. {
  197. Desc: "Database connection",
  198. Func: models.Ping,
  199. },
  200. },
  201. DisableDebug: !setting.EnablePprof,
  202. }))
  203. m.Use(context.Contexter())
  204. // OK we are now set-up enough to allow us to create a nicer recovery than
  205. // the default macaron recovery
  206. m.Use(context.Recovery())
  207. m.SetAutoHead(true)
  208. return m
  209. }
  210. // RegisterRoutes routes routes to Macaron
  211. func RegisterRoutes(m *macaron.Macaron) {
  212. reqSignIn := context.Toggle(&context.ToggleOptions{SignInRequired: true})
  213. ignSignIn := context.Toggle(&context.ToggleOptions{SignInRequired: setting.Service.RequireSignInView})
  214. ignSignInAndCsrf := context.Toggle(&context.ToggleOptions{DisableCSRF: true})
  215. reqSignOut := context.Toggle(&context.ToggleOptions{SignOutRequired: true})
  216. bindIgnErr := binding.BindIgnErr
  217. validation.AddBindingRules()
  218. openIDSignInEnabled := func(ctx *context.Context) {
  219. if !setting.Service.EnableOpenIDSignIn {
  220. ctx.Error(403)
  221. return
  222. }
  223. }
  224. openIDSignUpEnabled := func(ctx *context.Context) {
  225. if !setting.Service.EnableOpenIDSignUp {
  226. ctx.Error(403)
  227. return
  228. }
  229. }
  230. m.Use(user.GetNotificationCount)
  231. // FIXME: not all routes need go through same middlewares.
  232. // Especially some AJAX requests, we can reduce middleware number to improve performance.
  233. // Routers.
  234. // for health check
  235. m.Head("/", func() string {
  236. return ""
  237. })
  238. m.Get("/", routers.Home)
  239. m.Group("/explore", func() {
  240. m.Get("", func(ctx *context.Context) {
  241. ctx.Redirect(setting.AppSubURL + "/explore/repos")
  242. })
  243. m.Get("/repos", routers.ExploreRepos)
  244. m.Get("/users", routers.ExploreUsers)
  245. m.Get("/organizations", routers.ExploreOrganizations)
  246. m.Get("/code", routers.ExploreCode)
  247. }, ignSignIn)
  248. m.Combo("/install", routers.InstallInit).Get(routers.Install).
  249. Post(bindIgnErr(auth.InstallForm{}), routers.InstallPost)
  250. m.Get("/^:type(issues|pulls)$", reqSignIn, user.Issues)
  251. // ***** START: User *****
  252. m.Group("/user", func() {
  253. m.Get("/login", user.SignIn)
  254. m.Post("/login", bindIgnErr(auth.SignInForm{}), user.SignInPost)
  255. m.Group("", func() {
  256. m.Combo("/login/openid").
  257. Get(user.SignInOpenID).
  258. Post(bindIgnErr(auth.SignInOpenIDForm{}), user.SignInOpenIDPost)
  259. }, openIDSignInEnabled)
  260. m.Group("/openid", func() {
  261. m.Combo("/connect").
  262. Get(user.ConnectOpenID).
  263. Post(bindIgnErr(auth.ConnectOpenIDForm{}), user.ConnectOpenIDPost)
  264. m.Group("/register", func() {
  265. m.Combo("").
  266. Get(user.RegisterOpenID, openIDSignUpEnabled).
  267. Post(bindIgnErr(auth.SignUpOpenIDForm{}), user.RegisterOpenIDPost)
  268. }, openIDSignUpEnabled)
  269. }, openIDSignInEnabled)
  270. m.Get("/sign_up", user.SignUp)
  271. m.Post("/sign_up", bindIgnErr(auth.RegisterForm{}), user.SignUpPost)
  272. m.Group("/oauth2", func() {
  273. m.Get("/:provider", user.SignInOAuth)
  274. m.Get("/:provider/callback", user.SignInOAuthCallback)
  275. })
  276. m.Get("/link_account", user.LinkAccount)
  277. m.Post("/link_account_signin", bindIgnErr(auth.SignInForm{}), user.LinkAccountPostSignIn)
  278. m.Post("/link_account_signup", bindIgnErr(auth.RegisterForm{}), user.LinkAccountPostRegister)
  279. m.Group("/two_factor", func() {
  280. m.Get("", user.TwoFactor)
  281. m.Post("", bindIgnErr(auth.TwoFactorAuthForm{}), user.TwoFactorPost)
  282. m.Get("/scratch", user.TwoFactorScratch)
  283. m.Post("/scratch", bindIgnErr(auth.TwoFactorScratchAuthForm{}), user.TwoFactorScratchPost)
  284. })
  285. m.Group("/u2f", func() {
  286. m.Get("", user.U2F)
  287. m.Get("/challenge", user.U2FChallenge)
  288. m.Post("/sign", bindIgnErr(u2f.SignResponse{}), user.U2FSign)
  289. })
  290. }, reqSignOut)
  291. m.Group("/login/oauth", func() {
  292. m.Get("/authorize", bindIgnErr(auth.AuthorizationForm{}), user.AuthorizeOAuth)
  293. m.Post("/grant", bindIgnErr(auth.GrantApplicationForm{}), user.GrantApplicationOAuth)
  294. // TODO manage redirection
  295. m.Post("/authorize", bindIgnErr(auth.AuthorizationForm{}), user.AuthorizeOAuth)
  296. }, ignSignInAndCsrf, reqSignIn)
  297. m.Post("/login/oauth/access_token", bindIgnErr(auth.AccessTokenForm{}), ignSignInAndCsrf, user.AccessTokenOAuth)
  298. m.Group("/user/settings", func() {
  299. m.Get("", userSetting.Profile)
  300. m.Post("", bindIgnErr(auth.UpdateProfileForm{}), userSetting.ProfilePost)
  301. m.Get("/change_password", user.MustChangePassword)
  302. m.Post("/change_password", bindIgnErr(auth.MustChangePasswordForm{}), user.MustChangePasswordPost)
  303. m.Post("/avatar", binding.MultipartForm(auth.AvatarForm{}), userSetting.AvatarPost)
  304. m.Post("/avatar/delete", userSetting.DeleteAvatar)
  305. m.Group("/account", func() {
  306. m.Combo("").Get(userSetting.Account).Post(bindIgnErr(auth.ChangePasswordForm{}), userSetting.AccountPost)
  307. m.Post("/email", bindIgnErr(auth.AddEmailForm{}), userSetting.EmailPost)
  308. m.Post("/email/delete", userSetting.DeleteEmail)
  309. m.Post("/delete", userSetting.DeleteAccount)
  310. m.Post("/theme", bindIgnErr(auth.UpdateThemeForm{}), userSetting.UpdateUIThemePost)
  311. })
  312. m.Group("/security", func() {
  313. m.Get("", userSetting.Security)
  314. m.Group("/two_factor", func() {
  315. m.Post("/regenerate_scratch", userSetting.RegenerateScratchTwoFactor)
  316. m.Post("/disable", userSetting.DisableTwoFactor)
  317. m.Get("/enroll", userSetting.EnrollTwoFactor)
  318. m.Post("/enroll", bindIgnErr(auth.TwoFactorAuthForm{}), userSetting.EnrollTwoFactorPost)
  319. })
  320. m.Group("/u2f", func() {
  321. m.Post("/request_register", bindIgnErr(auth.U2FRegistrationForm{}), userSetting.U2FRegister)
  322. m.Post("/register", bindIgnErr(u2f.RegisterResponse{}), userSetting.U2FRegisterPost)
  323. m.Post("/delete", bindIgnErr(auth.U2FDeleteForm{}), userSetting.U2FDelete)
  324. })
  325. m.Group("/openid", func() {
  326. m.Post("", bindIgnErr(auth.AddOpenIDForm{}), userSetting.OpenIDPost)
  327. m.Post("/delete", userSetting.DeleteOpenID)
  328. m.Post("/toggle_visibility", userSetting.ToggleOpenIDVisibility)
  329. }, openIDSignInEnabled)
  330. m.Post("/account_link", userSetting.DeleteAccountLink)
  331. })
  332. m.Group("/applications/oauth2", func() {
  333. m.Get("/:id", userSetting.OAuth2ApplicationShow)
  334. m.Post("/:id", bindIgnErr(auth.EditOAuth2ApplicationForm{}), userSetting.OAuthApplicationsEdit)
  335. m.Post("/:id/regenerate_secret", userSetting.OAuthApplicationsRegenerateSecret)
  336. m.Post("", bindIgnErr(auth.EditOAuth2ApplicationForm{}), userSetting.OAuthApplicationsPost)
  337. m.Post("/delete", userSetting.DeleteOAuth2Application)
  338. m.Post("/revoke", userSetting.RevokeOAuth2Grant)
  339. })
  340. m.Combo("/applications").Get(userSetting.Applications).
  341. Post(bindIgnErr(auth.NewAccessTokenForm{}), userSetting.ApplicationsPost)
  342. m.Post("/applications/delete", userSetting.DeleteApplication)
  343. m.Combo("/keys").Get(userSetting.Keys).
  344. Post(bindIgnErr(auth.AddKeyForm{}), userSetting.KeysPost)
  345. m.Post("/keys/delete", userSetting.DeleteKey)
  346. m.Get("/organization", userSetting.Organization)
  347. m.Get("/repos", userSetting.Repos)
  348. // redirects from old settings urls to new ones
  349. // TODO: can be removed on next major version
  350. m.Get("/avatar", func(ctx *context.Context) {
  351. ctx.Redirect(setting.AppSubURL+"/user/settings", http.StatusMovedPermanently)
  352. })
  353. m.Get("/email", func(ctx *context.Context) {
  354. ctx.Redirect(setting.AppSubURL+"/user/settings/account", http.StatusMovedPermanently)
  355. })
  356. m.Get("/delete", func(ctx *context.Context) {
  357. ctx.Redirect(setting.AppSubURL+"/user/settings/account", http.StatusMovedPermanently)
  358. })
  359. m.Get("/openid", func(ctx *context.Context) {
  360. ctx.Redirect(setting.AppSubURL+"/user/settings/security", http.StatusMovedPermanently)
  361. })
  362. m.Get("/account_link", func(ctx *context.Context) {
  363. ctx.Redirect(setting.AppSubURL+"/user/settings/security", http.StatusMovedPermanently)
  364. })
  365. }, reqSignIn, func(ctx *context.Context) {
  366. ctx.Data["PageIsUserSettings"] = true
  367. ctx.Data["AllThemes"] = setting.UI.Themes
  368. })
  369. m.Group("/user", func() {
  370. // r.Get("/feeds", binding.Bind(auth.FeedsForm{}), user.Feeds)
  371. m.Any("/activate", user.Activate, reqSignIn)
  372. m.Any("/activate_email", user.ActivateEmail)
  373. m.Get("/avatar/:username/:size", user.Avatar)
  374. m.Get("/email2user", user.Email2User)
  375. m.Get("/recover_account", user.ResetPasswd)
  376. m.Post("/recover_account", user.ResetPasswdPost)
  377. m.Get("/forgot_password", user.ForgotPasswd)
  378. m.Post("/forgot_password", user.ForgotPasswdPost)
  379. m.Get("/logout", user.SignOut)
  380. })
  381. // ***** END: User *****
  382. adminReq := context.Toggle(&context.ToggleOptions{SignInRequired: true, AdminRequired: true})
  383. // ***** START: Admin *****
  384. m.Group("/admin", func() {
  385. m.Get("", adminReq, admin.Dashboard)
  386. m.Get("/config", admin.Config)
  387. m.Post("/config/test_mail", admin.SendTestMail)
  388. m.Get("/monitor", admin.Monitor)
  389. m.Post("/monitor/cancel/:pid", admin.MonitorCancel)
  390. m.Group("/users", func() {
  391. m.Get("", admin.Users)
  392. m.Combo("/new").Get(admin.NewUser).Post(bindIgnErr(auth.AdminCreateUserForm{}), admin.NewUserPost)
  393. m.Combo("/:userid").Get(admin.EditUser).Post(bindIgnErr(auth.AdminEditUserForm{}), admin.EditUserPost)
  394. m.Post("/:userid/delete", admin.DeleteUser)
  395. })
  396. m.Group("/orgs", func() {
  397. m.Get("", admin.Organizations)
  398. })
  399. m.Group("/repos", func() {
  400. m.Get("", admin.Repos)
  401. m.Post("/delete", admin.DeleteRepo)
  402. })
  403. m.Group("/hooks", func() {
  404. m.Get("", admin.DefaultWebhooks)
  405. m.Post("/delete", admin.DeleteDefaultWebhook)
  406. m.Get("/:type/new", repo.WebhooksNew)
  407. m.Post("/gitea/new", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksNewPost)
  408. m.Post("/gogs/new", bindIgnErr(auth.NewGogshookForm{}), repo.GogsHooksNewPost)
  409. m.Post("/slack/new", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksNewPost)
  410. m.Post("/discord/new", bindIgnErr(auth.NewDiscordHookForm{}), repo.DiscordHooksNewPost)
  411. m.Post("/dingtalk/new", bindIgnErr(auth.NewDingtalkHookForm{}), repo.DingtalkHooksNewPost)
  412. m.Post("/telegram/new", bindIgnErr(auth.NewTelegramHookForm{}), repo.TelegramHooksNewPost)
  413. m.Post("/msteams/new", bindIgnErr(auth.NewMSTeamsHookForm{}), repo.MSTeamsHooksNewPost)
  414. m.Get("/:id", repo.WebHooksEdit)
  415. m.Post("/gitea/:id", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksEditPost)
  416. m.Post("/gogs/:id", bindIgnErr(auth.NewGogshookForm{}), repo.GogsHooksEditPost)
  417. m.Post("/slack/:id", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksEditPost)
  418. m.Post("/discord/:id", bindIgnErr(auth.NewDiscordHookForm{}), repo.DiscordHooksEditPost)
  419. m.Post("/dingtalk/:id", bindIgnErr(auth.NewDingtalkHookForm{}), repo.DingtalkHooksEditPost)
  420. m.Post("/telegram/:id", bindIgnErr(auth.NewTelegramHookForm{}), repo.TelegramHooksEditPost)
  421. m.Post("/msteams/:id", bindIgnErr(auth.NewMSTeamsHookForm{}), repo.MSTeamsHooksNewPost)
  422. })
  423. m.Group("/auths", func() {
  424. m.Get("", admin.Authentications)
  425. m.Combo("/new").Get(admin.NewAuthSource).Post(bindIgnErr(auth.AuthenticationForm{}), admin.NewAuthSourcePost)
  426. m.Combo("/:authid").Get(admin.EditAuthSource).
  427. Post(bindIgnErr(auth.AuthenticationForm{}), admin.EditAuthSourcePost)
  428. m.Post("/:authid/delete", admin.DeleteAuthSource)
  429. })
  430. m.Group("/notices", func() {
  431. m.Get("", admin.Notices)
  432. m.Post("/delete", admin.DeleteNotices)
  433. m.Get("/empty", admin.EmptyNotices)
  434. })
  435. }, adminReq)
  436. // ***** END: Admin *****
  437. m.Group("", func() {
  438. m.Group("/:username", func() {
  439. m.Get("", user.Profile)
  440. m.Get("/followers", user.Followers)
  441. m.Get("/following", user.Following)
  442. })
  443. m.Get("/attachments/:uuid", func(ctx *context.Context) {
  444. attach, err := models.GetAttachmentByUUID(ctx.Params(":uuid"))
  445. if err != nil {
  446. if models.IsErrAttachmentNotExist(err) {
  447. ctx.Error(404)
  448. } else {
  449. ctx.ServerError("GetAttachmentByUUID", err)
  450. }
  451. return
  452. }
  453. fr, err := os.Open(attach.LocalPath())
  454. if err != nil {
  455. ctx.ServerError("Open", err)
  456. return
  457. }
  458. defer fr.Close()
  459. if err := attach.IncreaseDownloadCount(); err != nil {
  460. ctx.ServerError("Update", err)
  461. return
  462. }
  463. if err = repo.ServeData(ctx, attach.Name, fr); err != nil {
  464. ctx.ServerError("ServeData", err)
  465. return
  466. }
  467. })
  468. }, ignSignIn)
  469. m.Group("/attachments", func() {
  470. m.Post("", repo.UploadAttachment)
  471. m.Post("/delete", repo.DeleteAttachment)
  472. }, reqSignIn)
  473. m.Group("/:username", func() {
  474. m.Get("/action/:action", user.Action)
  475. }, reqSignIn)
  476. if macaron.Env == macaron.DEV {
  477. m.Get("/template/*", dev.TemplatePreview)
  478. }
  479. reqRepoAdmin := context.RequireRepoAdmin()
  480. reqRepoCodeWriter := context.RequireRepoWriter(models.UnitTypeCode)
  481. reqRepoCodeReader := context.RequireRepoReader(models.UnitTypeCode)
  482. reqRepoReleaseWriter := context.RequireRepoWriter(models.UnitTypeReleases)
  483. reqRepoReleaseReader := context.RequireRepoReader(models.UnitTypeReleases)
  484. reqRepoWikiWriter := context.RequireRepoWriter(models.UnitTypeWiki)
  485. reqRepoIssueReader := context.RequireRepoReader(models.UnitTypeIssues)
  486. reqRepoPullsWriter := context.RequireRepoWriter(models.UnitTypePullRequests)
  487. reqRepoPullsReader := context.RequireRepoReader(models.UnitTypePullRequests)
  488. reqRepoIssuesOrPullsWriter := context.RequireRepoWriterOr(models.UnitTypeIssues, models.UnitTypePullRequests)
  489. reqRepoIssuesOrPullsReader := context.RequireRepoReaderOr(models.UnitTypeIssues, models.UnitTypePullRequests)
  490. reqRepoIssueWriter := func(ctx *context.Context) {
  491. if !ctx.Repo.CanWrite(models.UnitTypeIssues) {
  492. ctx.Error(403)
  493. return
  494. }
  495. }
  496. // ***** START: Organization *****
  497. m.Group("/org", func() {
  498. m.Group("", func() {
  499. m.Get("/create", org.Create)
  500. m.Post("/create", bindIgnErr(auth.CreateOrgForm{}), org.CreatePost)
  501. })
  502. m.Group("/:org", func() {
  503. m.Get("/dashboard", user.Dashboard)
  504. m.Get("/^:type(issues|pulls)$", user.Issues)
  505. m.Get("/members", org.Members)
  506. m.Get("/members/action/:action", org.MembersAction)
  507. m.Get("/teams", org.Teams)
  508. }, context.OrgAssignment(true))
  509. m.Group("/:org", func() {
  510. m.Get("/teams/:team", org.TeamMembers)
  511. m.Get("/teams/:team/repositories", org.TeamRepositories)
  512. m.Route("/teams/:team/action/:action", "GET,POST", org.TeamsAction)
  513. m.Route("/teams/:team/action/repo/:action", "GET,POST", org.TeamsRepoAction)
  514. }, context.OrgAssignment(true, false, true))
  515. m.Group("/:org", func() {
  516. m.Get("/teams/new", org.NewTeam)
  517. m.Post("/teams/new", bindIgnErr(auth.CreateTeamForm{}), org.NewTeamPost)
  518. m.Get("/teams/:team/edit", org.EditTeam)
  519. m.Post("/teams/:team/edit", bindIgnErr(auth.CreateTeamForm{}), org.EditTeamPost)
  520. m.Post("/teams/:team/delete", org.DeleteTeam)
  521. m.Group("/settings", func() {
  522. m.Combo("").Get(org.Settings).
  523. Post(bindIgnErr(auth.UpdateOrgSettingForm{}), org.SettingsPost)
  524. m.Post("/avatar", binding.MultipartForm(auth.AvatarForm{}), org.SettingsAvatar)
  525. m.Post("/avatar/delete", org.SettingsDeleteAvatar)
  526. m.Group("/hooks", func() {
  527. m.Get("", org.Webhooks)
  528. m.Post("/delete", org.DeleteWebhook)
  529. m.Get("/:type/new", repo.WebhooksNew)
  530. m.Post("/gitea/new", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksNewPost)
  531. m.Post("/gogs/new", bindIgnErr(auth.NewGogshookForm{}), repo.GogsHooksNewPost)
  532. m.Post("/slack/new", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksNewPost)
  533. m.Post("/discord/new", bindIgnErr(auth.NewDiscordHookForm{}), repo.DiscordHooksNewPost)
  534. m.Post("/dingtalk/new", bindIgnErr(auth.NewDingtalkHookForm{}), repo.DingtalkHooksNewPost)
  535. m.Post("/telegram/new", bindIgnErr(auth.NewTelegramHookForm{}), repo.TelegramHooksNewPost)
  536. m.Get("/:id", repo.WebHooksEdit)
  537. m.Post("/gitea/:id", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksEditPost)
  538. m.Post("/gogs/:id", bindIgnErr(auth.NewGogshookForm{}), repo.GogsHooksEditPost)
  539. m.Post("/slack/:id", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksEditPost)
  540. m.Post("/discord/:id", bindIgnErr(auth.NewDiscordHookForm{}), repo.DiscordHooksEditPost)
  541. m.Post("/dingtalk/:id", bindIgnErr(auth.NewDingtalkHookForm{}), repo.DingtalkHooksEditPost)
  542. m.Post("/telegram/:id", bindIgnErr(auth.NewTelegramHookForm{}), repo.TelegramHooksEditPost)
  543. })
  544. m.Route("/delete", "GET,POST", org.SettingsDelete)
  545. })
  546. }, context.OrgAssignment(true, true))
  547. }, reqSignIn)
  548. // ***** END: Organization *****
  549. // ***** START: Repository *****
  550. m.Group("/repo", func() {
  551. m.Get("/create", repo.Create)
  552. m.Post("/create", bindIgnErr(auth.CreateRepoForm{}), repo.CreatePost)
  553. m.Get("/migrate", repo.Migrate)
  554. m.Post("/migrate", bindIgnErr(auth.MigrateRepoForm{}), repo.MigratePost)
  555. m.Group("/fork", func() {
  556. m.Combo("/:repoid").Get(repo.Fork).
  557. Post(bindIgnErr(auth.CreateRepoForm{}), repo.ForkPost)
  558. }, context.RepoIDAssignment(), context.UnitTypes(), reqRepoCodeReader)
  559. }, reqSignIn)
  560. // ***** Release Attachment Download without Signin
  561. m.Get("/:username/:reponame/releases/download/:vTag/:fileName", ignSignIn, context.RepoAssignment(), repo.MustBeNotEmpty, repo.RedirectDownload)
  562. m.Group("/:username/:reponame", func() {
  563. m.Group("/settings", func() {
  564. m.Combo("").Get(repo.Settings).
  565. Post(bindIgnErr(auth.RepoSettingForm{}), repo.SettingsPost)
  566. m.Post("/avatar", binding.MultipartForm(auth.AvatarForm{}), repo.SettingsAvatar)
  567. m.Post("/avatar/delete", repo.SettingsDeleteAvatar)
  568. m.Group("/collaboration", func() {
  569. m.Combo("").Get(repo.Collaboration).Post(repo.CollaborationPost)
  570. m.Post("/access_mode", repo.ChangeCollaborationAccessMode)
  571. m.Post("/delete", repo.DeleteCollaboration)
  572. m.Group("/team", func() {
  573. m.Post("", repo.AddTeamPost)
  574. m.Post("/delete", repo.DeleteTeam)
  575. })
  576. })
  577. m.Group("/branches", func() {
  578. m.Combo("").Get(repo.ProtectedBranch).Post(repo.ProtectedBranchPost)
  579. m.Combo("/*").Get(repo.SettingsProtectedBranch).
  580. Post(bindIgnErr(auth.ProtectBranchForm{}), context.RepoMustNotBeArchived(), repo.SettingsProtectedBranchPost)
  581. }, repo.MustBeNotEmpty)
  582. m.Group("/hooks", func() {
  583. m.Get("", repo.Webhooks)
  584. m.Post("/delete", repo.DeleteWebhook)
  585. m.Get("/:type/new", repo.WebhooksNew)
  586. m.Post("/gitea/new", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksNewPost)
  587. m.Post("/gogs/new", bindIgnErr(auth.NewGogshookForm{}), repo.GogsHooksNewPost)
  588. m.Post("/slack/new", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksNewPost)
  589. m.Post("/discord/new", bindIgnErr(auth.NewDiscordHookForm{}), repo.DiscordHooksNewPost)
  590. m.Post("/dingtalk/new", bindIgnErr(auth.NewDingtalkHookForm{}), repo.DingtalkHooksNewPost)
  591. m.Post("/telegram/new", bindIgnErr(auth.NewTelegramHookForm{}), repo.TelegramHooksNewPost)
  592. m.Post("/msteams/new", bindIgnErr(auth.NewMSTeamsHookForm{}), repo.MSTeamsHooksNewPost)
  593. m.Get("/:id", repo.WebHooksEdit)
  594. m.Post("/:id/test", repo.TestWebhook)
  595. m.Post("/gitea/:id", bindIgnErr(auth.NewWebhookForm{}), repo.WebHooksEditPost)
  596. m.Post("/gogs/:id", bindIgnErr(auth.NewGogshookForm{}), repo.GogsHooksEditPost)
  597. m.Post("/slack/:id", bindIgnErr(auth.NewSlackHookForm{}), repo.SlackHooksEditPost)
  598. m.Post("/discord/:id", bindIgnErr(auth.NewDiscordHookForm{}), repo.DiscordHooksEditPost)
  599. m.Post("/dingtalk/:id", bindIgnErr(auth.NewDingtalkHookForm{}), repo.DingtalkHooksEditPost)
  600. m.Post("/telegram/:id", bindIgnErr(auth.NewTelegramHookForm{}), repo.TelegramHooksEditPost)
  601. m.Post("/msteams/:id", bindIgnErr(auth.NewMSTeamsHookForm{}), repo.MSTeamsHooksEditPost)
  602. m.Group("/git", func() {
  603. m.Get("", repo.GitHooks)
  604. m.Combo("/:name").Get(repo.GitHooksEdit).
  605. Post(repo.GitHooksEditPost)
  606. }, context.GitHookService())
  607. })
  608. m.Group("/keys", func() {
  609. m.Combo("").Get(repo.DeployKeys).
  610. Post(bindIgnErr(auth.AddKeyForm{}), repo.DeployKeysPost)
  611. m.Post("/delete", repo.DeleteDeployKey)
  612. })
  613. m.Group("/lfs", func() {
  614. m.Get("", repo.LFSFiles)
  615. m.Get("/show/:oid", repo.LFSFileGet)
  616. m.Post("/delete/:oid", repo.LFSDelete)
  617. m.Get("/pointers", repo.LFSPointerFiles)
  618. m.Post("/pointers/associate", repo.LFSAutoAssociate)
  619. m.Get("/find", repo.LFSFileFind)
  620. m.Group("/locks", func() {
  621. m.Get("/", repo.LFSLocks)
  622. m.Post("/", repo.LFSLockFile)
  623. m.Post("/:lid/unlock", repo.LFSUnlock)
  624. })
  625. })
  626. }, func(ctx *context.Context) {
  627. ctx.Data["PageIsSettings"] = true
  628. ctx.Data["LFSStartServer"] = setting.LFS.StartServer
  629. })
  630. }, reqSignIn, context.RepoAssignment(), context.UnitTypes(), reqRepoAdmin, context.RepoRef())
  631. m.Get("/:username/:reponame/action/:action", reqSignIn, context.RepoAssignment(), context.UnitTypes(), repo.Action)
  632. m.Group("/:username/:reponame", func() {
  633. m.Group("/issues", func() {
  634. m.Combo("/new").Get(context.RepoRef(), repo.NewIssue).
  635. Post(bindIgnErr(auth.CreateIssueForm{}), repo.NewIssuePost)
  636. }, context.RepoMustNotBeArchived(), reqRepoIssueReader)
  637. // FIXME: should use different URLs but mostly same logic for comments of issue and pull reuqest.
  638. // So they can apply their own enable/disable logic on routers.
  639. m.Group("/issues", func() {
  640. m.Group("/:index", func() {
  641. m.Post("/title", repo.UpdateIssueTitle)
  642. m.Post("/content", repo.UpdateIssueContent)
  643. m.Post("/watch", repo.IssueWatch)
  644. m.Group("/dependency", func() {
  645. m.Post("/add", repo.AddDependency)
  646. m.Post("/delete", repo.RemoveDependency)
  647. })
  648. m.Combo("/comments").Post(repo.MustAllowUserComment, bindIgnErr(auth.CreateCommentForm{}), repo.NewComment)
  649. m.Group("/times", func() {
  650. m.Post("/add", bindIgnErr(auth.AddTimeManuallyForm{}), repo.AddTimeManually)
  651. m.Group("/stopwatch", func() {
  652. m.Post("/toggle", repo.IssueStopwatch)
  653. m.Post("/cancel", repo.CancelStopwatch)
  654. })
  655. })
  656. m.Post("/reactions/:action", bindIgnErr(auth.ReactionForm{}), repo.ChangeIssueReaction)
  657. m.Post("/lock", reqRepoIssueWriter, bindIgnErr(auth.IssueLockForm{}), repo.LockIssue)
  658. m.Post("/unlock", reqRepoIssueWriter, repo.UnlockIssue)
  659. m.Get("/attachments", repo.GetIssueAttachments)
  660. }, context.RepoMustNotBeArchived())
  661. m.Post("/labels", reqRepoIssuesOrPullsWriter, repo.UpdateIssueLabel)
  662. m.Post("/milestone", reqRepoIssuesOrPullsWriter, repo.UpdateIssueMilestone)
  663. m.Post("/assignee", reqRepoIssuesOrPullsWriter, repo.UpdateIssueAssignee)
  664. m.Post("/status", reqRepoIssuesOrPullsWriter, repo.UpdateIssueStatus)
  665. }, context.RepoMustNotBeArchived())
  666. m.Group("/comments/:id", func() {
  667. m.Post("", repo.UpdateCommentContent)
  668. m.Post("/delete", repo.DeleteComment)
  669. m.Post("/reactions/:action", bindIgnErr(auth.ReactionForm{}), repo.ChangeCommentReaction)
  670. m.Get("/attachments", repo.GetCommentAttachments)
  671. }, context.RepoMustNotBeArchived())
  672. m.Group("/labels", func() {
  673. m.Post("/new", bindIgnErr(auth.CreateLabelForm{}), repo.NewLabel)
  674. m.Post("/edit", bindIgnErr(auth.CreateLabelForm{}), repo.UpdateLabel)
  675. m.Post("/delete", repo.DeleteLabel)
  676. m.Post("/initialize", bindIgnErr(auth.InitializeLabelsForm{}), repo.InitializeLabels)
  677. }, context.RepoMustNotBeArchived(), reqRepoIssuesOrPullsWriter, context.RepoRef())
  678. m.Group("/milestones", func() {
  679. m.Combo("/new").Get(repo.NewMilestone).
  680. Post(bindIgnErr(auth.CreateMilestoneForm{}), repo.NewMilestonePost)
  681. m.Get("/:id/edit", repo.EditMilestone)
  682. m.Post("/:id/edit", bindIgnErr(auth.CreateMilestoneForm{}), repo.EditMilestonePost)
  683. m.Get("/:id/:action", repo.ChangeMilestonStatus)
  684. m.Post("/delete", repo.DeleteMilestone)
  685. }, context.RepoMustNotBeArchived(), reqRepoIssuesOrPullsWriter, context.RepoRef())
  686. m.Group("/milestone", func() {
  687. m.Get("/:id", repo.MilestoneIssuesAndPulls)
  688. }, reqRepoIssuesOrPullsReader, context.RepoRef())
  689. m.Combo("/compare/*", repo.MustBeNotEmpty, reqRepoCodeReader, repo.SetEditorconfigIfExists).
  690. Get(repo.SetDiffViewStyle, repo.CompareDiff).
  691. Post(context.RepoMustNotBeArchived(), reqRepoPullsReader, repo.MustAllowPulls, bindIgnErr(auth.CreateIssueForm{}), repo.CompareAndPullRequestPost)
  692. m.Group("", func() {
  693. m.Group("", func() {
  694. m.Combo("/_edit/*").Get(repo.EditFile).
  695. Post(bindIgnErr(auth.EditRepoFileForm{}), repo.EditFilePost)
  696. m.Combo("/_new/*").Get(repo.NewFile).
  697. Post(bindIgnErr(auth.EditRepoFileForm{}), repo.NewFilePost)
  698. m.Post("/_preview/*", bindIgnErr(auth.EditPreviewDiffForm{}), repo.DiffPreviewPost)
  699. m.Combo("/_delete/*").Get(repo.DeleteFile).
  700. Post(bindIgnErr(auth.DeleteRepoFileForm{}), repo.DeleteFilePost)
  701. m.Combo("/_upload/*", repo.MustBeAbleToUpload).
  702. Get(repo.UploadFile).
  703. Post(bindIgnErr(auth.UploadRepoFileForm{}), repo.UploadFilePost)
  704. }, context.RepoRefByType(context.RepoRefBranch), repo.MustBeEditable)
  705. m.Group("", func() {
  706. m.Post("/upload-file", repo.UploadFileToServer)
  707. m.Post("/upload-remove", bindIgnErr(auth.RemoveUploadFileForm{}), repo.RemoveUploadFileFromServer)
  708. }, context.RepoRef(), repo.MustBeEditable, repo.MustBeAbleToUpload)
  709. }, context.RepoMustNotBeArchived(), reqRepoCodeWriter, repo.MustBeNotEmpty)
  710. m.Group("/branches", func() {
  711. m.Group("/_new/", func() {
  712. m.Post("/branch/*", context.RepoRefByType(context.RepoRefBranch), repo.CreateBranch)
  713. m.Post("/tag/*", context.RepoRefByType(context.RepoRefTag), repo.CreateBranch)
  714. m.Post("/commit/*", context.RepoRefByType(context.RepoRefCommit), repo.CreateBranch)
  715. }, bindIgnErr(auth.NewBranchForm{}))
  716. m.Post("/delete", repo.DeleteBranchPost)
  717. m.Post("/restore", repo.RestoreBranchPost)
  718. }, context.RepoMustNotBeArchived(), reqRepoCodeWriter, repo.MustBeNotEmpty)
  719. }, reqSignIn, context.RepoAssignment(), context.UnitTypes())
  720. // Releases
  721. m.Group("/:username/:reponame", func() {
  722. m.Group("/releases", func() {
  723. m.Get("/", repo.MustBeNotEmpty, repo.Releases)
  724. }, repo.MustBeNotEmpty, context.RepoRef())
  725. m.Group("/releases", func() {
  726. m.Get("/new", repo.NewRelease)
  727. m.Post("/new", bindIgnErr(auth.NewReleaseForm{}), repo.NewReleasePost)
  728. m.Post("/delete", repo.DeleteRelease)
  729. }, reqSignIn, repo.MustBeNotEmpty, context.RepoMustNotBeArchived(), reqRepoReleaseWriter, context.RepoRef())
  730. m.Group("/releases", func() {
  731. m.Get("/edit/*", repo.EditRelease)
  732. m.Post("/edit/*", bindIgnErr(auth.EditReleaseForm{}), repo.EditReleasePost)
  733. }, reqSignIn, repo.MustBeNotEmpty, context.RepoMustNotBeArchived(), reqRepoReleaseWriter, func(ctx *context.Context) {
  734. var err error
  735. ctx.Repo.Commit, err = ctx.Repo.GitRepo.GetBranchCommit(ctx.Repo.Repository.DefaultBranch)
  736. if err != nil {
  737. ctx.ServerError("GetBranchCommit", err)
  738. return
  739. }
  740. ctx.Repo.CommitsCount, err = ctx.Repo.GetCommitsCount()
  741. if err != nil {
  742. ctx.ServerError("GetCommitsCount", err)
  743. return
  744. }
  745. ctx.Data["CommitsCount"] = ctx.Repo.CommitsCount
  746. })
  747. }, ignSignIn, context.RepoAssignment(), context.UnitTypes(), reqRepoReleaseReader)
  748. m.Group("/:username/:reponame", func() {
  749. m.Post("/topics", repo.TopicsPost)
  750. }, context.RepoAssignment(), context.RepoMustNotBeArchived(), reqRepoAdmin)
  751. m.Group("/:username/:reponame", func() {
  752. m.Group("", func() {
  753. m.Get("/^:type(issues|pulls)$", repo.Issues)
  754. m.Get("/^:type(issues|pulls)$/:index", repo.ViewIssue)
  755. m.Get("/labels/", reqRepoIssuesOrPullsReader, repo.RetrieveLabels, repo.Labels)
  756. m.Get("/milestones", reqRepoIssuesOrPullsReader, repo.Milestones)
  757. }, context.RepoRef())
  758. m.Group("/wiki", func() {
  759. m.Get("/?:page", repo.Wiki)
  760. m.Get("/_pages", repo.WikiPages)
  761. m.Get("/:page/_revision", repo.WikiRevision)
  762. m.Group("", func() {
  763. m.Combo("/_new").Get(repo.NewWiki).
  764. Post(bindIgnErr(auth.NewWikiForm{}), repo.NewWikiPost)
  765. m.Combo("/:page/_edit").Get(repo.EditWiki).
  766. Post(bindIgnErr(auth.NewWikiForm{}), repo.EditWikiPost)
  767. m.Post("/:page/delete", repo.DeleteWikiPagePost)
  768. }, context.RepoMustNotBeArchived(), reqSignIn, reqRepoWikiWriter)
  769. }, repo.MustEnableWiki, context.RepoRef())
  770. m.Group("/wiki", func() {
  771. m.Get("/raw/*", repo.WikiRaw)
  772. }, repo.MustEnableWiki)
  773. m.Group("/activity", func() {
  774. m.Get("", repo.Activity)
  775. m.Get("/:period", repo.Activity)
  776. }, context.RepoRef(), repo.MustBeNotEmpty, context.RequireRepoReaderOr(models.UnitTypePullRequests, models.UnitTypeIssues, models.UnitTypeReleases))
  777. m.Group("/activity_author_data", func() {
  778. m.Get("", repo.ActivityAuthors)
  779. m.Get("/:period", repo.ActivityAuthors)
  780. }, context.RepoRef(), repo.MustBeNotEmpty, context.RequireRepoReaderOr(models.UnitTypeCode))
  781. m.Get("/archive/*", repo.MustBeNotEmpty, reqRepoCodeReader, repo.Download)
  782. m.Get("/status", reqRepoCodeReader, repo.Status)
  783. m.Group("/branches", func() {
  784. m.Get("", repo.Branches)
  785. }, repo.MustBeNotEmpty, context.RepoRef(), reqRepoCodeReader)
  786. m.Group("/blob_excerpt", func() {
  787. m.Get("/:sha", repo.SetEditorconfigIfExists, repo.SetDiffViewStyle, repo.ExcerptBlob)
  788. }, repo.MustBeNotEmpty, context.RepoRef(), reqRepoCodeReader)
  789. m.Group("/pulls/:index", func() {
  790. m.Get(".diff", repo.DownloadPullDiff)
  791. m.Get(".patch", repo.DownloadPullPatch)
  792. m.Get("/commits", context.RepoRef(), repo.ViewPullCommits)
  793. m.Post("/merge", context.RepoMustNotBeArchived(), reqRepoPullsWriter, bindIgnErr(auth.MergePullRequestForm{}), repo.MergePullRequest)
  794. m.Post("/cleanup", context.RepoMustNotBeArchived(), context.RepoRef(), repo.CleanUpPullRequest)
  795. m.Group("/files", func() {
  796. m.Get("", context.RepoRef(), repo.SetEditorconfigIfExists, repo.SetDiffViewStyle, repo.SetWhitespaceBehavior, repo.ViewPullFiles)
  797. m.Group("/reviews", func() {
  798. m.Post("/comments", bindIgnErr(auth.CodeCommentForm{}), repo.CreateCodeComment)
  799. m.Post("/submit", bindIgnErr(auth.SubmitReviewForm{}), repo.SubmitReview)
  800. }, context.RepoMustNotBeArchived())
  801. })
  802. }, repo.MustAllowPulls)
  803. m.Group("/media", func() {
  804. m.Get("/branch/*", context.RepoRefByType(context.RepoRefBranch), repo.SingleDownloadOrLFS)
  805. m.Get("/tag/*", context.RepoRefByType(context.RepoRefTag), repo.SingleDownloadOrLFS)
  806. m.Get("/commit/*", context.RepoRefByType(context.RepoRefCommit), repo.SingleDownloadOrLFS)
  807. m.Get("/blob/:sha", context.RepoRefByType(context.RepoRefBlob), repo.DownloadByIDOrLFS)
  808. // "/*" route is deprecated, and kept for backward compatibility
  809. m.Get("/*", context.RepoRefByType(context.RepoRefLegacy), repo.SingleDownloadOrLFS)
  810. }, repo.MustBeNotEmpty, reqRepoCodeReader)
  811. m.Group("/raw", func() {
  812. m.Get("/branch/*", context.RepoRefByType(context.RepoRefBranch), repo.SingleDownload)
  813. m.Get("/tag/*", context.RepoRefByType(context.RepoRefTag), repo.SingleDownload)
  814. m.Get("/commit/*", context.RepoRefByType(context.RepoRefCommit), repo.SingleDownload)
  815. m.Get("/blob/:sha", context.RepoRefByType(context.RepoRefBlob), repo.DownloadByID)
  816. // "/*" route is deprecated, and kept for backward compatibility
  817. m.Get("/*", context.RepoRefByType(context.RepoRefLegacy), repo.SingleDownload)
  818. }, repo.MustBeNotEmpty, reqRepoCodeReader)
  819. m.Group("/commits", func() {
  820. m.Get("/branch/*", context.RepoRefByType(context.RepoRefBranch), repo.RefCommits)
  821. m.Get("/tag/*", context.RepoRefByType(context.RepoRefTag), repo.RefCommits)
  822. m.Get("/commit/*", context.RepoRefByType(context.RepoRefCommit), repo.RefCommits)
  823. // "/*" route is deprecated, and kept for backward compatibility
  824. m.Get("/*", context.RepoRefByType(context.RepoRefLegacy), repo.RefCommits)
  825. }, repo.MustBeNotEmpty, reqRepoCodeReader)
  826. m.Group("/blame", func() {
  827. m.Get("/branch/*", context.RepoRefByType(context.RepoRefBranch), repo.RefBlame)
  828. m.Get("/tag/*", context.RepoRefByType(context.RepoRefTag), repo.RefBlame)
  829. m.Get("/commit/*", context.RepoRefByType(context.RepoRefCommit), repo.RefBlame)
  830. }, repo.MustBeNotEmpty, reqRepoCodeReader)
  831. m.Group("", func() {
  832. m.Get("/graph", repo.Graph)
  833. m.Get("/commit/:sha([a-f0-9]{7,40})$", repo.SetEditorconfigIfExists, repo.SetDiffViewStyle, repo.Diff)
  834. }, repo.MustBeNotEmpty, context.RepoRef(), reqRepoCodeReader)
  835. m.Group("/src", func() {
  836. m.Get("/branch/*", context.RepoRefByType(context.RepoRefBranch), repo.Home)
  837. m.Get("/tag/*", context.RepoRefByType(context.RepoRefTag), repo.Home)
  838. m.Get("/commit/*", context.RepoRefByType(context.RepoRefCommit), repo.Home)
  839. // "/*" route is deprecated, and kept for backward compatibility
  840. m.Get("/*", context.RepoRefByType(context.RepoRefLegacy), repo.Home)
  841. }, repo.SetEditorconfigIfExists)
  842. m.Group("", func() {
  843. m.Get("/forks", repo.Forks)
  844. }, context.RepoRef(), reqRepoCodeReader)
  845. m.Get("/commit/:sha([a-f0-9]{7,40})\\.:ext(patch|diff)",
  846. repo.MustBeNotEmpty, reqRepoCodeReader, repo.RawDiff)
  847. }, ignSignIn, context.RepoAssignment(), context.UnitTypes())
  848. m.Group("/:username/:reponame", func() {
  849. m.Get("/stars", repo.Stars)
  850. m.Get("/watchers", repo.Watchers)
  851. m.Get("/search", reqRepoCodeReader, repo.Search)
  852. }, ignSignIn, context.RepoAssignment(), context.RepoRef(), context.UnitTypes())
  853. m.Group("/:username", func() {
  854. m.Group("/:reponame", func() {
  855. m.Get("", repo.SetEditorconfigIfExists, repo.Home)
  856. m.Get("\\.git$", repo.SetEditorconfigIfExists, repo.Home)
  857. }, ignSignIn, context.RepoAssignment(), context.RepoRef(), context.UnitTypes())
  858. m.Group("/:reponame", func() {
  859. m.Group("\\.git/info/lfs", func() {
  860. m.Post("/objects/batch", lfs.BatchHandler)
  861. m.Get("/objects/:oid/:filename", lfs.ObjectOidHandler)
  862. m.Any("/objects/:oid", lfs.ObjectOidHandler)
  863. m.Post("/objects", lfs.PostHandler)
  864. m.Post("/verify", lfs.VerifyHandler)
  865. m.Group("/locks", func() {
  866. m.Get("/", lfs.GetListLockHandler)
  867. m.Post("/", lfs.PostLockHandler)
  868. m.Post("/verify", lfs.VerifyLockHandler)
  869. m.Post("/:lid/unlock", lfs.UnLockHandler)
  870. })
  871. m.Any("/*", func(ctx *context.Context) {
  872. ctx.NotFound("", nil)
  873. })
  874. }, ignSignInAndCsrf)
  875. m.Any("/*", ignSignInAndCsrf, repo.HTTP)
  876. m.Head("/tasks/trigger", repo.TriggerTask)
  877. })
  878. })
  879. // ***** END: Repository *****
  880. m.Group("/notifications", func() {
  881. m.Get("", user.Notifications)
  882. m.Post("/status", user.NotificationStatusPost)
  883. m.Post("/purge", user.NotificationPurgePost)
  884. }, reqSignIn)
  885. if setting.API.EnableSwagger {
  886. m.Get("/swagger.v1.json", templates.JSONRenderer(), routers.SwaggerV1Json)
  887. }
  888. var handlers []macaron.Handler
  889. if setting.EnableCORS {
  890. handlers = append(handlers, cors.CORS(setting.CORSConfig))
  891. }
  892. handlers = append(handlers, ignSignIn)
  893. m.Group("/api", func() {
  894. apiv1.RegisterRoutes(m)
  895. }, handlers...)
  896. m.Group("/api/internal", func() {
  897. // package name internal is ideal but Golang is not allowed, so we use private as package name.
  898. private.RegisterRoutes(m)
  899. })
  900. // robots.txt
  901. m.Get("/robots.txt", func(ctx *context.Context) {
  902. if setting.HasRobotsTxt {
  903. ctx.ServeFileContent(path.Join(setting.CustomPath, "robots.txt"))
  904. } else {
  905. ctx.NotFound("", nil)
  906. }
  907. })
  908. // Progressive Web App
  909. m.Get("/manifest.json", templates.JSONRenderer(), func(ctx *context.Context) {
  910. ctx.HTML(200, "pwa/manifest_json")
  911. })
  912. m.Get("/serviceworker.js", templates.JSRenderer(), func(ctx *context.Context) {
  913. ctx.HTML(200, "pwa/serviceworker_js")
  914. })
  915. // prometheus metrics endpoint
  916. if setting.Metrics.Enabled {
  917. c := metrics.NewCollector()
  918. prometheus.MustRegister(c)
  919. m.Get("/metrics", routers.Metrics)
  920. }
  921. // Not found handler.
  922. m.NotFound(routers.NotFound)
  923. }