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.

action.go 27 kB

11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
8 years ago
8 years ago
11 years ago
11 years ago
8 years ago
8 years ago
8 years ago
8 years ago
11 years ago
9 years ago
8 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
11 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
11 years ago
11 years ago
8 years ago
11 years ago
11 years ago
8 years ago
8 years ago
8 years ago
9 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
9 years ago
8 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
8 years ago
8 years ago
8 years ago
11 years ago
9 years ago
11 years ago
11 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
11 years ago
11 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Copyright 2019 The Gitea Authors. All rights reserved.
  3. // Use of this source code is governed by a MIT-style
  4. // license that can be found in the LICENSE file.
  5. package models
  6. import (
  7. "encoding/json"
  8. "fmt"
  9. "path"
  10. "regexp"
  11. "strconv"
  12. "strings"
  13. "time"
  14. "unicode"
  15. "code.gitea.io/gitea/modules/base"
  16. "code.gitea.io/gitea/modules/git"
  17. "code.gitea.io/gitea/modules/log"
  18. "code.gitea.io/gitea/modules/setting"
  19. "code.gitea.io/gitea/modules/util"
  20. api "code.gitea.io/sdk/gitea"
  21. "github.com/Unknwon/com"
  22. "github.com/go-xorm/builder"
  23. )
  24. // ActionType represents the type of an action.
  25. type ActionType int
  26. // Possible action types.
  27. const (
  28. ActionCreateRepo ActionType = iota + 1 // 1
  29. ActionRenameRepo // 2
  30. ActionStarRepo // 3
  31. ActionWatchRepo // 4
  32. ActionCommitRepo // 5
  33. ActionCreateIssue // 6
  34. ActionCreatePullRequest // 7
  35. ActionTransferRepo // 8
  36. ActionPushTag // 9
  37. ActionCommentIssue // 10
  38. ActionMergePullRequest // 11
  39. ActionCloseIssue // 12
  40. ActionReopenIssue // 13
  41. ActionClosePullRequest // 14
  42. ActionReopenPullRequest // 15
  43. ActionDeleteTag // 16
  44. ActionDeleteBranch // 17
  45. ActionMirrorSyncPush // 18
  46. ActionMirrorSyncCreate // 19
  47. ActionMirrorSyncDelete // 20
  48. )
  49. var (
  50. // Same as GitHub. See
  51. // https://help.github.com/articles/closing-issues-via-commit-messages
  52. issueCloseKeywords = []string{"close", "closes", "closed", "fix", "fixes", "fixed", "resolve", "resolves", "resolved"}
  53. issueReopenKeywords = []string{"reopen", "reopens", "reopened"}
  54. issueCloseKeywordsPat, issueReopenKeywordsPat *regexp.Regexp
  55. issueReferenceKeywordsPat *regexp.Regexp
  56. )
  57. const issueRefRegexpStr = `(?:([0-9a-zA-Z-_\.]+)/([0-9a-zA-Z-_\.]+))?(#[0-9]+)+`
  58. func assembleKeywordsPattern(words []string) string {
  59. return fmt.Sprintf(`(?i)(?:%s) %s`, strings.Join(words, "|"), issueRefRegexpStr)
  60. }
  61. func init() {
  62. issueCloseKeywordsPat = regexp.MustCompile(assembleKeywordsPattern(issueCloseKeywords))
  63. issueReopenKeywordsPat = regexp.MustCompile(assembleKeywordsPattern(issueReopenKeywords))
  64. issueReferenceKeywordsPat = regexp.MustCompile(issueRefRegexpStr)
  65. }
  66. // Action represents user operation type and other information to
  67. // repository. It implemented interface base.Actioner so that can be
  68. // used in template render.
  69. type Action struct {
  70. ID int64 `xorm:"pk autoincr"`
  71. UserID int64 `xorm:"INDEX"` // Receiver user id.
  72. OpType ActionType
  73. ActUserID int64 `xorm:"INDEX"` // Action user id.
  74. ActUser *User `xorm:"-"`
  75. RepoID int64 `xorm:"INDEX"`
  76. Repo *Repository `xorm:"-"`
  77. CommentID int64 `xorm:"INDEX"`
  78. Comment *Comment `xorm:"-"`
  79. IsDeleted bool `xorm:"INDEX NOT NULL DEFAULT false"`
  80. RefName string
  81. IsPrivate bool `xorm:"INDEX NOT NULL DEFAULT false"`
  82. Content string `xorm:"TEXT"`
  83. CreatedUnix util.TimeStamp `xorm:"INDEX created"`
  84. }
  85. // GetOpType gets the ActionType of this action.
  86. func (a *Action) GetOpType() ActionType {
  87. return a.OpType
  88. }
  89. func (a *Action) loadActUser() {
  90. if a.ActUser != nil {
  91. return
  92. }
  93. var err error
  94. a.ActUser, err = GetUserByID(a.ActUserID)
  95. if err == nil {
  96. return
  97. } else if IsErrUserNotExist(err) {
  98. a.ActUser = NewGhostUser()
  99. } else {
  100. log.Error("GetUserByID(%d): %v", a.ActUserID, err)
  101. }
  102. }
  103. func (a *Action) loadRepo() {
  104. if a.Repo != nil {
  105. return
  106. }
  107. var err error
  108. a.Repo, err = GetRepositoryByID(a.RepoID)
  109. if err != nil {
  110. log.Error("GetRepositoryByID(%d): %v", a.RepoID, err)
  111. }
  112. }
  113. // GetActFullName gets the action's user full name.
  114. func (a *Action) GetActFullName() string {
  115. a.loadActUser()
  116. return a.ActUser.FullName
  117. }
  118. // GetActUserName gets the action's user name.
  119. func (a *Action) GetActUserName() string {
  120. a.loadActUser()
  121. return a.ActUser.Name
  122. }
  123. // ShortActUserName gets the action's user name trimmed to max 20
  124. // chars.
  125. func (a *Action) ShortActUserName() string {
  126. return base.EllipsisString(a.GetActUserName(), 20)
  127. }
  128. // GetActAvatar the action's user's avatar link
  129. func (a *Action) GetActAvatar() string {
  130. a.loadActUser()
  131. return a.ActUser.RelAvatarLink()
  132. }
  133. // GetRepoUserName returns the name of the action repository owner.
  134. func (a *Action) GetRepoUserName() string {
  135. a.loadRepo()
  136. return a.Repo.MustOwner().Name
  137. }
  138. // ShortRepoUserName returns the name of the action repository owner
  139. // trimmed to max 20 chars.
  140. func (a *Action) ShortRepoUserName() string {
  141. return base.EllipsisString(a.GetRepoUserName(), 20)
  142. }
  143. // GetRepoName returns the name of the action repository.
  144. func (a *Action) GetRepoName() string {
  145. a.loadRepo()
  146. return a.Repo.Name
  147. }
  148. // ShortRepoName returns the name of the action repository
  149. // trimmed to max 33 chars.
  150. func (a *Action) ShortRepoName() string {
  151. return base.EllipsisString(a.GetRepoName(), 33)
  152. }
  153. // GetRepoPath returns the virtual path to the action repository.
  154. func (a *Action) GetRepoPath() string {
  155. return path.Join(a.GetRepoUserName(), a.GetRepoName())
  156. }
  157. // ShortRepoPath returns the virtual path to the action repository
  158. // trimmed to max 20 + 1 + 33 chars.
  159. func (a *Action) ShortRepoPath() string {
  160. return path.Join(a.ShortRepoUserName(), a.ShortRepoName())
  161. }
  162. // GetRepoLink returns relative link to action repository.
  163. func (a *Action) GetRepoLink() string {
  164. if len(setting.AppSubURL) > 0 {
  165. return path.Join(setting.AppSubURL, a.GetRepoPath())
  166. }
  167. return "/" + a.GetRepoPath()
  168. }
  169. // GetRepositoryFromMatch returns a *Repository from a username and repo strings
  170. func GetRepositoryFromMatch(ownerName string, repoName string) (*Repository, error) {
  171. var err error
  172. refRepo, err := GetRepositoryByOwnerAndName(ownerName, repoName)
  173. if err != nil {
  174. if IsErrRepoNotExist(err) {
  175. log.Warn("Repository referenced in commit but does not exist: %v", err)
  176. return nil, err
  177. }
  178. log.Error("GetRepositoryByOwnerAndName: %v", err)
  179. return nil, err
  180. }
  181. return refRepo, nil
  182. }
  183. // GetCommentLink returns link to action comment.
  184. func (a *Action) GetCommentLink() string {
  185. return a.getCommentLink(x)
  186. }
  187. func (a *Action) getCommentLink(e Engine) string {
  188. if a == nil {
  189. return "#"
  190. }
  191. if a.Comment == nil && a.CommentID != 0 {
  192. a.Comment, _ = GetCommentByID(a.CommentID)
  193. }
  194. if a.Comment != nil {
  195. return a.Comment.HTMLURL()
  196. }
  197. if len(a.GetIssueInfos()) == 0 {
  198. return "#"
  199. }
  200. //Return link to issue
  201. issueIDString := a.GetIssueInfos()[0]
  202. issueID, err := strconv.ParseInt(issueIDString, 10, 64)
  203. if err != nil {
  204. return "#"
  205. }
  206. issue, err := getIssueByID(e, issueID)
  207. if err != nil {
  208. return "#"
  209. }
  210. if err = issue.loadRepo(e); err != nil {
  211. return "#"
  212. }
  213. return issue.HTMLURL()
  214. }
  215. // GetBranch returns the action's repository branch.
  216. func (a *Action) GetBranch() string {
  217. return a.RefName
  218. }
  219. // GetContent returns the action's content.
  220. func (a *Action) GetContent() string {
  221. return a.Content
  222. }
  223. // GetCreate returns the action creation time.
  224. func (a *Action) GetCreate() time.Time {
  225. return a.CreatedUnix.AsTime()
  226. }
  227. // GetIssueInfos returns a list of issues associated with
  228. // the action.
  229. func (a *Action) GetIssueInfos() []string {
  230. return strings.SplitN(a.Content, "|", 2)
  231. }
  232. // GetIssueTitle returns the title of first issue associated
  233. // with the action.
  234. func (a *Action) GetIssueTitle() string {
  235. index := com.StrTo(a.GetIssueInfos()[0]).MustInt64()
  236. issue, err := GetIssueByIndex(a.RepoID, index)
  237. if err != nil {
  238. log.Error("GetIssueByIndex: %v", err)
  239. return "500 when get issue"
  240. }
  241. return issue.Title
  242. }
  243. // GetIssueContent returns the content of first issue associated with
  244. // this action.
  245. func (a *Action) GetIssueContent() string {
  246. index := com.StrTo(a.GetIssueInfos()[0]).MustInt64()
  247. issue, err := GetIssueByIndex(a.RepoID, index)
  248. if err != nil {
  249. log.Error("GetIssueByIndex: %v", err)
  250. return "500 when get issue"
  251. }
  252. return issue.Content
  253. }
  254. func newRepoAction(e Engine, u *User, repo *Repository) (err error) {
  255. if err = notifyWatchers(e, &Action{
  256. ActUserID: u.ID,
  257. ActUser: u,
  258. OpType: ActionCreateRepo,
  259. RepoID: repo.ID,
  260. Repo: repo,
  261. IsPrivate: repo.IsPrivate,
  262. }); err != nil {
  263. return fmt.Errorf("notify watchers '%d/%d': %v", u.ID, repo.ID, err)
  264. }
  265. log.Trace("action.newRepoAction: %s/%s", u.Name, repo.Name)
  266. return err
  267. }
  268. // NewRepoAction adds new action for creating repository.
  269. func NewRepoAction(u *User, repo *Repository) (err error) {
  270. return newRepoAction(x, u, repo)
  271. }
  272. func renameRepoAction(e Engine, actUser *User, oldRepoName string, repo *Repository) (err error) {
  273. if err = notifyWatchers(e, &Action{
  274. ActUserID: actUser.ID,
  275. ActUser: actUser,
  276. OpType: ActionRenameRepo,
  277. RepoID: repo.ID,
  278. Repo: repo,
  279. IsPrivate: repo.IsPrivate,
  280. Content: oldRepoName,
  281. }); err != nil {
  282. return fmt.Errorf("notify watchers: %v", err)
  283. }
  284. log.Trace("action.renameRepoAction: %s/%s", actUser.Name, repo.Name)
  285. return nil
  286. }
  287. // RenameRepoAction adds new action for renaming a repository.
  288. func RenameRepoAction(actUser *User, oldRepoName string, repo *Repository) error {
  289. return renameRepoAction(x, actUser, oldRepoName, repo)
  290. }
  291. func issueIndexTrimRight(c rune) bool {
  292. return !unicode.IsDigit(c)
  293. }
  294. // PushCommit represents a commit in a push operation.
  295. type PushCommit struct {
  296. Sha1 string
  297. Message string
  298. AuthorEmail string
  299. AuthorName string
  300. CommitterEmail string
  301. CommitterName string
  302. Timestamp time.Time
  303. }
  304. // PushCommits represents list of commits in a push operation.
  305. type PushCommits struct {
  306. Len int
  307. Commits []*PushCommit
  308. CompareURL string
  309. avatars map[string]string
  310. emailUsers map[string]*User
  311. }
  312. // NewPushCommits creates a new PushCommits object.
  313. func NewPushCommits() *PushCommits {
  314. return &PushCommits{
  315. avatars: make(map[string]string),
  316. emailUsers: make(map[string]*User),
  317. }
  318. }
  319. // ToAPIPayloadCommits converts a PushCommits object to
  320. // api.PayloadCommit format.
  321. func (pc *PushCommits) ToAPIPayloadCommits(repoLink string) []*api.PayloadCommit {
  322. commits := make([]*api.PayloadCommit, len(pc.Commits))
  323. if pc.emailUsers == nil {
  324. pc.emailUsers = make(map[string]*User)
  325. }
  326. var err error
  327. for i, commit := range pc.Commits {
  328. authorUsername := ""
  329. author, ok := pc.emailUsers[commit.AuthorEmail]
  330. if !ok {
  331. author, err = GetUserByEmail(commit.AuthorEmail)
  332. if err == nil {
  333. authorUsername = author.Name
  334. pc.emailUsers[commit.AuthorEmail] = author
  335. }
  336. } else {
  337. authorUsername = author.Name
  338. }
  339. committerUsername := ""
  340. committer, ok := pc.emailUsers[commit.CommitterEmail]
  341. if !ok {
  342. committer, err = GetUserByEmail(commit.CommitterEmail)
  343. if err == nil {
  344. // TODO: check errors other than email not found.
  345. committerUsername = committer.Name
  346. pc.emailUsers[commit.CommitterEmail] = committer
  347. }
  348. } else {
  349. committerUsername = committer.Name
  350. }
  351. commits[i] = &api.PayloadCommit{
  352. ID: commit.Sha1,
  353. Message: commit.Message,
  354. URL: fmt.Sprintf("%s/commit/%s", repoLink, commit.Sha1),
  355. Author: &api.PayloadUser{
  356. Name: commit.AuthorName,
  357. Email: commit.AuthorEmail,
  358. UserName: authorUsername,
  359. },
  360. Committer: &api.PayloadUser{
  361. Name: commit.CommitterName,
  362. Email: commit.CommitterEmail,
  363. UserName: committerUsername,
  364. },
  365. Timestamp: commit.Timestamp,
  366. }
  367. }
  368. return commits
  369. }
  370. // AvatarLink tries to match user in database with e-mail
  371. // in order to show custom avatar, and falls back to general avatar link.
  372. func (pc *PushCommits) AvatarLink(email string) string {
  373. avatar, ok := pc.avatars[email]
  374. if ok {
  375. return avatar
  376. }
  377. u, ok := pc.emailUsers[email]
  378. if !ok {
  379. var err error
  380. u, err = GetUserByEmail(email)
  381. if err != nil {
  382. pc.avatars[email] = base.AvatarLink(email)
  383. if !IsErrUserNotExist(err) {
  384. log.Error("GetUserByEmail: %v", err)
  385. return ""
  386. }
  387. } else {
  388. pc.emailUsers[email] = u
  389. }
  390. }
  391. if u != nil {
  392. pc.avatars[email] = u.RelAvatarLink()
  393. }
  394. return pc.avatars[email]
  395. }
  396. // getIssueFromRef returns the issue referenced by a ref. Returns a nil *Issue
  397. // if the provided ref is misformatted or references a non-existent issue.
  398. func getIssueFromRef(repo *Repository, ref string) (*Issue, error) {
  399. ref = ref[strings.IndexByte(ref, ' ')+1:]
  400. ref = strings.TrimRightFunc(ref, issueIndexTrimRight)
  401. var refRepo *Repository
  402. poundIndex := strings.IndexByte(ref, '#')
  403. if poundIndex < 0 {
  404. return nil, nil
  405. } else if poundIndex == 0 {
  406. refRepo = repo
  407. } else {
  408. slashIndex := strings.IndexByte(ref, '/')
  409. if slashIndex < 0 || slashIndex >= poundIndex {
  410. return nil, nil
  411. }
  412. ownerName := ref[:slashIndex]
  413. repoName := ref[slashIndex+1 : poundIndex]
  414. var err error
  415. refRepo, err = GetRepositoryByOwnerAndName(ownerName, repoName)
  416. if err != nil {
  417. if IsErrRepoNotExist(err) {
  418. return nil, nil
  419. }
  420. return nil, err
  421. }
  422. }
  423. issueIndex, err := strconv.ParseInt(ref[poundIndex+1:], 10, 64)
  424. if err != nil {
  425. return nil, nil
  426. }
  427. issue, err := GetIssueByIndex(refRepo.ID, int64(issueIndex))
  428. if err != nil {
  429. if IsErrIssueNotExist(err) {
  430. return nil, nil
  431. }
  432. return nil, err
  433. }
  434. return issue, nil
  435. }
  436. func changeIssueStatus(repo *Repository, doer *User, ref string, refMarked map[int64]bool, status bool) error {
  437. issue, err := getIssueFromRef(repo, ref)
  438. if err != nil {
  439. return err
  440. }
  441. if issue == nil || refMarked[issue.ID] {
  442. return nil
  443. }
  444. refMarked[issue.ID] = true
  445. if issue.RepoID != repo.ID || issue.IsClosed == status {
  446. return nil
  447. }
  448. stopTimerIfAvailable := func(doer *User, issue *Issue) error {
  449. if StopwatchExists(doer.ID, issue.ID) {
  450. if err := CreateOrStopIssueStopwatch(doer, issue); err != nil {
  451. return err
  452. }
  453. }
  454. return nil
  455. }
  456. issue.Repo = repo
  457. if err = issue.ChangeStatus(doer, status); err != nil {
  458. // Don't return an error when dependencies are open as this would let the push fail
  459. if IsErrDependenciesLeft(err) {
  460. return stopTimerIfAvailable(doer, issue)
  461. }
  462. return err
  463. }
  464. return stopTimerIfAvailable(doer, issue)
  465. }
  466. // UpdateIssuesCommit checks if issues are manipulated by commit message.
  467. func UpdateIssuesCommit(doer *User, repo *Repository, commits []*PushCommit, branchName string) error {
  468. // Commits are appended in the reverse order.
  469. for i := len(commits) - 1; i >= 0; i-- {
  470. c := commits[i]
  471. refMarked := make(map[int64]bool)
  472. var refRepo *Repository
  473. var err error
  474. for _, m := range issueReferenceKeywordsPat.FindAllStringSubmatch(c.Message, -1) {
  475. if len(m[3]) == 0 {
  476. continue
  477. }
  478. ref := m[3]
  479. // issue is from another repo
  480. if len(m[1]) > 0 && len(m[2]) > 0 {
  481. refRepo, err = GetRepositoryFromMatch(string(m[1]), string(m[2]))
  482. if err != nil {
  483. continue
  484. }
  485. } else {
  486. refRepo = repo
  487. }
  488. issue, err := getIssueFromRef(refRepo, ref)
  489. if err != nil {
  490. return err
  491. }
  492. if issue == nil || refMarked[issue.ID] {
  493. continue
  494. }
  495. refMarked[issue.ID] = true
  496. message := fmt.Sprintf(`<a href="%s/commit/%s">%s</a>`, repo.Link(), c.Sha1, c.Message)
  497. if err = CreateRefComment(doer, refRepo, issue, message, c.Sha1); err != nil {
  498. return err
  499. }
  500. }
  501. // Change issue status only if the commit has been pushed to the default branch.
  502. // and if the repo is configured to allow only that
  503. if repo.DefaultBranch != branchName && !repo.CloseIssuesViaCommitInAnyBranch {
  504. continue
  505. }
  506. refMarked = make(map[int64]bool)
  507. for _, m := range issueCloseKeywordsPat.FindAllStringSubmatch(c.Message, -1) {
  508. if len(m[3]) == 0 {
  509. continue
  510. }
  511. ref := m[3]
  512. // issue is from another repo
  513. if len(m[1]) > 0 && len(m[2]) > 0 {
  514. refRepo, err = GetRepositoryFromMatch(string(m[1]), string(m[2]))
  515. if err != nil {
  516. continue
  517. }
  518. } else {
  519. refRepo = repo
  520. }
  521. perm, err := GetUserRepoPermission(refRepo, doer)
  522. if err != nil {
  523. return err
  524. }
  525. // only close issues in another repo if user has push access
  526. if perm.CanWrite(UnitTypeCode) {
  527. if err := changeIssueStatus(refRepo, doer, ref, refMarked, true); err != nil {
  528. return err
  529. }
  530. }
  531. }
  532. // It is conflict to have close and reopen at same time, so refsMarked doesn't need to reinit here.
  533. for _, m := range issueReopenKeywordsPat.FindAllStringSubmatch(c.Message, -1) {
  534. if len(m[3]) == 0 {
  535. continue
  536. }
  537. ref := m[3]
  538. // issue is from another repo
  539. if len(m[1]) > 0 && len(m[2]) > 0 {
  540. refRepo, err = GetRepositoryFromMatch(string(m[1]), string(m[2]))
  541. if err != nil {
  542. continue
  543. }
  544. } else {
  545. refRepo = repo
  546. }
  547. perm, err := GetUserRepoPermission(refRepo, doer)
  548. if err != nil {
  549. return err
  550. }
  551. // only reopen issues in another repo if user has push access
  552. if perm.CanWrite(UnitTypeCode) {
  553. if err := changeIssueStatus(refRepo, doer, ref, refMarked, false); err != nil {
  554. return err
  555. }
  556. }
  557. }
  558. }
  559. return nil
  560. }
  561. // CommitRepoActionOptions represent options of a new commit action.
  562. type CommitRepoActionOptions struct {
  563. PusherName string
  564. RepoOwnerID int64
  565. RepoName string
  566. RefFullName string
  567. OldCommitID string
  568. NewCommitID string
  569. Commits *PushCommits
  570. }
  571. // CommitRepoAction adds new commit action to the repository, and prepare
  572. // corresponding webhooks.
  573. func CommitRepoAction(opts CommitRepoActionOptions) error {
  574. pusher, err := GetUserByName(opts.PusherName)
  575. if err != nil {
  576. return fmt.Errorf("GetUserByName [%s]: %v", opts.PusherName, err)
  577. }
  578. repo, err := GetRepositoryByName(opts.RepoOwnerID, opts.RepoName)
  579. if err != nil {
  580. return fmt.Errorf("GetRepositoryByName [owner_id: %d, name: %s]: %v", opts.RepoOwnerID, opts.RepoName, err)
  581. }
  582. refName := git.RefEndName(opts.RefFullName)
  583. // Change default branch and empty status only if pushed ref is non-empty branch.
  584. if repo.IsEmpty && opts.NewCommitID != git.EmptySHA && strings.HasPrefix(opts.RefFullName, git.BranchPrefix) {
  585. repo.DefaultBranch = refName
  586. repo.IsEmpty = false
  587. }
  588. // Change repository empty status and update last updated time.
  589. if err = UpdateRepository(repo, false); err != nil {
  590. return fmt.Errorf("UpdateRepository: %v", err)
  591. }
  592. isNewBranch := false
  593. opType := ActionCommitRepo
  594. // Check it's tag push or branch.
  595. if strings.HasPrefix(opts.RefFullName, git.TagPrefix) {
  596. opType = ActionPushTag
  597. if opts.NewCommitID == git.EmptySHA {
  598. opType = ActionDeleteTag
  599. }
  600. opts.Commits = &PushCommits{}
  601. } else if opts.NewCommitID == git.EmptySHA {
  602. opType = ActionDeleteBranch
  603. opts.Commits = &PushCommits{}
  604. } else {
  605. // if not the first commit, set the compare URL.
  606. if opts.OldCommitID == git.EmptySHA {
  607. isNewBranch = true
  608. } else {
  609. opts.Commits.CompareURL = repo.ComposeCompareURL(opts.OldCommitID, opts.NewCommitID)
  610. }
  611. if err = UpdateIssuesCommit(pusher, repo, opts.Commits.Commits, refName); err != nil {
  612. log.Error("updateIssuesCommit: %v", err)
  613. }
  614. }
  615. if len(opts.Commits.Commits) > setting.UI.FeedMaxCommitNum {
  616. opts.Commits.Commits = opts.Commits.Commits[:setting.UI.FeedMaxCommitNum]
  617. }
  618. data, err := json.Marshal(opts.Commits)
  619. if err != nil {
  620. return fmt.Errorf("Marshal: %v", err)
  621. }
  622. if err = NotifyWatchers(&Action{
  623. ActUserID: pusher.ID,
  624. ActUser: pusher,
  625. OpType: opType,
  626. Content: string(data),
  627. RepoID: repo.ID,
  628. Repo: repo,
  629. RefName: refName,
  630. IsPrivate: repo.IsPrivate,
  631. }); err != nil {
  632. return fmt.Errorf("NotifyWatchers: %v", err)
  633. }
  634. defer func() {
  635. go HookQueue.Add(repo.ID)
  636. }()
  637. apiPusher := pusher.APIFormat()
  638. apiRepo := repo.APIFormat(AccessModeNone)
  639. var shaSum string
  640. var isHookEventPush = false
  641. switch opType {
  642. case ActionCommitRepo: // Push
  643. isHookEventPush = true
  644. if isNewBranch {
  645. gitRepo, err := git.OpenRepository(repo.RepoPath())
  646. if err != nil {
  647. log.Error("OpenRepository[%s]: %v", repo.RepoPath(), err)
  648. }
  649. shaSum, err = gitRepo.GetBranchCommitID(refName)
  650. if err != nil {
  651. log.Error("GetBranchCommitID[%s]: %v", opts.RefFullName, err)
  652. }
  653. if err = PrepareWebhooks(repo, HookEventCreate, &api.CreatePayload{
  654. Ref: refName,
  655. Sha: shaSum,
  656. RefType: "branch",
  657. Repo: apiRepo,
  658. Sender: apiPusher,
  659. }); err != nil {
  660. return fmt.Errorf("PrepareWebhooks: %v", err)
  661. }
  662. }
  663. case ActionDeleteBranch: // Delete Branch
  664. isHookEventPush = true
  665. if err = PrepareWebhooks(repo, HookEventDelete, &api.DeletePayload{
  666. Ref: refName,
  667. RefType: "branch",
  668. PusherType: api.PusherTypeUser,
  669. Repo: apiRepo,
  670. Sender: apiPusher,
  671. }); err != nil {
  672. return fmt.Errorf("PrepareWebhooks.(delete branch): %v", err)
  673. }
  674. case ActionPushTag: // Create
  675. isHookEventPush = true
  676. gitRepo, err := git.OpenRepository(repo.RepoPath())
  677. if err != nil {
  678. log.Error("OpenRepository[%s]: %v", repo.RepoPath(), err)
  679. }
  680. shaSum, err = gitRepo.GetTagCommitID(refName)
  681. if err != nil {
  682. log.Error("GetTagCommitID[%s]: %v", opts.RefFullName, err)
  683. }
  684. if err = PrepareWebhooks(repo, HookEventCreate, &api.CreatePayload{
  685. Ref: refName,
  686. Sha: shaSum,
  687. RefType: "tag",
  688. Repo: apiRepo,
  689. Sender: apiPusher,
  690. }); err != nil {
  691. return fmt.Errorf("PrepareWebhooks: %v", err)
  692. }
  693. case ActionDeleteTag: // Delete Tag
  694. isHookEventPush = true
  695. if err = PrepareWebhooks(repo, HookEventDelete, &api.DeletePayload{
  696. Ref: refName,
  697. RefType: "tag",
  698. PusherType: api.PusherTypeUser,
  699. Repo: apiRepo,
  700. Sender: apiPusher,
  701. }); err != nil {
  702. return fmt.Errorf("PrepareWebhooks.(delete tag): %v", err)
  703. }
  704. }
  705. if isHookEventPush {
  706. if err = PrepareWebhooks(repo, HookEventPush, &api.PushPayload{
  707. Ref: opts.RefFullName,
  708. Before: opts.OldCommitID,
  709. After: opts.NewCommitID,
  710. CompareURL: setting.AppURL + opts.Commits.CompareURL,
  711. Commits: opts.Commits.ToAPIPayloadCommits(repo.HTMLURL()),
  712. Repo: apiRepo,
  713. Pusher: apiPusher,
  714. Sender: apiPusher,
  715. }); err != nil {
  716. return fmt.Errorf("PrepareWebhooks: %v", err)
  717. }
  718. }
  719. return nil
  720. }
  721. func transferRepoAction(e Engine, doer, oldOwner *User, repo *Repository) (err error) {
  722. if err = notifyWatchers(e, &Action{
  723. ActUserID: doer.ID,
  724. ActUser: doer,
  725. OpType: ActionTransferRepo,
  726. RepoID: repo.ID,
  727. Repo: repo,
  728. IsPrivate: repo.IsPrivate,
  729. Content: path.Join(oldOwner.Name, repo.Name),
  730. }); err != nil {
  731. return fmt.Errorf("notifyWatchers: %v", err)
  732. }
  733. // Remove watch for organization.
  734. if oldOwner.IsOrganization() {
  735. if err = watchRepo(e, oldOwner.ID, repo.ID, false); err != nil {
  736. return fmt.Errorf("watchRepo [false]: %v", err)
  737. }
  738. }
  739. return nil
  740. }
  741. // TransferRepoAction adds new action for transferring repository,
  742. // the Owner field of repository is assumed to be new owner.
  743. func TransferRepoAction(doer, oldOwner *User, repo *Repository) error {
  744. return transferRepoAction(x, doer, oldOwner, repo)
  745. }
  746. func mergePullRequestAction(e Engine, doer *User, repo *Repository, issue *Issue) error {
  747. return notifyWatchers(e, &Action{
  748. ActUserID: doer.ID,
  749. ActUser: doer,
  750. OpType: ActionMergePullRequest,
  751. Content: fmt.Sprintf("%d|%s", issue.Index, issue.Title),
  752. RepoID: repo.ID,
  753. Repo: repo,
  754. IsPrivate: repo.IsPrivate,
  755. })
  756. }
  757. // MergePullRequestAction adds new action for merging pull request.
  758. func MergePullRequestAction(actUser *User, repo *Repository, pull *Issue) error {
  759. return mergePullRequestAction(x, actUser, repo, pull)
  760. }
  761. func mirrorSyncAction(e Engine, opType ActionType, repo *Repository, refName string, data []byte) error {
  762. if err := notifyWatchers(e, &Action{
  763. ActUserID: repo.OwnerID,
  764. ActUser: repo.MustOwner(),
  765. OpType: opType,
  766. RepoID: repo.ID,
  767. Repo: repo,
  768. IsPrivate: repo.IsPrivate,
  769. RefName: refName,
  770. Content: string(data),
  771. }); err != nil {
  772. return fmt.Errorf("notifyWatchers: %v", err)
  773. }
  774. return nil
  775. }
  776. // MirrorSyncPushActionOptions mirror synchronization action options.
  777. type MirrorSyncPushActionOptions struct {
  778. RefName string
  779. OldCommitID string
  780. NewCommitID string
  781. Commits *PushCommits
  782. }
  783. // MirrorSyncPushAction adds new action for mirror synchronization of pushed commits.
  784. func MirrorSyncPushAction(repo *Repository, opts MirrorSyncPushActionOptions) error {
  785. if len(opts.Commits.Commits) > setting.UI.FeedMaxCommitNum {
  786. opts.Commits.Commits = opts.Commits.Commits[:setting.UI.FeedMaxCommitNum]
  787. }
  788. apiCommits := opts.Commits.ToAPIPayloadCommits(repo.HTMLURL())
  789. opts.Commits.CompareURL = repo.ComposeCompareURL(opts.OldCommitID, opts.NewCommitID)
  790. apiPusher := repo.MustOwner().APIFormat()
  791. if err := PrepareWebhooks(repo, HookEventPush, &api.PushPayload{
  792. Ref: opts.RefName,
  793. Before: opts.OldCommitID,
  794. After: opts.NewCommitID,
  795. CompareURL: setting.AppURL + opts.Commits.CompareURL,
  796. Commits: apiCommits,
  797. Repo: repo.APIFormat(AccessModeOwner),
  798. Pusher: apiPusher,
  799. Sender: apiPusher,
  800. }); err != nil {
  801. return fmt.Errorf("PrepareWebhooks: %v", err)
  802. }
  803. data, err := json.Marshal(opts.Commits)
  804. if err != nil {
  805. return err
  806. }
  807. return mirrorSyncAction(x, ActionMirrorSyncPush, repo, opts.RefName, data)
  808. }
  809. // MirrorSyncCreateAction adds new action for mirror synchronization of new reference.
  810. func MirrorSyncCreateAction(repo *Repository, refName string) error {
  811. return mirrorSyncAction(x, ActionMirrorSyncCreate, repo, refName, nil)
  812. }
  813. // MirrorSyncDeleteAction adds new action for mirror synchronization of delete reference.
  814. func MirrorSyncDeleteAction(repo *Repository, refName string) error {
  815. return mirrorSyncAction(x, ActionMirrorSyncDelete, repo, refName, nil)
  816. }
  817. // GetFeedsOptions options for retrieving feeds
  818. type GetFeedsOptions struct {
  819. RequestedUser *User
  820. RequestingUserID int64
  821. IncludePrivate bool // include private actions
  822. OnlyPerformedBy bool // only actions performed by requested user
  823. IncludeDeleted bool // include deleted actions
  824. }
  825. // GetFeeds returns actions according to the provided options
  826. func GetFeeds(opts GetFeedsOptions) ([]*Action, error) {
  827. cond := builder.NewCond()
  828. var repoIDs []int64
  829. if opts.RequestedUser.IsOrganization() {
  830. env, err := opts.RequestedUser.AccessibleReposEnv(opts.RequestingUserID)
  831. if err != nil {
  832. return nil, fmt.Errorf("AccessibleReposEnv: %v", err)
  833. }
  834. if repoIDs, err = env.RepoIDs(1, opts.RequestedUser.NumRepos); err != nil {
  835. return nil, fmt.Errorf("GetUserRepositories: %v", err)
  836. }
  837. cond = cond.And(builder.In("repo_id", repoIDs))
  838. }
  839. cond = cond.And(builder.Eq{"user_id": opts.RequestedUser.ID})
  840. if opts.OnlyPerformedBy {
  841. cond = cond.And(builder.Eq{"act_user_id": opts.RequestedUser.ID})
  842. }
  843. if !opts.IncludePrivate {
  844. cond = cond.And(builder.Eq{"is_private": false})
  845. }
  846. if !opts.IncludeDeleted {
  847. cond = cond.And(builder.Eq{"is_deleted": false})
  848. }
  849. actions := make([]*Action, 0, 20)
  850. if err := x.Limit(20).Desc("id").Where(cond).Find(&actions); err != nil {
  851. return nil, fmt.Errorf("Find: %v", err)
  852. }
  853. if err := ActionList(actions).LoadAttributes(); err != nil {
  854. return nil, fmt.Errorf("LoadAttributes: %v", err)
  855. }
  856. return actions, nil
  857. }