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

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