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