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.

issue.go 49 kB

11 years ago
11 years ago
11 years ago
Issue due date (#3794) * Started adding deadline to ui * Implemented basic issue due date managing * Improved UI for due date managing * Added at least write access to the repo in order to modify issue due dates * Ui improvements * Added issue comments creation when adding/modifying/removing a due date * Show due date in issue list * Added api support for issue due dates * Fixed lint suggestions * Added deadline to sdk * Updated css * Added support for adding/modifiying deadlines for pull requests via api * Fixed comments not created when updating or removing a deadline * update sdk (will do properly once go-gitea/go-sdk#103 is merged) * enhanced updateIssueDeadline * Removed unnessecary Issue.DeadlineString * UI improvements * Small improvments to comment creation + ui & validation improvements * Check if an issue is overdue is now a seperate function * Updated go-sdk with govendor as it was merged * Simplified isOverdue method * removed unessecary deadline to 0 set * Update swagger definitions * Added missing return * Added an explanary comment * Improved updateIssueDeadline method so it'll only update `deadline_unix` * Small changes and improvements * no need to explicitly load the issue when updating a deadline, just use whats already there * small optimisations * Added check if a deadline was modified before updating it * Moved comment creating logic into its own function * Code cleanup for creating deadline comment * locale improvement * When modifying a deadline, the old deadline is saved with the comment * small improvments to xorm session handling when updating an issue deadline + style nitpicks * style nitpicks * Moved checking for if the user has write acces to middleware
7 years ago
Shows total tracked time in issue and milestone list (#3341) * Show total tracked time in issue and milestone list Show total tracked time at issue page Signed-off-by: Jonas Franz <info@jonasfranz.software> * Optimizing TotalTimes by using SumInt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fixing wrong total times for milestones caused by a missing JOIN Adding unit tests for total times Signed-off-by: Jonas Franz <info@jonasfranz.software> * Logging error instead of ignoring it Signed-off-by: Jonas Franz <info@jonasfranz.software> * Correcting spelling mistakes Signed-off-by: Jonas Franz <info@jonasfranz.software> * Change error message to a short version Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add error handling to TotalTimes Add variable for totalTimes Signed-off-by: Jonas Franz <info@jonasfranz.de> * Introduce TotalTrackedTimes as variable of issue Load TotalTrackedTimes by loading attributes of IssueList Load TotalTrackedTimes by loading attributes of single issue Add Sec2Time as helper to use it in templates Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fixed test + gofmt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Load TotalTrackedTimes via MilestoneList instead of single requests Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add documentation for MilestoneList Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add documentation for MilestoneList Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix test Signed-off-by: Jonas Franz <info@jonasfranz.software> * Change comment from SQL query to description Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix unit test by using int64 instead of int Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix unit test by using int64 instead of int Signed-off-by: Jonas Franz <info@jonasfranz.software> * Check if timetracker is enabled Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix test by enabling timetracking Signed-off-by: Jonas Franz <info@jonasfranz.de>
7 years ago
Shows total tracked time in issue and milestone list (#3341) * Show total tracked time in issue and milestone list Show total tracked time at issue page Signed-off-by: Jonas Franz <info@jonasfranz.software> * Optimizing TotalTimes by using SumInt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fixing wrong total times for milestones caused by a missing JOIN Adding unit tests for total times Signed-off-by: Jonas Franz <info@jonasfranz.software> * Logging error instead of ignoring it Signed-off-by: Jonas Franz <info@jonasfranz.software> * Correcting spelling mistakes Signed-off-by: Jonas Franz <info@jonasfranz.software> * Change error message to a short version Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add error handling to TotalTimes Add variable for totalTimes Signed-off-by: Jonas Franz <info@jonasfranz.de> * Introduce TotalTrackedTimes as variable of issue Load TotalTrackedTimes by loading attributes of IssueList Load TotalTrackedTimes by loading attributes of single issue Add Sec2Time as helper to use it in templates Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fixed test + gofmt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Load TotalTrackedTimes via MilestoneList instead of single requests Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add documentation for MilestoneList Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add documentation for MilestoneList Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix test Signed-off-by: Jonas Franz <info@jonasfranz.software> * Change comment from SQL query to description Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix unit test by using int64 instead of int Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix unit test by using int64 instead of int Signed-off-by: Jonas Franz <info@jonasfranz.software> * Check if timetracker is enabled Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix test by enabling timetracking Signed-off-by: Jonas Franz <info@jonasfranz.de>
7 years ago
Issue due date (#3794) * Started adding deadline to ui * Implemented basic issue due date managing * Improved UI for due date managing * Added at least write access to the repo in order to modify issue due dates * Ui improvements * Added issue comments creation when adding/modifying/removing a due date * Show due date in issue list * Added api support for issue due dates * Fixed lint suggestions * Added deadline to sdk * Updated css * Added support for adding/modifiying deadlines for pull requests via api * Fixed comments not created when updating or removing a deadline * update sdk (will do properly once go-gitea/go-sdk#103 is merged) * enhanced updateIssueDeadline * Removed unnessecary Issue.DeadlineString * UI improvements * Small improvments to comment creation + ui & validation improvements * Check if an issue is overdue is now a seperate function * Updated go-sdk with govendor as it was merged * Simplified isOverdue method * removed unessecary deadline to 0 set * Update swagger definitions * Added missing return * Added an explanary comment * Improved updateIssueDeadline method so it'll only update `deadline_unix` * Small changes and improvements * no need to explicitly load the issue when updating a deadline, just use whats already there * small optimisations * Added check if a deadline was modified before updating it * Moved comment creating logic into its own function * Code cleanup for creating deadline comment * locale improvement * When modifying a deadline, the old deadline is saved with the comment * small improvments to xorm session handling when updating an issue deadline + style nitpicks * style nitpicks * Moved checking for if the user has write acces to middleware
7 years ago
Shows total tracked time in issue and milestone list (#3341) * Show total tracked time in issue and milestone list Show total tracked time at issue page Signed-off-by: Jonas Franz <info@jonasfranz.software> * Optimizing TotalTimes by using SumInt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fixing wrong total times for milestones caused by a missing JOIN Adding unit tests for total times Signed-off-by: Jonas Franz <info@jonasfranz.software> * Logging error instead of ignoring it Signed-off-by: Jonas Franz <info@jonasfranz.software> * Correcting spelling mistakes Signed-off-by: Jonas Franz <info@jonasfranz.software> * Change error message to a short version Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add error handling to TotalTimes Add variable for totalTimes Signed-off-by: Jonas Franz <info@jonasfranz.de> * Introduce TotalTrackedTimes as variable of issue Load TotalTrackedTimes by loading attributes of IssueList Load TotalTrackedTimes by loading attributes of single issue Add Sec2Time as helper to use it in templates Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fixed test + gofmt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Load TotalTrackedTimes via MilestoneList instead of single requests Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add documentation for MilestoneList Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add documentation for MilestoneList Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix test Signed-off-by: Jonas Franz <info@jonasfranz.software> * Change comment from SQL query to description Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix unit test by using int64 instead of int Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix unit test by using int64 instead of int Signed-off-by: Jonas Franz <info@jonasfranz.software> * Check if timetracker is enabled Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix test by enabling timetracking Signed-off-by: Jonas Franz <info@jonasfranz.de>
7 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
Shows total tracked time in issue and milestone list (#3341) * Show total tracked time in issue and milestone list Show total tracked time at issue page Signed-off-by: Jonas Franz <info@jonasfranz.software> * Optimizing TotalTimes by using SumInt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fixing wrong total times for milestones caused by a missing JOIN Adding unit tests for total times Signed-off-by: Jonas Franz <info@jonasfranz.software> * Logging error instead of ignoring it Signed-off-by: Jonas Franz <info@jonasfranz.software> * Correcting spelling mistakes Signed-off-by: Jonas Franz <info@jonasfranz.software> * Change error message to a short version Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add error handling to TotalTimes Add variable for totalTimes Signed-off-by: Jonas Franz <info@jonasfranz.de> * Introduce TotalTrackedTimes as variable of issue Load TotalTrackedTimes by loading attributes of IssueList Load TotalTrackedTimes by loading attributes of single issue Add Sec2Time as helper to use it in templates Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fixed test + gofmt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Load TotalTrackedTimes via MilestoneList instead of single requests Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add documentation for MilestoneList Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add documentation for MilestoneList Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix test Signed-off-by: Jonas Franz <info@jonasfranz.software> * Change comment from SQL query to description Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix unit test by using int64 instead of int Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix unit test by using int64 instead of int Signed-off-by: Jonas Franz <info@jonasfranz.software> * Check if timetracker is enabled Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix test by enabling timetracking Signed-off-by: Jonas Franz <info@jonasfranz.de>
7 years ago
Shows total tracked time in issue and milestone list (#3341) * Show total tracked time in issue and milestone list Show total tracked time at issue page Signed-off-by: Jonas Franz <info@jonasfranz.software> * Optimizing TotalTimes by using SumInt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fixing wrong total times for milestones caused by a missing JOIN Adding unit tests for total times Signed-off-by: Jonas Franz <info@jonasfranz.software> * Logging error instead of ignoring it Signed-off-by: Jonas Franz <info@jonasfranz.software> * Correcting spelling mistakes Signed-off-by: Jonas Franz <info@jonasfranz.software> * Change error message to a short version Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add error handling to TotalTimes Add variable for totalTimes Signed-off-by: Jonas Franz <info@jonasfranz.de> * Introduce TotalTrackedTimes as variable of issue Load TotalTrackedTimes by loading attributes of IssueList Load TotalTrackedTimes by loading attributes of single issue Add Sec2Time as helper to use it in templates Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fixed test + gofmt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Load TotalTrackedTimes via MilestoneList instead of single requests Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add documentation for MilestoneList Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add documentation for MilestoneList Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix test Signed-off-by: Jonas Franz <info@jonasfranz.software> * Change comment from SQL query to description Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix unit test by using int64 instead of int Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix unit test by using int64 instead of int Signed-off-by: Jonas Franz <info@jonasfranz.software> * Check if timetracker is enabled Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix test by enabling timetracking Signed-off-by: Jonas Franz <info@jonasfranz.de>
7 years ago
9 years ago
8 years ago
8 years ago
Issue due date (#3794) * Started adding deadline to ui * Implemented basic issue due date managing * Improved UI for due date managing * Added at least write access to the repo in order to modify issue due dates * Ui improvements * Added issue comments creation when adding/modifying/removing a due date * Show due date in issue list * Added api support for issue due dates * Fixed lint suggestions * Added deadline to sdk * Updated css * Added support for adding/modifiying deadlines for pull requests via api * Fixed comments not created when updating or removing a deadline * update sdk (will do properly once go-gitea/go-sdk#103 is merged) * enhanced updateIssueDeadline * Removed unnessecary Issue.DeadlineString * UI improvements * Small improvments to comment creation + ui & validation improvements * Check if an issue is overdue is now a seperate function * Updated go-sdk with govendor as it was merged * Simplified isOverdue method * removed unessecary deadline to 0 set * Update swagger definitions * Added missing return * Added an explanary comment * Improved updateIssueDeadline method so it'll only update `deadline_unix` * Small changes and improvements * no need to explicitly load the issue when updating a deadline, just use whats already there * small optimisations * Added check if a deadline was modified before updating it * Moved comment creating logic into its own function * Code cleanup for creating deadline comment * locale improvement * When modifying a deadline, the old deadline is saved with the comment * small improvments to xorm session handling when updating an issue deadline + style nitpicks * style nitpicks * Moved checking for if the user has write acces to middleware
7 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
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
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
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
8 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
11 years ago
11 years ago
11 years ago
11 years ago
Issue due date (#3794) * Started adding deadline to ui * Implemented basic issue due date managing * Improved UI for due date managing * Added at least write access to the repo in order to modify issue due dates * Ui improvements * Added issue comments creation when adding/modifying/removing a due date * Show due date in issue list * Added api support for issue due dates * Fixed lint suggestions * Added deadline to sdk * Updated css * Added support for adding/modifiying deadlines for pull requests via api * Fixed comments not created when updating or removing a deadline * update sdk (will do properly once go-gitea/go-sdk#103 is merged) * enhanced updateIssueDeadline * Removed unnessecary Issue.DeadlineString * UI improvements * Small improvments to comment creation + ui & validation improvements * Check if an issue is overdue is now a seperate function * Updated go-sdk with govendor as it was merged * Simplified isOverdue method * removed unessecary deadline to 0 set * Update swagger definitions * Added missing return * Added an explanary comment * Improved updateIssueDeadline method so it'll only update `deadline_unix` * Small changes and improvements * no need to explicitly load the issue when updating a deadline, just use whats already there * small optimisations * Added check if a deadline was modified before updating it * Moved comment creating logic into its own function * Code cleanup for creating deadline comment * locale improvement * When modifying a deadline, the old deadline is saved with the comment * small improvments to xorm session handling when updating an issue deadline + style nitpicks * style nitpicks * Moved checking for if the user has write acces to middleware
7 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package models
  5. import (
  6. "errors"
  7. "fmt"
  8. "path"
  9. "regexp"
  10. "sort"
  11. "strings"
  12. "code.gitea.io/gitea/modules/base"
  13. "code.gitea.io/gitea/modules/log"
  14. "code.gitea.io/gitea/modules/setting"
  15. api "code.gitea.io/gitea/modules/structs"
  16. "code.gitea.io/gitea/modules/util"
  17. "github.com/Unknwon/com"
  18. "github.com/go-xorm/xorm"
  19. "xorm.io/builder"
  20. )
  21. // Issue represents an issue or pull request of repository.
  22. type Issue struct {
  23. ID int64 `xorm:"pk autoincr"`
  24. RepoID int64 `xorm:"INDEX UNIQUE(repo_index)"`
  25. Repo *Repository `xorm:"-"`
  26. Index int64 `xorm:"UNIQUE(repo_index)"` // Index in one repository.
  27. PosterID int64 `xorm:"INDEX"`
  28. Poster *User `xorm:"-"`
  29. OriginalAuthor string
  30. OriginalAuthorID int64
  31. Title string `xorm:"name"`
  32. Content string `xorm:"TEXT"`
  33. RenderedContent string `xorm:"-"`
  34. Labels []*Label `xorm:"-"`
  35. MilestoneID int64 `xorm:"INDEX"`
  36. Milestone *Milestone `xorm:"-"`
  37. Priority int
  38. AssigneeID int64 `xorm:"-"`
  39. Assignee *User `xorm:"-"`
  40. IsClosed bool `xorm:"INDEX"`
  41. IsRead bool `xorm:"-"`
  42. IsPull bool `xorm:"INDEX"` // Indicates whether is a pull request or not.
  43. PullRequest *PullRequest `xorm:"-"`
  44. NumComments int
  45. Ref string
  46. DeadlineUnix util.TimeStamp `xorm:"INDEX"`
  47. CreatedUnix util.TimeStamp `xorm:"INDEX created"`
  48. UpdatedUnix util.TimeStamp `xorm:"INDEX updated"`
  49. ClosedUnix util.TimeStamp `xorm:"INDEX"`
  50. Attachments []*Attachment `xorm:"-"`
  51. Comments []*Comment `xorm:"-"`
  52. Reactions ReactionList `xorm:"-"`
  53. TotalTrackedTime int64 `xorm:"-"`
  54. Assignees []*User `xorm:"-"`
  55. // IsLocked limits commenting abilities to users on an issue
  56. // with write access
  57. IsLocked bool `xorm:"NOT NULL DEFAULT false"`
  58. }
  59. var (
  60. issueTasksPat *regexp.Regexp
  61. issueTasksDonePat *regexp.Regexp
  62. )
  63. const issueTasksRegexpStr = `(^\s*[-*]\s\[[\sx]\]\s.)|(\n\s*[-*]\s\[[\sx]\]\s.)`
  64. const issueTasksDoneRegexpStr = `(^\s*[-*]\s\[[x]\]\s.)|(\n\s*[-*]\s\[[x]\]\s.)`
  65. func init() {
  66. issueTasksPat = regexp.MustCompile(issueTasksRegexpStr)
  67. issueTasksDonePat = regexp.MustCompile(issueTasksDoneRegexpStr)
  68. }
  69. func (issue *Issue) loadTotalTimes(e Engine) (err error) {
  70. opts := FindTrackedTimesOptions{IssueID: issue.ID}
  71. issue.TotalTrackedTime, err = opts.ToSession(e).SumInt(&TrackedTime{}, "time")
  72. if err != nil {
  73. return err
  74. }
  75. return nil
  76. }
  77. // IsOverdue checks if the issue is overdue
  78. func (issue *Issue) IsOverdue() bool {
  79. return util.TimeStampNow() >= issue.DeadlineUnix
  80. }
  81. // LoadRepo loads issue's repository
  82. func (issue *Issue) LoadRepo() error {
  83. return issue.loadRepo(x)
  84. }
  85. func (issue *Issue) loadRepo(e Engine) (err error) {
  86. if issue.Repo == nil {
  87. issue.Repo, err = getRepositoryByID(e, issue.RepoID)
  88. if err != nil {
  89. return fmt.Errorf("getRepositoryByID [%d]: %v", issue.RepoID, err)
  90. }
  91. }
  92. return nil
  93. }
  94. // IsTimetrackerEnabled returns true if the repo enables timetracking
  95. func (issue *Issue) IsTimetrackerEnabled() bool {
  96. return issue.isTimetrackerEnabled(x)
  97. }
  98. func (issue *Issue) isTimetrackerEnabled(e Engine) bool {
  99. if err := issue.loadRepo(e); err != nil {
  100. log.Error(fmt.Sprintf("loadRepo: %v", err))
  101. return false
  102. }
  103. return issue.Repo.IsTimetrackerEnabled()
  104. }
  105. // GetPullRequest returns the issue pull request
  106. func (issue *Issue) GetPullRequest() (pr *PullRequest, err error) {
  107. if !issue.IsPull {
  108. return nil, fmt.Errorf("Issue is not a pull request")
  109. }
  110. pr, err = getPullRequestByIssueID(x, issue.ID)
  111. if err != nil {
  112. return nil, err
  113. }
  114. pr.Issue = issue
  115. return
  116. }
  117. func (issue *Issue) loadLabels(e Engine) (err error) {
  118. if issue.Labels == nil {
  119. issue.Labels, err = getLabelsByIssueID(e, issue.ID)
  120. if err != nil {
  121. return fmt.Errorf("getLabelsByIssueID [%d]: %v", issue.ID, err)
  122. }
  123. }
  124. return nil
  125. }
  126. // LoadPoster loads poster
  127. func (issue *Issue) LoadPoster() error {
  128. return issue.loadPoster(x)
  129. }
  130. func (issue *Issue) loadPoster(e Engine) (err error) {
  131. if issue.Poster == nil {
  132. issue.Poster, err = getUserByID(e, issue.PosterID)
  133. if err != nil {
  134. issue.PosterID = -1
  135. issue.Poster = NewGhostUser()
  136. if !IsErrUserNotExist(err) {
  137. return fmt.Errorf("getUserByID.(poster) [%d]: %v", issue.PosterID, err)
  138. }
  139. err = nil
  140. return
  141. }
  142. }
  143. return
  144. }
  145. func (issue *Issue) loadPullRequest(e Engine) (err error) {
  146. if issue.IsPull && issue.PullRequest == nil {
  147. issue.PullRequest, err = getPullRequestByIssueID(e, issue.ID)
  148. if err != nil {
  149. if IsErrPullRequestNotExist(err) {
  150. return err
  151. }
  152. return fmt.Errorf("getPullRequestByIssueID [%d]: %v", issue.ID, err)
  153. }
  154. issue.PullRequest.Issue = issue
  155. }
  156. return nil
  157. }
  158. // LoadPullRequest loads pull request info
  159. func (issue *Issue) LoadPullRequest() error {
  160. return issue.loadPullRequest(x)
  161. }
  162. func (issue *Issue) loadComments(e Engine) (err error) {
  163. return issue.loadCommentsByType(e, CommentTypeUnknown)
  164. }
  165. // LoadDiscussComments loads discuss comments
  166. func (issue *Issue) LoadDiscussComments() error {
  167. return issue.loadCommentsByType(x, CommentTypeComment)
  168. }
  169. func (issue *Issue) loadCommentsByType(e Engine, tp CommentType) (err error) {
  170. if issue.Comments != nil {
  171. return nil
  172. }
  173. issue.Comments, err = findComments(e, FindCommentsOptions{
  174. IssueID: issue.ID,
  175. Type: tp,
  176. })
  177. return err
  178. }
  179. func (issue *Issue) loadReactions(e Engine) (err error) {
  180. if issue.Reactions != nil {
  181. return nil
  182. }
  183. reactions, err := findReactions(e, FindReactionsOptions{
  184. IssueID: issue.ID,
  185. })
  186. if err != nil {
  187. return err
  188. }
  189. // Load reaction user data
  190. if _, err := ReactionList(reactions).loadUsers(e); err != nil {
  191. return err
  192. }
  193. // Cache comments to map
  194. comments := make(map[int64]*Comment)
  195. for _, comment := range issue.Comments {
  196. comments[comment.ID] = comment
  197. }
  198. // Add reactions either to issue or comment
  199. for _, react := range reactions {
  200. if react.CommentID == 0 {
  201. issue.Reactions = append(issue.Reactions, react)
  202. } else if comment, ok := comments[react.CommentID]; ok {
  203. comment.Reactions = append(comment.Reactions, react)
  204. }
  205. }
  206. return nil
  207. }
  208. func (issue *Issue) loadAttributes(e Engine) (err error) {
  209. if err = issue.loadRepo(e); err != nil {
  210. return
  211. }
  212. if err = issue.loadPoster(e); err != nil {
  213. return
  214. }
  215. if err = issue.loadLabels(e); err != nil {
  216. return
  217. }
  218. if issue.Milestone == nil && issue.MilestoneID > 0 {
  219. issue.Milestone, err = getMilestoneByRepoID(e, issue.RepoID, issue.MilestoneID)
  220. if err != nil && !IsErrMilestoneNotExist(err) {
  221. return fmt.Errorf("getMilestoneByRepoID [repo_id: %d, milestone_id: %d]: %v", issue.RepoID, issue.MilestoneID, err)
  222. }
  223. }
  224. if err = issue.loadAssignees(e); err != nil {
  225. return
  226. }
  227. if err = issue.loadPullRequest(e); err != nil && !IsErrPullRequestNotExist(err) {
  228. // It is possible pull request is not yet created.
  229. return err
  230. }
  231. if issue.Attachments == nil {
  232. issue.Attachments, err = getAttachmentsByIssueID(e, issue.ID)
  233. if err != nil {
  234. return fmt.Errorf("getAttachmentsByIssueID [%d]: %v", issue.ID, err)
  235. }
  236. }
  237. if err = issue.loadComments(e); err != nil {
  238. return err
  239. }
  240. if err = CommentList(issue.Comments).loadAttributes(e); err != nil {
  241. return err
  242. }
  243. if issue.isTimetrackerEnabled(e) {
  244. if err = issue.loadTotalTimes(e); err != nil {
  245. return err
  246. }
  247. }
  248. return issue.loadReactions(e)
  249. }
  250. // LoadAttributes loads the attribute of this issue.
  251. func (issue *Issue) LoadAttributes() error {
  252. return issue.loadAttributes(x)
  253. }
  254. // GetIsRead load the `IsRead` field of the issue
  255. func (issue *Issue) GetIsRead(userID int64) error {
  256. issueUser := &IssueUser{IssueID: issue.ID, UID: userID}
  257. if has, err := x.Get(issueUser); err != nil {
  258. return err
  259. } else if !has {
  260. issue.IsRead = false
  261. return nil
  262. }
  263. issue.IsRead = issueUser.IsRead
  264. return nil
  265. }
  266. // APIURL returns the absolute APIURL to this issue.
  267. func (issue *Issue) APIURL() string {
  268. return issue.Repo.APIURL() + "/" + path.Join("issues", fmt.Sprint(issue.Index))
  269. }
  270. // HTMLURL returns the absolute URL to this issue.
  271. func (issue *Issue) HTMLURL() string {
  272. var path string
  273. if issue.IsPull {
  274. path = "pulls"
  275. } else {
  276. path = "issues"
  277. }
  278. return fmt.Sprintf("%s/%s/%d", issue.Repo.HTMLURL(), path, issue.Index)
  279. }
  280. // DiffURL returns the absolute URL to this diff
  281. func (issue *Issue) DiffURL() string {
  282. if issue.IsPull {
  283. return fmt.Sprintf("%s/pulls/%d.diff", issue.Repo.HTMLURL(), issue.Index)
  284. }
  285. return ""
  286. }
  287. // PatchURL returns the absolute URL to this patch
  288. func (issue *Issue) PatchURL() string {
  289. if issue.IsPull {
  290. return fmt.Sprintf("%s/pulls/%d.patch", issue.Repo.HTMLURL(), issue.Index)
  291. }
  292. return ""
  293. }
  294. // State returns string representation of issue status.
  295. func (issue *Issue) State() api.StateType {
  296. if issue.IsClosed {
  297. return api.StateClosed
  298. }
  299. return api.StateOpen
  300. }
  301. // APIFormat assumes some fields assigned with values:
  302. // Required - Poster, Labels,
  303. // Optional - Milestone, Assignee, PullRequest
  304. func (issue *Issue) APIFormat() *api.Issue {
  305. return issue.apiFormat(x)
  306. }
  307. func (issue *Issue) apiFormat(e Engine) *api.Issue {
  308. issue.loadLabels(e)
  309. apiLabels := make([]*api.Label, len(issue.Labels))
  310. for i := range issue.Labels {
  311. apiLabels[i] = issue.Labels[i].APIFormat()
  312. }
  313. issue.loadPoster(e)
  314. issue.loadRepo(e)
  315. apiIssue := &api.Issue{
  316. ID: issue.ID,
  317. URL: issue.APIURL(),
  318. Index: issue.Index,
  319. Poster: issue.Poster.APIFormat(),
  320. Title: issue.Title,
  321. Body: issue.Content,
  322. Labels: apiLabels,
  323. State: issue.State(),
  324. Comments: issue.NumComments,
  325. Created: issue.CreatedUnix.AsTime(),
  326. Updated: issue.UpdatedUnix.AsTime(),
  327. }
  328. if issue.ClosedUnix != 0 {
  329. apiIssue.Closed = issue.ClosedUnix.AsTimePtr()
  330. }
  331. if issue.Milestone != nil {
  332. apiIssue.Milestone = issue.Milestone.APIFormat()
  333. }
  334. issue.loadAssignees(e)
  335. if len(issue.Assignees) > 0 {
  336. for _, assignee := range issue.Assignees {
  337. apiIssue.Assignees = append(apiIssue.Assignees, assignee.APIFormat())
  338. }
  339. apiIssue.Assignee = issue.Assignees[0].APIFormat() // For compatibility, we're keeping the first assignee as `apiIssue.Assignee`
  340. }
  341. if issue.IsPull {
  342. issue.loadPullRequest(e)
  343. apiIssue.PullRequest = &api.PullRequestMeta{
  344. HasMerged: issue.PullRequest.HasMerged,
  345. }
  346. if issue.PullRequest.HasMerged {
  347. apiIssue.PullRequest.Merged = issue.PullRequest.MergedUnix.AsTimePtr()
  348. }
  349. }
  350. if issue.DeadlineUnix != 0 {
  351. apiIssue.Deadline = issue.DeadlineUnix.AsTimePtr()
  352. }
  353. return apiIssue
  354. }
  355. // HashTag returns unique hash tag for issue.
  356. func (issue *Issue) HashTag() string {
  357. return "issue-" + com.ToStr(issue.ID)
  358. }
  359. // IsPoster returns true if given user by ID is the poster.
  360. func (issue *Issue) IsPoster(uid int64) bool {
  361. return issue.PosterID == uid
  362. }
  363. func (issue *Issue) hasLabel(e Engine, labelID int64) bool {
  364. return hasIssueLabel(e, issue.ID, labelID)
  365. }
  366. // HasLabel returns true if issue has been labeled by given ID.
  367. func (issue *Issue) HasLabel(labelID int64) bool {
  368. return issue.hasLabel(x, labelID)
  369. }
  370. func (issue *Issue) sendLabelUpdatedWebhook(doer *User) {
  371. var err error
  372. if err = issue.loadRepo(x); err != nil {
  373. log.Error("loadRepo: %v", err)
  374. return
  375. }
  376. if err = issue.loadPoster(x); err != nil {
  377. log.Error("loadPoster: %v", err)
  378. return
  379. }
  380. mode, _ := AccessLevel(issue.Poster, issue.Repo)
  381. if issue.IsPull {
  382. if err = issue.loadPullRequest(x); err != nil {
  383. log.Error("loadPullRequest: %v", err)
  384. return
  385. }
  386. if err = issue.PullRequest.LoadIssue(); err != nil {
  387. log.Error("LoadIssue: %v", err)
  388. return
  389. }
  390. err = PrepareWebhooks(issue.Repo, HookEventPullRequest, &api.PullRequestPayload{
  391. Action: api.HookIssueLabelUpdated,
  392. Index: issue.Index,
  393. PullRequest: issue.PullRequest.APIFormat(),
  394. Repository: issue.Repo.APIFormat(AccessModeNone),
  395. Sender: doer.APIFormat(),
  396. })
  397. } else {
  398. err = PrepareWebhooks(issue.Repo, HookEventIssues, &api.IssuePayload{
  399. Action: api.HookIssueLabelUpdated,
  400. Index: issue.Index,
  401. Issue: issue.APIFormat(),
  402. Repository: issue.Repo.APIFormat(mode),
  403. Sender: doer.APIFormat(),
  404. })
  405. }
  406. if err != nil {
  407. log.Error("PrepareWebhooks [is_pull: %v]: %v", issue.IsPull, err)
  408. } else {
  409. go HookQueue.Add(issue.RepoID)
  410. }
  411. }
  412. func (issue *Issue) addLabel(e *xorm.Session, label *Label, doer *User) error {
  413. return newIssueLabel(e, issue, label, doer)
  414. }
  415. // AddLabel adds a new label to the issue.
  416. func (issue *Issue) AddLabel(doer *User, label *Label) error {
  417. if err := NewIssueLabel(issue, label, doer); err != nil {
  418. return err
  419. }
  420. issue.sendLabelUpdatedWebhook(doer)
  421. return nil
  422. }
  423. func (issue *Issue) addLabels(e *xorm.Session, labels []*Label, doer *User) error {
  424. return newIssueLabels(e, issue, labels, doer)
  425. }
  426. // AddLabels adds a list of new labels to the issue.
  427. func (issue *Issue) AddLabels(doer *User, labels []*Label) error {
  428. if err := NewIssueLabels(issue, labels, doer); err != nil {
  429. return err
  430. }
  431. issue.sendLabelUpdatedWebhook(doer)
  432. return nil
  433. }
  434. func (issue *Issue) getLabels(e Engine) (err error) {
  435. if len(issue.Labels) > 0 {
  436. return nil
  437. }
  438. issue.Labels, err = getLabelsByIssueID(e, issue.ID)
  439. if err != nil {
  440. return fmt.Errorf("getLabelsByIssueID: %v", err)
  441. }
  442. return nil
  443. }
  444. func (issue *Issue) removeLabel(e *xorm.Session, doer *User, label *Label) error {
  445. return deleteIssueLabel(e, issue, label, doer)
  446. }
  447. // RemoveLabel removes a label from issue by given ID.
  448. func (issue *Issue) RemoveLabel(doer *User, label *Label) error {
  449. if err := issue.loadRepo(x); err != nil {
  450. return err
  451. }
  452. perm, err := GetUserRepoPermission(issue.Repo, doer)
  453. if err != nil {
  454. return err
  455. }
  456. if !perm.CanWriteIssuesOrPulls(issue.IsPull) {
  457. return ErrLabelNotExist{}
  458. }
  459. if err := DeleteIssueLabel(issue, label, doer); err != nil {
  460. return err
  461. }
  462. issue.sendLabelUpdatedWebhook(doer)
  463. return nil
  464. }
  465. func (issue *Issue) clearLabels(e *xorm.Session, doer *User) (err error) {
  466. if err = issue.getLabels(e); err != nil {
  467. return fmt.Errorf("getLabels: %v", err)
  468. }
  469. for i := range issue.Labels {
  470. if err = issue.removeLabel(e, doer, issue.Labels[i]); err != nil {
  471. return fmt.Errorf("removeLabel: %v", err)
  472. }
  473. }
  474. return nil
  475. }
  476. // ClearLabels removes all issue labels as the given user.
  477. // Triggers appropriate WebHooks, if any.
  478. func (issue *Issue) ClearLabels(doer *User) (err error) {
  479. sess := x.NewSession()
  480. defer sess.Close()
  481. if err = sess.Begin(); err != nil {
  482. return err
  483. }
  484. if err := issue.loadRepo(sess); err != nil {
  485. return err
  486. } else if err = issue.loadPullRequest(sess); err != nil {
  487. return err
  488. }
  489. perm, err := getUserRepoPermission(sess, issue.Repo, doer)
  490. if err != nil {
  491. return err
  492. }
  493. if !perm.CanWriteIssuesOrPulls(issue.IsPull) {
  494. return ErrLabelNotExist{}
  495. }
  496. if err = issue.clearLabels(sess, doer); err != nil {
  497. return err
  498. }
  499. if err = sess.Commit(); err != nil {
  500. return fmt.Errorf("Commit: %v", err)
  501. }
  502. if err = issue.loadPoster(x); err != nil {
  503. return fmt.Errorf("loadPoster: %v", err)
  504. }
  505. mode, _ := AccessLevel(issue.Poster, issue.Repo)
  506. if issue.IsPull {
  507. err = issue.PullRequest.LoadIssue()
  508. if err != nil {
  509. log.Error("LoadIssue: %v", err)
  510. return
  511. }
  512. err = PrepareWebhooks(issue.Repo, HookEventPullRequest, &api.PullRequestPayload{
  513. Action: api.HookIssueLabelCleared,
  514. Index: issue.Index,
  515. PullRequest: issue.PullRequest.APIFormat(),
  516. Repository: issue.Repo.APIFormat(mode),
  517. Sender: doer.APIFormat(),
  518. })
  519. } else {
  520. err = PrepareWebhooks(issue.Repo, HookEventIssues, &api.IssuePayload{
  521. Action: api.HookIssueLabelCleared,
  522. Index: issue.Index,
  523. Issue: issue.APIFormat(),
  524. Repository: issue.Repo.APIFormat(mode),
  525. Sender: doer.APIFormat(),
  526. })
  527. }
  528. if err != nil {
  529. log.Error("PrepareWebhooks [is_pull: %v]: %v", issue.IsPull, err)
  530. } else {
  531. go HookQueue.Add(issue.RepoID)
  532. }
  533. return nil
  534. }
  535. type labelSorter []*Label
  536. func (ts labelSorter) Len() int {
  537. return len([]*Label(ts))
  538. }
  539. func (ts labelSorter) Less(i, j int) bool {
  540. return []*Label(ts)[i].ID < []*Label(ts)[j].ID
  541. }
  542. func (ts labelSorter) Swap(i, j int) {
  543. []*Label(ts)[i], []*Label(ts)[j] = []*Label(ts)[j], []*Label(ts)[i]
  544. }
  545. // ReplaceLabels removes all current labels and add new labels to the issue.
  546. // Triggers appropriate WebHooks, if any.
  547. func (issue *Issue) ReplaceLabels(labels []*Label, doer *User) (err error) {
  548. sess := x.NewSession()
  549. defer sess.Close()
  550. if err = sess.Begin(); err != nil {
  551. return err
  552. }
  553. if err = issue.loadLabels(sess); err != nil {
  554. return err
  555. }
  556. sort.Sort(labelSorter(labels))
  557. sort.Sort(labelSorter(issue.Labels))
  558. var toAdd, toRemove []*Label
  559. addIndex, removeIndex := 0, 0
  560. for addIndex < len(labels) && removeIndex < len(issue.Labels) {
  561. addLabel := labels[addIndex]
  562. removeLabel := issue.Labels[removeIndex]
  563. if addLabel.ID == removeLabel.ID {
  564. addIndex++
  565. removeIndex++
  566. } else if addLabel.ID < removeLabel.ID {
  567. toAdd = append(toAdd, addLabel)
  568. addIndex++
  569. } else {
  570. toRemove = append(toRemove, removeLabel)
  571. removeIndex++
  572. }
  573. }
  574. toAdd = append(toAdd, labels[addIndex:]...)
  575. toRemove = append(toRemove, issue.Labels[removeIndex:]...)
  576. if len(toAdd) > 0 {
  577. if err = issue.addLabels(sess, toAdd, doer); err != nil {
  578. return fmt.Errorf("addLabels: %v", err)
  579. }
  580. }
  581. for _, l := range toRemove {
  582. if err = issue.removeLabel(sess, doer, l); err != nil {
  583. return fmt.Errorf("removeLabel: %v", err)
  584. }
  585. }
  586. return sess.Commit()
  587. }
  588. // ReadBy sets issue to be read by given user.
  589. func (issue *Issue) ReadBy(userID int64) error {
  590. if err := UpdateIssueUserByRead(userID, issue.ID); err != nil {
  591. return err
  592. }
  593. return setNotificationStatusReadIfUnread(x, userID, issue.ID)
  594. }
  595. func updateIssueCols(e Engine, issue *Issue, cols ...string) error {
  596. if _, err := e.ID(issue.ID).Cols(cols...).Update(issue); err != nil {
  597. return err
  598. }
  599. return nil
  600. }
  601. // UpdateIssueCols only updates values of specific columns for given issue.
  602. func UpdateIssueCols(issue *Issue, cols ...string) error {
  603. return updateIssueCols(x, issue, cols...)
  604. }
  605. func (issue *Issue) changeStatus(e *xorm.Session, doer *User, isClosed bool) (err error) {
  606. // Reload the issue
  607. currentIssue, err := getIssueByID(e, issue.ID)
  608. if err != nil {
  609. return err
  610. }
  611. // Nothing should be performed if current status is same as target status
  612. if currentIssue.IsClosed == isClosed {
  613. return nil
  614. }
  615. // Check for open dependencies
  616. if isClosed && issue.Repo.isDependenciesEnabled(e) {
  617. // only check if dependencies are enabled and we're about to close an issue, otherwise reopening an issue would fail when there are unsatisfied dependencies
  618. noDeps, err := issueNoDependenciesLeft(e, issue)
  619. if err != nil {
  620. return err
  621. }
  622. if !noDeps {
  623. return ErrDependenciesLeft{issue.ID}
  624. }
  625. }
  626. issue.IsClosed = isClosed
  627. if isClosed {
  628. issue.ClosedUnix = util.TimeStampNow()
  629. } else {
  630. issue.ClosedUnix = 0
  631. }
  632. if err = updateIssueCols(e, issue, "is_closed", "closed_unix"); err != nil {
  633. return err
  634. }
  635. // Update issue count of labels
  636. if err = issue.getLabels(e); err != nil {
  637. return err
  638. }
  639. for idx := range issue.Labels {
  640. if issue.IsClosed {
  641. issue.Labels[idx].NumClosedIssues++
  642. } else {
  643. issue.Labels[idx].NumClosedIssues--
  644. }
  645. if err = updateLabel(e, issue.Labels[idx]); err != nil {
  646. return err
  647. }
  648. }
  649. // Update issue count of milestone
  650. if err = changeMilestoneIssueStats(e, issue); err != nil {
  651. return err
  652. }
  653. // New action comment
  654. if _, err = createStatusComment(e, doer, issue); err != nil {
  655. return err
  656. }
  657. return nil
  658. }
  659. // ChangeStatus changes issue status to open or closed.
  660. func (issue *Issue) ChangeStatus(doer *User, isClosed bool) (err error) {
  661. sess := x.NewSession()
  662. defer sess.Close()
  663. if err = sess.Begin(); err != nil {
  664. return err
  665. }
  666. if err = issue.loadRepo(sess); err != nil {
  667. return err
  668. }
  669. if err = issue.loadPoster(sess); err != nil {
  670. return err
  671. }
  672. if err = issue.changeStatus(sess, doer, isClosed); err != nil {
  673. return err
  674. }
  675. if err = sess.Commit(); err != nil {
  676. return fmt.Errorf("Commit: %v", err)
  677. }
  678. sess.Close()
  679. mode, _ := AccessLevel(issue.Poster, issue.Repo)
  680. if issue.IsPull {
  681. if err = issue.loadPullRequest(sess); err != nil {
  682. return err
  683. }
  684. // Merge pull request calls issue.changeStatus so we need to handle separately.
  685. apiPullRequest := &api.PullRequestPayload{
  686. Index: issue.Index,
  687. PullRequest: issue.PullRequest.APIFormat(),
  688. Repository: issue.Repo.APIFormat(mode),
  689. Sender: doer.APIFormat(),
  690. }
  691. if isClosed {
  692. apiPullRequest.Action = api.HookIssueClosed
  693. } else {
  694. apiPullRequest.Action = api.HookIssueReOpened
  695. }
  696. err = PrepareWebhooks(issue.Repo, HookEventPullRequest, apiPullRequest)
  697. } else {
  698. apiIssue := &api.IssuePayload{
  699. Index: issue.Index,
  700. Issue: issue.APIFormat(),
  701. Repository: issue.Repo.APIFormat(mode),
  702. Sender: doer.APIFormat(),
  703. }
  704. if isClosed {
  705. apiIssue.Action = api.HookIssueClosed
  706. } else {
  707. apiIssue.Action = api.HookIssueReOpened
  708. }
  709. err = PrepareWebhooks(issue.Repo, HookEventIssues, apiIssue)
  710. }
  711. if err != nil {
  712. log.Error("PrepareWebhooks [is_pull: %v, is_closed: %v]: %v", issue.IsPull, isClosed, err)
  713. } else {
  714. go HookQueue.Add(issue.Repo.ID)
  715. }
  716. return nil
  717. }
  718. // ChangeTitle changes the title of this issue, as the given user.
  719. func (issue *Issue) ChangeTitle(doer *User, title string) (err error) {
  720. oldTitle := issue.Title
  721. issue.Title = title
  722. sess := x.NewSession()
  723. defer sess.Close()
  724. if err = sess.Begin(); err != nil {
  725. return err
  726. }
  727. if err = updateIssueCols(sess, issue, "name"); err != nil {
  728. return fmt.Errorf("updateIssueCols: %v", err)
  729. }
  730. if err = issue.loadRepo(sess); err != nil {
  731. return fmt.Errorf("loadRepo: %v", err)
  732. }
  733. if _, err = createChangeTitleComment(sess, doer, issue.Repo, issue, oldTitle, title); err != nil {
  734. return fmt.Errorf("createChangeTitleComment: %v", err)
  735. }
  736. if err = sess.Commit(); err != nil {
  737. return err
  738. }
  739. mode, _ := AccessLevel(issue.Poster, issue.Repo)
  740. if issue.IsPull {
  741. if err = issue.loadPullRequest(sess); err != nil {
  742. return fmt.Errorf("loadPullRequest: %v", err)
  743. }
  744. issue.PullRequest.Issue = issue
  745. err = PrepareWebhooks(issue.Repo, HookEventPullRequest, &api.PullRequestPayload{
  746. Action: api.HookIssueEdited,
  747. Index: issue.Index,
  748. Changes: &api.ChangesPayload{
  749. Title: &api.ChangesFromPayload{
  750. From: oldTitle,
  751. },
  752. },
  753. PullRequest: issue.PullRequest.APIFormat(),
  754. Repository: issue.Repo.APIFormat(mode),
  755. Sender: doer.APIFormat(),
  756. })
  757. } else {
  758. err = PrepareWebhooks(issue.Repo, HookEventIssues, &api.IssuePayload{
  759. Action: api.HookIssueEdited,
  760. Index: issue.Index,
  761. Changes: &api.ChangesPayload{
  762. Title: &api.ChangesFromPayload{
  763. From: oldTitle,
  764. },
  765. },
  766. Issue: issue.APIFormat(),
  767. Repository: issue.Repo.APIFormat(mode),
  768. Sender: issue.Poster.APIFormat(),
  769. })
  770. }
  771. if err != nil {
  772. log.Error("PrepareWebhooks [is_pull: %v]: %v", issue.IsPull, err)
  773. } else {
  774. go HookQueue.Add(issue.RepoID)
  775. }
  776. return nil
  777. }
  778. // AddDeletePRBranchComment adds delete branch comment for pull request issue
  779. func AddDeletePRBranchComment(doer *User, repo *Repository, issueID int64, branchName string) error {
  780. issue, err := getIssueByID(x, issueID)
  781. if err != nil {
  782. return err
  783. }
  784. sess := x.NewSession()
  785. defer sess.Close()
  786. if err := sess.Begin(); err != nil {
  787. return err
  788. }
  789. if _, err := createDeleteBranchComment(sess, doer, repo, issue, branchName); err != nil {
  790. return err
  791. }
  792. return sess.Commit()
  793. }
  794. // ChangeContent changes issue content, as the given user.
  795. func (issue *Issue) ChangeContent(doer *User, content string) (err error) {
  796. oldContent := issue.Content
  797. issue.Content = content
  798. if err = UpdateIssueCols(issue, "content"); err != nil {
  799. return fmt.Errorf("UpdateIssueCols: %v", err)
  800. }
  801. mode, _ := AccessLevel(issue.Poster, issue.Repo)
  802. if issue.IsPull {
  803. issue.PullRequest.Issue = issue
  804. err = PrepareWebhooks(issue.Repo, HookEventPullRequest, &api.PullRequestPayload{
  805. Action: api.HookIssueEdited,
  806. Index: issue.Index,
  807. Changes: &api.ChangesPayload{
  808. Body: &api.ChangesFromPayload{
  809. From: oldContent,
  810. },
  811. },
  812. PullRequest: issue.PullRequest.APIFormat(),
  813. Repository: issue.Repo.APIFormat(mode),
  814. Sender: doer.APIFormat(),
  815. })
  816. } else {
  817. err = PrepareWebhooks(issue.Repo, HookEventIssues, &api.IssuePayload{
  818. Action: api.HookIssueEdited,
  819. Index: issue.Index,
  820. Changes: &api.ChangesPayload{
  821. Body: &api.ChangesFromPayload{
  822. From: oldContent,
  823. },
  824. },
  825. Issue: issue.APIFormat(),
  826. Repository: issue.Repo.APIFormat(mode),
  827. Sender: doer.APIFormat(),
  828. })
  829. }
  830. if err != nil {
  831. log.Error("PrepareWebhooks [is_pull: %v]: %v", issue.IsPull, err)
  832. } else {
  833. go HookQueue.Add(issue.RepoID)
  834. }
  835. return nil
  836. }
  837. // GetTasks returns the amount of tasks in the issues content
  838. func (issue *Issue) GetTasks() int {
  839. return len(issueTasksPat.FindAllStringIndex(issue.Content, -1))
  840. }
  841. // GetTasksDone returns the amount of completed tasks in the issues content
  842. func (issue *Issue) GetTasksDone() int {
  843. return len(issueTasksDonePat.FindAllStringIndex(issue.Content, -1))
  844. }
  845. // GetLastEventTimestamp returns the last user visible event timestamp, either the creation of this issue or the close.
  846. func (issue *Issue) GetLastEventTimestamp() util.TimeStamp {
  847. if issue.IsClosed {
  848. return issue.ClosedUnix
  849. }
  850. return issue.CreatedUnix
  851. }
  852. // GetLastEventLabel returns the localization label for the current issue.
  853. func (issue *Issue) GetLastEventLabel() string {
  854. if issue.IsClosed {
  855. if issue.IsPull && issue.PullRequest.HasMerged {
  856. return "repo.pulls.merged_by"
  857. }
  858. return "repo.issues.closed_by"
  859. }
  860. return "repo.issues.opened_by"
  861. }
  862. // GetLastEventLabelFake returns the localization label for the current issue without providing a link in the username.
  863. func (issue *Issue) GetLastEventLabelFake() string {
  864. if issue.IsClosed {
  865. if issue.IsPull && issue.PullRequest.HasMerged {
  866. return "repo.pulls.merged_by_fake"
  867. }
  868. return "repo.issues.closed_by_fake"
  869. }
  870. return "repo.issues.opened_by_fake"
  871. }
  872. // NewIssueOptions represents the options of a new issue.
  873. type NewIssueOptions struct {
  874. Repo *Repository
  875. Issue *Issue
  876. LabelIDs []int64
  877. AssigneeIDs []int64
  878. Attachments []string // In UUID format.
  879. IsPull bool
  880. }
  881. // GetMaxIndexOfIssue returns the max index on issue
  882. func GetMaxIndexOfIssue(repoID int64) (int64, error) {
  883. return getMaxIndexOfIssue(x, repoID)
  884. }
  885. func getMaxIndexOfIssue(e Engine, repoID int64) (int64, error) {
  886. var (
  887. maxIndex int64
  888. has bool
  889. err error
  890. )
  891. has, err = e.SQL("SELECT COALESCE((SELECT MAX(`index`) FROM issue WHERE repo_id = ?),0)", repoID).Get(&maxIndex)
  892. if err != nil {
  893. return 0, err
  894. } else if !has {
  895. return 0, errors.New("Retrieve Max index from issue failed")
  896. }
  897. return maxIndex, nil
  898. }
  899. func newIssue(e *xorm.Session, doer *User, opts NewIssueOptions) (err error) {
  900. opts.Issue.Title = strings.TrimSpace(opts.Issue.Title)
  901. maxIndex, err := getMaxIndexOfIssue(e, opts.Issue.RepoID)
  902. if err != nil {
  903. return err
  904. }
  905. opts.Issue.Index = maxIndex + 1
  906. if opts.Issue.MilestoneID > 0 {
  907. milestone, err := getMilestoneByRepoID(e, opts.Issue.RepoID, opts.Issue.MilestoneID)
  908. if err != nil && !IsErrMilestoneNotExist(err) {
  909. return fmt.Errorf("getMilestoneByID: %v", err)
  910. }
  911. // Assume milestone is invalid and drop silently.
  912. opts.Issue.MilestoneID = 0
  913. if milestone != nil {
  914. opts.Issue.MilestoneID = milestone.ID
  915. opts.Issue.Milestone = milestone
  916. }
  917. }
  918. // Keep the old assignee id thingy for compatibility reasons
  919. if opts.Issue.AssigneeID > 0 {
  920. isAdded := false
  921. // Check if the user has already been passed to issue.AssigneeIDs, if not, add it
  922. for _, aID := range opts.AssigneeIDs {
  923. if aID == opts.Issue.AssigneeID {
  924. isAdded = true
  925. break
  926. }
  927. }
  928. if !isAdded {
  929. opts.AssigneeIDs = append(opts.AssigneeIDs, opts.Issue.AssigneeID)
  930. }
  931. }
  932. // Check for and validate assignees
  933. if len(opts.AssigneeIDs) > 0 {
  934. for _, assigneeID := range opts.AssigneeIDs {
  935. user, err := getUserByID(e, assigneeID)
  936. if err != nil {
  937. return fmt.Errorf("getUserByID [user_id: %d, repo_id: %d]: %v", assigneeID, opts.Repo.ID, err)
  938. }
  939. valid, err := canBeAssigned(e, user, opts.Repo)
  940. if err != nil {
  941. return fmt.Errorf("canBeAssigned [user_id: %d, repo_id: %d]: %v", assigneeID, opts.Repo.ID, err)
  942. }
  943. if !valid {
  944. return ErrUserDoesNotHaveAccessToRepo{UserID: assigneeID, RepoName: opts.Repo.Name}
  945. }
  946. }
  947. }
  948. // Milestone and assignee validation should happen before insert actual object.
  949. if _, err = e.Insert(opts.Issue); err != nil {
  950. return err
  951. }
  952. if opts.Issue.MilestoneID > 0 {
  953. if err = changeMilestoneAssign(e, doer, opts.Issue, -1); err != nil {
  954. return err
  955. }
  956. }
  957. // Insert the assignees
  958. for _, assigneeID := range opts.AssigneeIDs {
  959. err = opts.Issue.changeAssignee(e, doer, assigneeID, true)
  960. if err != nil {
  961. return err
  962. }
  963. }
  964. if opts.IsPull {
  965. _, err = e.Exec("UPDATE `repository` SET num_pulls = num_pulls + 1 WHERE id = ?", opts.Issue.RepoID)
  966. } else {
  967. _, err = e.Exec("UPDATE `repository` SET num_issues = num_issues + 1 WHERE id = ?", opts.Issue.RepoID)
  968. }
  969. if err != nil {
  970. return err
  971. }
  972. if len(opts.LabelIDs) > 0 {
  973. // During the session, SQLite3 driver cannot handle retrieve objects after update something.
  974. // So we have to get all needed labels first.
  975. labels := make([]*Label, 0, len(opts.LabelIDs))
  976. if err = e.In("id", opts.LabelIDs).Find(&labels); err != nil {
  977. return fmt.Errorf("find all labels [label_ids: %v]: %v", opts.LabelIDs, err)
  978. }
  979. if err = opts.Issue.loadPoster(e); err != nil {
  980. return err
  981. }
  982. for _, label := range labels {
  983. // Silently drop invalid labels.
  984. if label.RepoID != opts.Repo.ID {
  985. continue
  986. }
  987. if err = opts.Issue.addLabel(e, label, opts.Issue.Poster); err != nil {
  988. return fmt.Errorf("addLabel [id: %d]: %v", label.ID, err)
  989. }
  990. }
  991. }
  992. if err = newIssueUsers(e, opts.Repo, opts.Issue); err != nil {
  993. return err
  994. }
  995. if len(opts.Attachments) > 0 {
  996. attachments, err := getAttachmentsByUUIDs(e, opts.Attachments)
  997. if err != nil {
  998. return fmt.Errorf("getAttachmentsByUUIDs [uuids: %v]: %v", opts.Attachments, err)
  999. }
  1000. for i := 0; i < len(attachments); i++ {
  1001. attachments[i].IssueID = opts.Issue.ID
  1002. if _, err = e.ID(attachments[i].ID).Update(attachments[i]); err != nil {
  1003. return fmt.Errorf("update attachment [id: %d]: %v", attachments[i].ID, err)
  1004. }
  1005. }
  1006. }
  1007. return opts.Issue.loadAttributes(e)
  1008. }
  1009. // NewIssue creates new issue with labels for repository.
  1010. func NewIssue(repo *Repository, issue *Issue, labelIDs []int64, assigneeIDs []int64, uuids []string) (err error) {
  1011. sess := x.NewSession()
  1012. defer sess.Close()
  1013. if err = sess.Begin(); err != nil {
  1014. return err
  1015. }
  1016. if err = newIssue(sess, issue.Poster, NewIssueOptions{
  1017. Repo: repo,
  1018. Issue: issue,
  1019. LabelIDs: labelIDs,
  1020. Attachments: uuids,
  1021. AssigneeIDs: assigneeIDs,
  1022. }); err != nil {
  1023. if IsErrUserDoesNotHaveAccessToRepo(err) {
  1024. return err
  1025. }
  1026. return fmt.Errorf("newIssue: %v", err)
  1027. }
  1028. if err = sess.Commit(); err != nil {
  1029. return fmt.Errorf("Commit: %v", err)
  1030. }
  1031. if err = NotifyWatchers(&Action{
  1032. ActUserID: issue.Poster.ID,
  1033. ActUser: issue.Poster,
  1034. OpType: ActionCreateIssue,
  1035. Content: fmt.Sprintf("%d|%s", issue.Index, issue.Title),
  1036. RepoID: repo.ID,
  1037. Repo: repo,
  1038. IsPrivate: repo.IsPrivate,
  1039. }); err != nil {
  1040. log.Error("NotifyWatchers: %v", err)
  1041. }
  1042. mode, _ := AccessLevel(issue.Poster, issue.Repo)
  1043. if err = PrepareWebhooks(repo, HookEventIssues, &api.IssuePayload{
  1044. Action: api.HookIssueOpened,
  1045. Index: issue.Index,
  1046. Issue: issue.APIFormat(),
  1047. Repository: repo.APIFormat(mode),
  1048. Sender: issue.Poster.APIFormat(),
  1049. }); err != nil {
  1050. log.Error("PrepareWebhooks: %v", err)
  1051. } else {
  1052. go HookQueue.Add(issue.RepoID)
  1053. }
  1054. return nil
  1055. }
  1056. // GetIssueByIndex returns raw issue without loading attributes by index in a repository.
  1057. func GetIssueByIndex(repoID, index int64) (*Issue, error) {
  1058. issue := &Issue{
  1059. RepoID: repoID,
  1060. Index: index,
  1061. }
  1062. has, err := x.Get(issue)
  1063. if err != nil {
  1064. return nil, err
  1065. } else if !has {
  1066. return nil, ErrIssueNotExist{0, repoID, index}
  1067. }
  1068. return issue, nil
  1069. }
  1070. // GetIssueWithAttrsByIndex returns issue by index in a repository.
  1071. func GetIssueWithAttrsByIndex(repoID, index int64) (*Issue, error) {
  1072. issue, err := GetIssueByIndex(repoID, index)
  1073. if err != nil {
  1074. return nil, err
  1075. }
  1076. return issue, issue.LoadAttributes()
  1077. }
  1078. func getIssueByID(e Engine, id int64) (*Issue, error) {
  1079. issue := new(Issue)
  1080. has, err := e.ID(id).Get(issue)
  1081. if err != nil {
  1082. return nil, err
  1083. } else if !has {
  1084. return nil, ErrIssueNotExist{id, 0, 0}
  1085. }
  1086. return issue, nil
  1087. }
  1088. // GetIssueWithAttrsByID returns an issue with attributes by given ID.
  1089. func GetIssueWithAttrsByID(id int64) (*Issue, error) {
  1090. issue, err := getIssueByID(x, id)
  1091. if err != nil {
  1092. return nil, err
  1093. }
  1094. return issue, issue.loadAttributes(x)
  1095. }
  1096. // GetIssueByID returns an issue by given ID.
  1097. func GetIssueByID(id int64) (*Issue, error) {
  1098. return getIssueByID(x, id)
  1099. }
  1100. func getIssuesByIDs(e Engine, issueIDs []int64) ([]*Issue, error) {
  1101. issues := make([]*Issue, 0, 10)
  1102. return issues, e.In("id", issueIDs).Find(&issues)
  1103. }
  1104. func getIssueIDsByRepoID(e Engine, repoID int64) ([]int64, error) {
  1105. var ids = make([]int64, 0, 10)
  1106. err := e.Table("issue").Where("repo_id = ?", repoID).Find(&ids)
  1107. return ids, err
  1108. }
  1109. // GetIssueIDsByRepoID returns all issue ids by repo id
  1110. func GetIssueIDsByRepoID(repoID int64) ([]int64, error) {
  1111. return getIssueIDsByRepoID(x, repoID)
  1112. }
  1113. // GetIssuesByIDs return issues with the given IDs.
  1114. func GetIssuesByIDs(issueIDs []int64) ([]*Issue, error) {
  1115. return getIssuesByIDs(x, issueIDs)
  1116. }
  1117. // IssuesOptions represents options of an issue.
  1118. type IssuesOptions struct {
  1119. RepoIDs []int64 // include all repos if empty
  1120. AssigneeID int64
  1121. PosterID int64
  1122. MentionedID int64
  1123. MilestoneID int64
  1124. Page int
  1125. PageSize int
  1126. IsClosed util.OptionalBool
  1127. IsPull util.OptionalBool
  1128. LabelIDs []int64
  1129. SortType string
  1130. IssueIDs []int64
  1131. }
  1132. // sortIssuesSession sort an issues-related session based on the provided
  1133. // sortType string
  1134. func sortIssuesSession(sess *xorm.Session, sortType string) {
  1135. switch sortType {
  1136. case "oldest":
  1137. sess.Asc("issue.created_unix")
  1138. case "recentupdate":
  1139. sess.Desc("issue.updated_unix")
  1140. case "leastupdate":
  1141. sess.Asc("issue.updated_unix")
  1142. case "mostcomment":
  1143. sess.Desc("issue.num_comments")
  1144. case "leastcomment":
  1145. sess.Asc("issue.num_comments")
  1146. case "priority":
  1147. sess.Desc("issue.priority")
  1148. case "nearduedate":
  1149. sess.Asc("issue.deadline_unix")
  1150. case "farduedate":
  1151. sess.Desc("issue.deadline_unix")
  1152. default:
  1153. sess.Desc("issue.created_unix")
  1154. }
  1155. }
  1156. func (opts *IssuesOptions) setupSession(sess *xorm.Session) {
  1157. if opts.Page >= 0 && opts.PageSize > 0 {
  1158. var start int
  1159. if opts.Page == 0 {
  1160. start = 0
  1161. } else {
  1162. start = (opts.Page - 1) * opts.PageSize
  1163. }
  1164. sess.Limit(opts.PageSize, start)
  1165. }
  1166. if len(opts.IssueIDs) > 0 {
  1167. sess.In("issue.id", opts.IssueIDs)
  1168. }
  1169. if len(opts.RepoIDs) > 0 {
  1170. // In case repository IDs are provided but actually no repository has issue.
  1171. sess.In("issue.repo_id", opts.RepoIDs)
  1172. }
  1173. switch opts.IsClosed {
  1174. case util.OptionalBoolTrue:
  1175. sess.And("issue.is_closed=?", true)
  1176. case util.OptionalBoolFalse:
  1177. sess.And("issue.is_closed=?", false)
  1178. }
  1179. if opts.AssigneeID > 0 {
  1180. sess.Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  1181. And("issue_assignees.assignee_id = ?", opts.AssigneeID)
  1182. }
  1183. if opts.PosterID > 0 {
  1184. sess.And("issue.poster_id=?", opts.PosterID)
  1185. }
  1186. if opts.MentionedID > 0 {
  1187. sess.Join("INNER", "issue_user", "issue.id = issue_user.issue_id").
  1188. And("issue_user.is_mentioned = ?", true).
  1189. And("issue_user.uid = ?", opts.MentionedID)
  1190. }
  1191. if opts.MilestoneID > 0 {
  1192. sess.And("issue.milestone_id=?", opts.MilestoneID)
  1193. }
  1194. switch opts.IsPull {
  1195. case util.OptionalBoolTrue:
  1196. sess.And("issue.is_pull=?", true)
  1197. case util.OptionalBoolFalse:
  1198. sess.And("issue.is_pull=?", false)
  1199. }
  1200. if opts.LabelIDs != nil {
  1201. for i, labelID := range opts.LabelIDs {
  1202. sess.Join("INNER", fmt.Sprintf("issue_label il%d", i),
  1203. fmt.Sprintf("issue.id = il%[1]d.issue_id AND il%[1]d.label_id = %[2]d", i, labelID))
  1204. }
  1205. }
  1206. }
  1207. // CountIssuesByRepo map from repoID to number of issues matching the options
  1208. func CountIssuesByRepo(opts *IssuesOptions) (map[int64]int64, error) {
  1209. sess := x.NewSession()
  1210. defer sess.Close()
  1211. opts.setupSession(sess)
  1212. countsSlice := make([]*struct {
  1213. RepoID int64
  1214. Count int64
  1215. }, 0, 10)
  1216. if err := sess.GroupBy("issue.repo_id").
  1217. Select("issue.repo_id AS repo_id, COUNT(*) AS count").
  1218. Table("issue").
  1219. Find(&countsSlice); err != nil {
  1220. return nil, err
  1221. }
  1222. countMap := make(map[int64]int64, len(countsSlice))
  1223. for _, c := range countsSlice {
  1224. countMap[c.RepoID] = c.Count
  1225. }
  1226. return countMap, nil
  1227. }
  1228. // Issues returns a list of issues by given conditions.
  1229. func Issues(opts *IssuesOptions) ([]*Issue, error) {
  1230. sess := x.NewSession()
  1231. defer sess.Close()
  1232. opts.setupSession(sess)
  1233. sortIssuesSession(sess, opts.SortType)
  1234. issues := make([]*Issue, 0, setting.UI.IssuePagingNum)
  1235. if err := sess.Find(&issues); err != nil {
  1236. return nil, fmt.Errorf("Find: %v", err)
  1237. }
  1238. sess.Close()
  1239. if err := IssueList(issues).LoadAttributes(); err != nil {
  1240. return nil, fmt.Errorf("LoadAttributes: %v", err)
  1241. }
  1242. return issues, nil
  1243. }
  1244. // GetParticipantsByIssueID returns all users who are participated in comments of an issue.
  1245. func GetParticipantsByIssueID(issueID int64) ([]*User, error) {
  1246. return getParticipantsByIssueID(x, issueID)
  1247. }
  1248. func getParticipantsByIssueID(e Engine, issueID int64) ([]*User, error) {
  1249. userIDs := make([]int64, 0, 5)
  1250. if err := e.Table("comment").Cols("poster_id").
  1251. Where("`comment`.issue_id = ?", issueID).
  1252. And("`comment`.type = ?", CommentTypeComment).
  1253. And("`user`.is_active = ?", true).
  1254. And("`user`.prohibit_login = ?", false).
  1255. Join("INNER", "`user`", "`user`.id = `comment`.poster_id").
  1256. Distinct("poster_id").
  1257. Find(&userIDs); err != nil {
  1258. return nil, fmt.Errorf("get poster IDs: %v", err)
  1259. }
  1260. if len(userIDs) == 0 {
  1261. return nil, nil
  1262. }
  1263. users := make([]*User, 0, len(userIDs))
  1264. return users, e.In("id", userIDs).Find(&users)
  1265. }
  1266. // UpdateIssueMentions extracts mentioned people from content and
  1267. // updates issue-user relations for them.
  1268. func UpdateIssueMentions(e Engine, issueID int64, mentions []string) error {
  1269. if len(mentions) == 0 {
  1270. return nil
  1271. }
  1272. for i := range mentions {
  1273. mentions[i] = strings.ToLower(mentions[i])
  1274. }
  1275. users := make([]*User, 0, len(mentions))
  1276. if err := e.In("lower_name", mentions).Asc("lower_name").Find(&users); err != nil {
  1277. return fmt.Errorf("find mentioned users: %v", err)
  1278. }
  1279. ids := make([]int64, 0, len(mentions))
  1280. for _, user := range users {
  1281. ids = append(ids, user.ID)
  1282. if !user.IsOrganization() || user.NumMembers == 0 {
  1283. continue
  1284. }
  1285. memberIDs := make([]int64, 0, user.NumMembers)
  1286. orgUsers, err := getOrgUsersByOrgID(e, user.ID)
  1287. if err != nil {
  1288. return fmt.Errorf("GetOrgUsersByOrgID [%d]: %v", user.ID, err)
  1289. }
  1290. for _, orgUser := range orgUsers {
  1291. memberIDs = append(memberIDs, orgUser.ID)
  1292. }
  1293. ids = append(ids, memberIDs...)
  1294. }
  1295. if err := UpdateIssueUsersByMentions(e, issueID, ids); err != nil {
  1296. return fmt.Errorf("UpdateIssueUsersByMentions: %v", err)
  1297. }
  1298. return nil
  1299. }
  1300. // IssueStats represents issue statistic information.
  1301. type IssueStats struct {
  1302. OpenCount, ClosedCount int64
  1303. YourRepositoriesCount int64
  1304. AssignCount int64
  1305. CreateCount int64
  1306. MentionCount int64
  1307. }
  1308. // Filter modes.
  1309. const (
  1310. FilterModeAll = iota
  1311. FilterModeAssign
  1312. FilterModeCreate
  1313. FilterModeMention
  1314. )
  1315. func parseCountResult(results []map[string][]byte) int64 {
  1316. if len(results) == 0 {
  1317. return 0
  1318. }
  1319. for _, result := range results[0] {
  1320. return com.StrTo(string(result)).MustInt64()
  1321. }
  1322. return 0
  1323. }
  1324. // IssueStatsOptions contains parameters accepted by GetIssueStats.
  1325. type IssueStatsOptions struct {
  1326. RepoID int64
  1327. Labels string
  1328. MilestoneID int64
  1329. AssigneeID int64
  1330. MentionedID int64
  1331. PosterID int64
  1332. IsPull util.OptionalBool
  1333. IssueIDs []int64
  1334. }
  1335. // GetIssueStats returns issue statistic information by given conditions.
  1336. func GetIssueStats(opts *IssueStatsOptions) (*IssueStats, error) {
  1337. stats := &IssueStats{}
  1338. countSession := func(opts *IssueStatsOptions) *xorm.Session {
  1339. sess := x.
  1340. Where("issue.repo_id = ?", opts.RepoID)
  1341. if len(opts.IssueIDs) > 0 {
  1342. sess.In("issue.id", opts.IssueIDs)
  1343. }
  1344. if len(opts.Labels) > 0 && opts.Labels != "0" {
  1345. labelIDs, err := base.StringsToInt64s(strings.Split(opts.Labels, ","))
  1346. if err != nil {
  1347. log.Warn("Malformed Labels argument: %s", opts.Labels)
  1348. } else {
  1349. for i, labelID := range labelIDs {
  1350. sess.Join("INNER", fmt.Sprintf("issue_label il%d", i),
  1351. fmt.Sprintf("issue.id = il%[1]d.issue_id AND il%[1]d.label_id = %[2]d", i, labelID))
  1352. }
  1353. }
  1354. }
  1355. if opts.MilestoneID > 0 {
  1356. sess.And("issue.milestone_id = ?", opts.MilestoneID)
  1357. }
  1358. if opts.AssigneeID > 0 {
  1359. sess.Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  1360. And("issue_assignees.assignee_id = ?", opts.AssigneeID)
  1361. }
  1362. if opts.PosterID > 0 {
  1363. sess.And("issue.poster_id = ?", opts.PosterID)
  1364. }
  1365. if opts.MentionedID > 0 {
  1366. sess.Join("INNER", "issue_user", "issue.id = issue_user.issue_id").
  1367. And("issue_user.uid = ?", opts.MentionedID).
  1368. And("issue_user.is_mentioned = ?", true)
  1369. }
  1370. switch opts.IsPull {
  1371. case util.OptionalBoolTrue:
  1372. sess.And("issue.is_pull=?", true)
  1373. case util.OptionalBoolFalse:
  1374. sess.And("issue.is_pull=?", false)
  1375. }
  1376. return sess
  1377. }
  1378. var err error
  1379. stats.OpenCount, err = countSession(opts).
  1380. And("issue.is_closed = ?", false).
  1381. Count(new(Issue))
  1382. if err != nil {
  1383. return stats, err
  1384. }
  1385. stats.ClosedCount, err = countSession(opts).
  1386. And("issue.is_closed = ?", true).
  1387. Count(new(Issue))
  1388. return stats, err
  1389. }
  1390. // UserIssueStatsOptions contains parameters accepted by GetUserIssueStats.
  1391. type UserIssueStatsOptions struct {
  1392. UserID int64
  1393. RepoID int64
  1394. UserRepoIDs []int64
  1395. FilterMode int
  1396. IsPull bool
  1397. IsClosed bool
  1398. }
  1399. // GetUserIssueStats returns issue statistic information for dashboard by given conditions.
  1400. func GetUserIssueStats(opts UserIssueStatsOptions) (*IssueStats, error) {
  1401. var err error
  1402. stats := &IssueStats{}
  1403. cond := builder.NewCond()
  1404. cond = cond.And(builder.Eq{"issue.is_pull": opts.IsPull})
  1405. if opts.RepoID > 0 {
  1406. cond = cond.And(builder.Eq{"issue.repo_id": opts.RepoID})
  1407. }
  1408. switch opts.FilterMode {
  1409. case FilterModeAll:
  1410. stats.OpenCount, err = x.Where(cond).And("is_closed = ?", false).
  1411. And(builder.In("issue.repo_id", opts.UserRepoIDs)).
  1412. Count(new(Issue))
  1413. if err != nil {
  1414. return nil, err
  1415. }
  1416. stats.ClosedCount, err = x.Where(cond).And("is_closed = ?", true).
  1417. And(builder.In("issue.repo_id", opts.UserRepoIDs)).
  1418. Count(new(Issue))
  1419. if err != nil {
  1420. return nil, err
  1421. }
  1422. case FilterModeAssign:
  1423. stats.OpenCount, err = x.Where(cond).And("is_closed = ?", false).
  1424. Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  1425. And("issue_assignees.assignee_id = ?", opts.UserID).
  1426. Count(new(Issue))
  1427. if err != nil {
  1428. return nil, err
  1429. }
  1430. stats.ClosedCount, err = x.Where(cond).And("is_closed = ?", true).
  1431. Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  1432. And("issue_assignees.assignee_id = ?", opts.UserID).
  1433. Count(new(Issue))
  1434. if err != nil {
  1435. return nil, err
  1436. }
  1437. case FilterModeCreate:
  1438. stats.OpenCount, err = x.Where(cond).And("is_closed = ?", false).
  1439. And("poster_id = ?", opts.UserID).
  1440. Count(new(Issue))
  1441. if err != nil {
  1442. return nil, err
  1443. }
  1444. stats.ClosedCount, err = x.Where(cond).And("is_closed = ?", true).
  1445. And("poster_id = ?", opts.UserID).
  1446. Count(new(Issue))
  1447. if err != nil {
  1448. return nil, err
  1449. }
  1450. }
  1451. cond = cond.And(builder.Eq{"issue.is_closed": opts.IsClosed})
  1452. stats.AssignCount, err = x.Where(cond).
  1453. Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  1454. And("issue_assignees.assignee_id = ?", opts.UserID).
  1455. Count(new(Issue))
  1456. if err != nil {
  1457. return nil, err
  1458. }
  1459. stats.CreateCount, err = x.Where(cond).
  1460. And("poster_id = ?", opts.UserID).
  1461. Count(new(Issue))
  1462. if err != nil {
  1463. return nil, err
  1464. }
  1465. stats.YourRepositoriesCount, err = x.Where(cond).
  1466. And(builder.In("issue.repo_id", opts.UserRepoIDs)).
  1467. Count(new(Issue))
  1468. if err != nil {
  1469. return nil, err
  1470. }
  1471. return stats, nil
  1472. }
  1473. // GetRepoIssueStats returns number of open and closed repository issues by given filter mode.
  1474. func GetRepoIssueStats(repoID, uid int64, filterMode int, isPull bool) (numOpen int64, numClosed int64) {
  1475. countSession := func(isClosed, isPull bool, repoID int64) *xorm.Session {
  1476. sess := x.
  1477. Where("is_closed = ?", isClosed).
  1478. And("is_pull = ?", isPull).
  1479. And("repo_id = ?", repoID)
  1480. return sess
  1481. }
  1482. openCountSession := countSession(false, isPull, repoID)
  1483. closedCountSession := countSession(true, isPull, repoID)
  1484. switch filterMode {
  1485. case FilterModeAssign:
  1486. openCountSession.Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  1487. And("issue_assignees.assignee_id = ?", uid)
  1488. closedCountSession.Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  1489. And("issue_assignees.assignee_id = ?", uid)
  1490. case FilterModeCreate:
  1491. openCountSession.And("poster_id = ?", uid)
  1492. closedCountSession.And("poster_id = ?", uid)
  1493. }
  1494. openResult, _ := openCountSession.Count(new(Issue))
  1495. closedResult, _ := closedCountSession.Count(new(Issue))
  1496. return openResult, closedResult
  1497. }
  1498. // SearchIssueIDsByKeyword search issues on database
  1499. func SearchIssueIDsByKeyword(kw string, repoID int64, limit, start int) (int64, []int64, error) {
  1500. var repoCond = builder.Eq{"repo_id": repoID}
  1501. var subQuery = builder.Select("id").From("issue").Where(repoCond)
  1502. var cond = builder.And(
  1503. repoCond,
  1504. builder.Or(
  1505. builder.Like{"name", kw},
  1506. builder.Like{"content", kw},
  1507. builder.In("id", builder.Select("issue_id").
  1508. From("comment").
  1509. Where(builder.And(
  1510. builder.Eq{"type": CommentTypeComment},
  1511. builder.In("issue_id", subQuery),
  1512. builder.Like{"content", kw},
  1513. )),
  1514. ),
  1515. ),
  1516. )
  1517. var ids = make([]int64, 0, limit)
  1518. err := x.Distinct("id").Table("issue").Where(cond).Limit(limit, start).Find(&ids)
  1519. if err != nil {
  1520. return 0, nil, err
  1521. }
  1522. total, err := x.Distinct("id").Table("issue").Where(cond).Count()
  1523. if err != nil {
  1524. return 0, nil, err
  1525. }
  1526. return total, ids, nil
  1527. }
  1528. func updateIssue(e Engine, issue *Issue) error {
  1529. _, err := e.ID(issue.ID).AllCols().Update(issue)
  1530. if err != nil {
  1531. return err
  1532. }
  1533. return nil
  1534. }
  1535. // UpdateIssue updates all fields of given issue.
  1536. func UpdateIssue(issue *Issue) error {
  1537. return updateIssue(x, issue)
  1538. }
  1539. // UpdateIssueDeadline updates an issue deadline and adds comments. Setting a deadline to 0 means deleting it.
  1540. func UpdateIssueDeadline(issue *Issue, deadlineUnix util.TimeStamp, doer *User) (err error) {
  1541. // if the deadline hasn't changed do nothing
  1542. if issue.DeadlineUnix == deadlineUnix {
  1543. return nil
  1544. }
  1545. sess := x.NewSession()
  1546. defer sess.Close()
  1547. if err := sess.Begin(); err != nil {
  1548. return err
  1549. }
  1550. // Update the deadline
  1551. if err = updateIssueCols(sess, &Issue{ID: issue.ID, DeadlineUnix: deadlineUnix}, "deadline_unix"); err != nil {
  1552. return err
  1553. }
  1554. // Make the comment
  1555. if _, err = createDeadlineComment(sess, doer, issue, deadlineUnix); err != nil {
  1556. return fmt.Errorf("createRemovedDueDateComment: %v", err)
  1557. }
  1558. return sess.Commit()
  1559. }
  1560. // Get Blocked By Dependencies, aka all issues this issue is blocked by.
  1561. func (issue *Issue) getBlockedByDependencies(e Engine) (issueDeps []*Issue, err error) {
  1562. return issueDeps, e.
  1563. Table("issue_dependency").
  1564. Select("issue.*").
  1565. Join("INNER", "issue", "issue.id = issue_dependency.dependency_id").
  1566. Where("issue_id = ?", issue.ID).
  1567. Find(&issueDeps)
  1568. }
  1569. // Get Blocking Dependencies, aka all issues this issue blocks.
  1570. func (issue *Issue) getBlockingDependencies(e Engine) (issueDeps []*Issue, err error) {
  1571. return issueDeps, e.
  1572. Table("issue_dependency").
  1573. Select("issue.*").
  1574. Join("INNER", "issue", "issue.id = issue_dependency.issue_id").
  1575. Where("dependency_id = ?", issue.ID).
  1576. Find(&issueDeps)
  1577. }
  1578. // BlockedByDependencies finds all Dependencies an issue is blocked by
  1579. func (issue *Issue) BlockedByDependencies() ([]*Issue, error) {
  1580. return issue.getBlockedByDependencies(x)
  1581. }
  1582. // BlockingDependencies returns all blocking dependencies, aka all other issues a given issue blocks
  1583. func (issue *Issue) BlockingDependencies() ([]*Issue, error) {
  1584. return issue.getBlockingDependencies(x)
  1585. }