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 53 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
9 years ago
8 years ago
8 years ago
Issue due date (#3794) * Started adding deadline to ui * Implemented basic issue due date managing * Improved UI for due date managing * Added at least write access to the repo in order to modify issue due dates * Ui improvements * Added issue comments creation when adding/modifying/removing a due date * Show due date in issue list * Added api support for issue due dates * Fixed lint suggestions * Added deadline to sdk * Updated css * Added support for adding/modifiying deadlines for pull requests via api * Fixed comments not created when updating or removing a deadline * update sdk (will do properly once go-gitea/go-sdk#103 is merged) * enhanced updateIssueDeadline * Removed unnessecary Issue.DeadlineString * UI improvements * Small improvments to comment creation + ui & validation improvements * Check if an issue is overdue is now a seperate function * Updated go-sdk with govendor as it was merged * Simplified isOverdue method * removed unessecary deadline to 0 set * Update swagger definitions * Added missing return * Added an explanary comment * Improved updateIssueDeadline method so it'll only update `deadline_unix` * Small changes and improvements * no need to explicitly load the issue when updating a deadline, just use whats already there * small optimisations * Added check if a deadline was modified before updating it * Moved comment creating logic into its own function * Code cleanup for creating deadline comment * locale improvement * When modifying a deadline, the old deadline is saved with the comment * small improvments to xorm session handling when updating an issue deadline + style nitpicks * style nitpicks * Moved checking for if the user has write acces to middleware
7 years ago
8 years ago
8 years ago
8 years ago
8 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
8 years ago
8 years ago
8 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
8 years ago
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
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949
  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. func (issue *Issue) changeStatus(e *xorm.Session, doer *User, isClosed bool) (err error) {
  614. // Reload the issue
  615. currentIssue, err := getIssueByID(e, issue.ID)
  616. if err != nil {
  617. return err
  618. }
  619. // Nothing should be performed if current status is same as target status
  620. if currentIssue.IsClosed == isClosed {
  621. return nil
  622. }
  623. // Check for open dependencies
  624. if isClosed && issue.Repo.isDependenciesEnabled(e) {
  625. // 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
  626. noDeps, err := issueNoDependenciesLeft(e, issue)
  627. if err != nil {
  628. return err
  629. }
  630. if !noDeps {
  631. return ErrDependenciesLeft{issue.ID}
  632. }
  633. }
  634. issue.IsClosed = isClosed
  635. if isClosed {
  636. issue.ClosedUnix = timeutil.TimeStampNow()
  637. } else {
  638. issue.ClosedUnix = 0
  639. }
  640. if err = updateIssueCols(e, issue, "is_closed", "closed_unix"); err != nil {
  641. return err
  642. }
  643. // Update issue count of labels
  644. if err = issue.getLabels(e); err != nil {
  645. return err
  646. }
  647. for idx := range issue.Labels {
  648. if err = updateLabel(e, issue.Labels[idx]); err != nil {
  649. return err
  650. }
  651. }
  652. // Update issue count of milestone
  653. if err := updateMilestoneClosedNum(e, issue.MilestoneID); err != nil {
  654. return err
  655. }
  656. // New action comment
  657. if _, err = createStatusComment(e, doer, issue); err != nil {
  658. return err
  659. }
  660. return nil
  661. }
  662. // ChangeStatus changes issue status to open or closed.
  663. func (issue *Issue) ChangeStatus(doer *User, isClosed bool) (err error) {
  664. sess := x.NewSession()
  665. defer sess.Close()
  666. if err = sess.Begin(); err != nil {
  667. return err
  668. }
  669. if err = issue.loadRepo(sess); err != nil {
  670. return err
  671. }
  672. if err = issue.loadPoster(sess); err != nil {
  673. return err
  674. }
  675. if err = issue.changeStatus(sess, doer, isClosed); err != nil {
  676. return err
  677. }
  678. if err = sess.Commit(); err != nil {
  679. return fmt.Errorf("Commit: %v", err)
  680. }
  681. sess.Close()
  682. mode, _ := AccessLevel(issue.Poster, issue.Repo)
  683. if issue.IsPull {
  684. if err = issue.loadPullRequest(sess); err != nil {
  685. return err
  686. }
  687. // Merge pull request calls issue.changeStatus so we need to handle separately.
  688. apiPullRequest := &api.PullRequestPayload{
  689. Index: issue.Index,
  690. PullRequest: issue.PullRequest.APIFormat(),
  691. Repository: issue.Repo.APIFormat(mode),
  692. Sender: doer.APIFormat(),
  693. }
  694. if isClosed {
  695. apiPullRequest.Action = api.HookIssueClosed
  696. } else {
  697. apiPullRequest.Action = api.HookIssueReOpened
  698. }
  699. err = PrepareWebhooks(issue.Repo, HookEventPullRequest, apiPullRequest)
  700. } else {
  701. apiIssue := &api.IssuePayload{
  702. Index: issue.Index,
  703. Issue: issue.APIFormat(),
  704. Repository: issue.Repo.APIFormat(mode),
  705. Sender: doer.APIFormat(),
  706. }
  707. if isClosed {
  708. apiIssue.Action = api.HookIssueClosed
  709. } else {
  710. apiIssue.Action = api.HookIssueReOpened
  711. }
  712. err = PrepareWebhooks(issue.Repo, HookEventIssues, apiIssue)
  713. }
  714. if err != nil {
  715. log.Error("PrepareWebhooks [is_pull: %v, is_closed: %v]: %v", issue.IsPull, isClosed, err)
  716. } else {
  717. go HookQueue.Add(issue.Repo.ID)
  718. }
  719. return nil
  720. }
  721. // ChangeTitle changes the title of this issue, as the given user.
  722. func (issue *Issue) ChangeTitle(doer *User, oldTitle string) (err error) {
  723. sess := x.NewSession()
  724. defer sess.Close()
  725. if err = sess.Begin(); err != nil {
  726. return err
  727. }
  728. if err = updateIssueCols(sess, issue, "name"); err != nil {
  729. return fmt.Errorf("updateIssueCols: %v", err)
  730. }
  731. if err = issue.loadRepo(sess); err != nil {
  732. return fmt.Errorf("loadRepo: %v", err)
  733. }
  734. if _, err = createChangeTitleComment(sess, doer, issue.Repo, issue, oldTitle, issue.Title); err != nil {
  735. return fmt.Errorf("createChangeTitleComment: %v", err)
  736. }
  737. if err = issue.neuterCrossReferences(sess); err != nil {
  738. return err
  739. }
  740. if err = issue.addCrossReferences(sess, doer); err != nil {
  741. return err
  742. }
  743. return sess.Commit()
  744. }
  745. // AddDeletePRBranchComment adds delete branch comment for pull request issue
  746. func AddDeletePRBranchComment(doer *User, repo *Repository, issueID int64, branchName string) error {
  747. issue, err := getIssueByID(x, issueID)
  748. if err != nil {
  749. return err
  750. }
  751. sess := x.NewSession()
  752. defer sess.Close()
  753. if err := sess.Begin(); err != nil {
  754. return err
  755. }
  756. if _, err := createDeleteBranchComment(sess, doer, repo, issue, branchName); err != nil {
  757. return err
  758. }
  759. return sess.Commit()
  760. }
  761. // ChangeContent changes issue content, as the given user.
  762. func (issue *Issue) ChangeContent(doer *User, content string) (err error) {
  763. oldContent := issue.Content
  764. issue.Content = content
  765. sess := x.NewSession()
  766. defer sess.Close()
  767. if err = sess.Begin(); err != nil {
  768. return err
  769. }
  770. if err = updateIssueCols(sess, issue, "content"); err != nil {
  771. return fmt.Errorf("UpdateIssueCols: %v", err)
  772. }
  773. if err = issue.neuterCrossReferences(sess); err != nil {
  774. return err
  775. }
  776. if err = issue.addCrossReferences(sess, doer); err != nil {
  777. return err
  778. }
  779. if err = sess.Commit(); err != nil {
  780. return err
  781. }
  782. sess.Close()
  783. mode, _ := AccessLevel(issue.Poster, issue.Repo)
  784. if issue.IsPull {
  785. issue.PullRequest.Issue = issue
  786. err = PrepareWebhooks(issue.Repo, HookEventPullRequest, &api.PullRequestPayload{
  787. Action: api.HookIssueEdited,
  788. Index: issue.Index,
  789. Changes: &api.ChangesPayload{
  790. Body: &api.ChangesFromPayload{
  791. From: oldContent,
  792. },
  793. },
  794. PullRequest: issue.PullRequest.APIFormat(),
  795. Repository: issue.Repo.APIFormat(mode),
  796. Sender: doer.APIFormat(),
  797. })
  798. } else {
  799. err = PrepareWebhooks(issue.Repo, HookEventIssues, &api.IssuePayload{
  800. Action: api.HookIssueEdited,
  801. Index: issue.Index,
  802. Changes: &api.ChangesPayload{
  803. Body: &api.ChangesFromPayload{
  804. From: oldContent,
  805. },
  806. },
  807. Issue: issue.APIFormat(),
  808. Repository: issue.Repo.APIFormat(mode),
  809. Sender: doer.APIFormat(),
  810. })
  811. }
  812. if err != nil {
  813. log.Error("PrepareWebhooks [is_pull: %v]: %v", issue.IsPull, err)
  814. } else {
  815. go HookQueue.Add(issue.RepoID)
  816. }
  817. return nil
  818. }
  819. // GetTasks returns the amount of tasks in the issues content
  820. func (issue *Issue) GetTasks() int {
  821. return len(issueTasksPat.FindAllStringIndex(issue.Content, -1))
  822. }
  823. // GetTasksDone returns the amount of completed tasks in the issues content
  824. func (issue *Issue) GetTasksDone() int {
  825. return len(issueTasksDonePat.FindAllStringIndex(issue.Content, -1))
  826. }
  827. // GetLastEventTimestamp returns the last user visible event timestamp, either the creation of this issue or the close.
  828. func (issue *Issue) GetLastEventTimestamp() timeutil.TimeStamp {
  829. if issue.IsClosed {
  830. return issue.ClosedUnix
  831. }
  832. return issue.CreatedUnix
  833. }
  834. // GetLastEventLabel returns the localization label for the current issue.
  835. func (issue *Issue) GetLastEventLabel() string {
  836. if issue.IsClosed {
  837. if issue.IsPull && issue.PullRequest.HasMerged {
  838. return "repo.pulls.merged_by"
  839. }
  840. return "repo.issues.closed_by"
  841. }
  842. return "repo.issues.opened_by"
  843. }
  844. // GetLastEventLabelFake returns the localization label for the current issue without providing a link in the username.
  845. func (issue *Issue) GetLastEventLabelFake() string {
  846. if issue.IsClosed {
  847. if issue.IsPull && issue.PullRequest.HasMerged {
  848. return "repo.pulls.merged_by_fake"
  849. }
  850. return "repo.issues.closed_by_fake"
  851. }
  852. return "repo.issues.opened_by_fake"
  853. }
  854. // NewIssueOptions represents the options of a new issue.
  855. type NewIssueOptions struct {
  856. Repo *Repository
  857. Issue *Issue
  858. LabelIDs []int64
  859. AssigneeIDs []int64
  860. Attachments []string // In UUID format.
  861. IsPull bool
  862. }
  863. func newIssue(e *xorm.Session, doer *User, opts NewIssueOptions) (err error) {
  864. opts.Issue.Title = strings.TrimSpace(opts.Issue.Title)
  865. if opts.Issue.MilestoneID > 0 {
  866. milestone, err := getMilestoneByRepoID(e, opts.Issue.RepoID, opts.Issue.MilestoneID)
  867. if err != nil && !IsErrMilestoneNotExist(err) {
  868. return fmt.Errorf("getMilestoneByID: %v", err)
  869. }
  870. // Assume milestone is invalid and drop silently.
  871. opts.Issue.MilestoneID = 0
  872. if milestone != nil {
  873. opts.Issue.MilestoneID = milestone.ID
  874. opts.Issue.Milestone = milestone
  875. }
  876. }
  877. // Keep the old assignee id thingy for compatibility reasons
  878. if opts.Issue.AssigneeID > 0 {
  879. isAdded := false
  880. // Check if the user has already been passed to issue.AssigneeIDs, if not, add it
  881. for _, aID := range opts.AssigneeIDs {
  882. if aID == opts.Issue.AssigneeID {
  883. isAdded = true
  884. break
  885. }
  886. }
  887. if !isAdded {
  888. opts.AssigneeIDs = append(opts.AssigneeIDs, opts.Issue.AssigneeID)
  889. }
  890. }
  891. // Check for and validate assignees
  892. if len(opts.AssigneeIDs) > 0 {
  893. for _, assigneeID := range opts.AssigneeIDs {
  894. user, err := getUserByID(e, assigneeID)
  895. if err != nil {
  896. return fmt.Errorf("getUserByID [user_id: %d, repo_id: %d]: %v", assigneeID, opts.Repo.ID, err)
  897. }
  898. valid, err := canBeAssigned(e, user, opts.Repo)
  899. if err != nil {
  900. return fmt.Errorf("canBeAssigned [user_id: %d, repo_id: %d]: %v", assigneeID, opts.Repo.ID, err)
  901. }
  902. if !valid {
  903. return ErrUserDoesNotHaveAccessToRepo{UserID: assigneeID, RepoName: opts.Repo.Name}
  904. }
  905. }
  906. }
  907. // Milestone and assignee validation should happen before insert actual object.
  908. if _, err := e.SetExpr("`index`", "coalesce(MAX(`index`),0)+1").
  909. Where("repo_id=?", opts.Issue.RepoID).
  910. Insert(opts.Issue); err != nil {
  911. return ErrNewIssueInsert{err}
  912. }
  913. inserted, err := getIssueByID(e, opts.Issue.ID)
  914. if err != nil {
  915. return err
  916. }
  917. // Patch Index with the value calculated by the database
  918. opts.Issue.Index = inserted.Index
  919. if opts.Issue.MilestoneID > 0 {
  920. if _, err = e.Exec("UPDATE `milestone` SET num_issues=num_issues+1 WHERE id=?", opts.Issue.MilestoneID); err != nil {
  921. return err
  922. }
  923. }
  924. // Insert the assignees
  925. for _, assigneeID := range opts.AssigneeIDs {
  926. err = opts.Issue.changeAssignee(e, doer, assigneeID, true)
  927. if err != nil {
  928. return err
  929. }
  930. }
  931. if opts.IsPull {
  932. _, err = e.Exec("UPDATE `repository` SET num_pulls = num_pulls + 1 WHERE id = ?", opts.Issue.RepoID)
  933. } else {
  934. _, err = e.Exec("UPDATE `repository` SET num_issues = num_issues + 1 WHERE id = ?", opts.Issue.RepoID)
  935. }
  936. if err != nil {
  937. return err
  938. }
  939. if len(opts.LabelIDs) > 0 {
  940. // During the session, SQLite3 driver cannot handle retrieve objects after update something.
  941. // So we have to get all needed labels first.
  942. labels := make([]*Label, 0, len(opts.LabelIDs))
  943. if err = e.In("id", opts.LabelIDs).Find(&labels); err != nil {
  944. return fmt.Errorf("find all labels [label_ids: %v]: %v", opts.LabelIDs, err)
  945. }
  946. if err = opts.Issue.loadPoster(e); err != nil {
  947. return err
  948. }
  949. for _, label := range labels {
  950. // Silently drop invalid labels.
  951. if label.RepoID != opts.Repo.ID {
  952. continue
  953. }
  954. if err = opts.Issue.addLabel(e, label, opts.Issue.Poster); err != nil {
  955. return fmt.Errorf("addLabel [id: %d]: %v", label.ID, err)
  956. }
  957. }
  958. }
  959. if err = newIssueUsers(e, opts.Repo, opts.Issue); err != nil {
  960. return err
  961. }
  962. if len(opts.Attachments) > 0 {
  963. attachments, err := getAttachmentsByUUIDs(e, opts.Attachments)
  964. if err != nil {
  965. return fmt.Errorf("getAttachmentsByUUIDs [uuids: %v]: %v", opts.Attachments, err)
  966. }
  967. for i := 0; i < len(attachments); i++ {
  968. attachments[i].IssueID = opts.Issue.ID
  969. if _, err = e.ID(attachments[i].ID).Update(attachments[i]); err != nil {
  970. return fmt.Errorf("update attachment [id: %d]: %v", attachments[i].ID, err)
  971. }
  972. }
  973. }
  974. if err = opts.Issue.loadAttributes(e); err != nil {
  975. return err
  976. }
  977. return opts.Issue.addCrossReferences(e, doer)
  978. }
  979. // NewIssue creates new issue with labels for repository.
  980. func NewIssue(repo *Repository, issue *Issue, labelIDs []int64, assigneeIDs []int64, uuids []string) (err error) {
  981. // Retry several times in case INSERT fails due to duplicate key for (repo_id, index); see #7887
  982. i := 0
  983. for {
  984. if err = newIssueAttempt(repo, issue, labelIDs, assigneeIDs, uuids); err == nil {
  985. return nil
  986. }
  987. if !IsErrNewIssueInsert(err) {
  988. return err
  989. }
  990. if i++; i == issueMaxDupIndexAttempts {
  991. break
  992. }
  993. log.Error("NewIssue: error attempting to insert the new issue; will retry. Original error: %v", err)
  994. }
  995. return fmt.Errorf("NewIssue: too many errors attempting to insert the new issue. Last error was: %v", err)
  996. }
  997. func newIssueAttempt(repo *Repository, issue *Issue, labelIDs []int64, assigneeIDs []int64, uuids []string) (err error) {
  998. sess := x.NewSession()
  999. defer sess.Close()
  1000. if err = sess.Begin(); err != nil {
  1001. return err
  1002. }
  1003. if err = newIssue(sess, issue.Poster, NewIssueOptions{
  1004. Repo: repo,
  1005. Issue: issue,
  1006. LabelIDs: labelIDs,
  1007. Attachments: uuids,
  1008. AssigneeIDs: assigneeIDs,
  1009. }); err != nil {
  1010. if IsErrUserDoesNotHaveAccessToRepo(err) || IsErrNewIssueInsert(err) {
  1011. return err
  1012. }
  1013. return fmt.Errorf("newIssue: %v", err)
  1014. }
  1015. if err = sess.Commit(); err != nil {
  1016. return fmt.Errorf("Commit: %v", err)
  1017. }
  1018. return nil
  1019. }
  1020. // GetIssueByIndex returns raw issue without loading attributes by index in a repository.
  1021. func GetIssueByIndex(repoID, index int64) (*Issue, error) {
  1022. issue := &Issue{
  1023. RepoID: repoID,
  1024. Index: index,
  1025. }
  1026. has, err := x.Get(issue)
  1027. if err != nil {
  1028. return nil, err
  1029. } else if !has {
  1030. return nil, ErrIssueNotExist{0, repoID, index}
  1031. }
  1032. return issue, nil
  1033. }
  1034. // GetIssueWithAttrsByIndex returns issue by index in a repository.
  1035. func GetIssueWithAttrsByIndex(repoID, index int64) (*Issue, error) {
  1036. issue, err := GetIssueByIndex(repoID, index)
  1037. if err != nil {
  1038. return nil, err
  1039. }
  1040. return issue, issue.LoadAttributes()
  1041. }
  1042. func getIssueByID(e Engine, id int64) (*Issue, error) {
  1043. issue := new(Issue)
  1044. has, err := e.ID(id).Get(issue)
  1045. if err != nil {
  1046. return nil, err
  1047. } else if !has {
  1048. return nil, ErrIssueNotExist{id, 0, 0}
  1049. }
  1050. return issue, nil
  1051. }
  1052. // GetIssueWithAttrsByID returns an issue with attributes by given ID.
  1053. func GetIssueWithAttrsByID(id int64) (*Issue, error) {
  1054. issue, err := getIssueByID(x, id)
  1055. if err != nil {
  1056. return nil, err
  1057. }
  1058. return issue, issue.loadAttributes(x)
  1059. }
  1060. // GetIssueByID returns an issue by given ID.
  1061. func GetIssueByID(id int64) (*Issue, error) {
  1062. return getIssueByID(x, id)
  1063. }
  1064. func getIssuesByIDs(e Engine, issueIDs []int64) ([]*Issue, error) {
  1065. issues := make([]*Issue, 0, 10)
  1066. return issues, e.In("id", issueIDs).Find(&issues)
  1067. }
  1068. func getIssueIDsByRepoID(e Engine, repoID int64) ([]int64, error) {
  1069. var ids = make([]int64, 0, 10)
  1070. err := e.Table("issue").Where("repo_id = ?", repoID).Find(&ids)
  1071. return ids, err
  1072. }
  1073. // GetIssueIDsByRepoID returns all issue ids by repo id
  1074. func GetIssueIDsByRepoID(repoID int64) ([]int64, error) {
  1075. return getIssueIDsByRepoID(x, repoID)
  1076. }
  1077. // GetIssuesByIDs return issues with the given IDs.
  1078. func GetIssuesByIDs(issueIDs []int64) ([]*Issue, error) {
  1079. return getIssuesByIDs(x, issueIDs)
  1080. }
  1081. // IssuesOptions represents options of an issue.
  1082. type IssuesOptions struct {
  1083. RepoIDs []int64 // include all repos if empty
  1084. AssigneeID int64
  1085. PosterID int64
  1086. MentionedID int64
  1087. MilestoneID int64
  1088. Page int
  1089. PageSize int
  1090. IsClosed util.OptionalBool
  1091. IsPull util.OptionalBool
  1092. LabelIDs []int64
  1093. SortType string
  1094. IssueIDs []int64
  1095. }
  1096. // sortIssuesSession sort an issues-related session based on the provided
  1097. // sortType string
  1098. func sortIssuesSession(sess *xorm.Session, sortType string) {
  1099. switch sortType {
  1100. case "oldest":
  1101. sess.Asc("issue.created_unix")
  1102. case "recentupdate":
  1103. sess.Desc("issue.updated_unix")
  1104. case "leastupdate":
  1105. sess.Asc("issue.updated_unix")
  1106. case "mostcomment":
  1107. sess.Desc("issue.num_comments")
  1108. case "leastcomment":
  1109. sess.Asc("issue.num_comments")
  1110. case "priority":
  1111. sess.Desc("issue.priority")
  1112. case "nearduedate":
  1113. sess.Asc("issue.deadline_unix")
  1114. case "farduedate":
  1115. sess.Desc("issue.deadline_unix")
  1116. default:
  1117. sess.Desc("issue.created_unix")
  1118. }
  1119. }
  1120. func (opts *IssuesOptions) setupSession(sess *xorm.Session) {
  1121. if opts.Page >= 0 && opts.PageSize > 0 {
  1122. var start int
  1123. if opts.Page == 0 {
  1124. start = 0
  1125. } else {
  1126. start = (opts.Page - 1) * opts.PageSize
  1127. }
  1128. sess.Limit(opts.PageSize, start)
  1129. }
  1130. if len(opts.IssueIDs) > 0 {
  1131. sess.In("issue.id", opts.IssueIDs)
  1132. }
  1133. if len(opts.RepoIDs) > 0 {
  1134. // In case repository IDs are provided but actually no repository has issue.
  1135. sess.In("issue.repo_id", opts.RepoIDs)
  1136. }
  1137. switch opts.IsClosed {
  1138. case util.OptionalBoolTrue:
  1139. sess.And("issue.is_closed=?", true)
  1140. case util.OptionalBoolFalse:
  1141. sess.And("issue.is_closed=?", false)
  1142. }
  1143. if opts.AssigneeID > 0 {
  1144. sess.Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  1145. And("issue_assignees.assignee_id = ?", opts.AssigneeID)
  1146. }
  1147. if opts.PosterID > 0 {
  1148. sess.And("issue.poster_id=?", opts.PosterID)
  1149. }
  1150. if opts.MentionedID > 0 {
  1151. sess.Join("INNER", "issue_user", "issue.id = issue_user.issue_id").
  1152. And("issue_user.is_mentioned = ?", true).
  1153. And("issue_user.uid = ?", opts.MentionedID)
  1154. }
  1155. if opts.MilestoneID > 0 {
  1156. sess.And("issue.milestone_id=?", opts.MilestoneID)
  1157. }
  1158. switch opts.IsPull {
  1159. case util.OptionalBoolTrue:
  1160. sess.And("issue.is_pull=?", true)
  1161. case util.OptionalBoolFalse:
  1162. sess.And("issue.is_pull=?", false)
  1163. }
  1164. if opts.LabelIDs != nil {
  1165. for i, labelID := range opts.LabelIDs {
  1166. sess.Join("INNER", fmt.Sprintf("issue_label il%d", i),
  1167. fmt.Sprintf("issue.id = il%[1]d.issue_id AND il%[1]d.label_id = %[2]d", i, labelID))
  1168. }
  1169. }
  1170. }
  1171. // CountIssuesByRepo map from repoID to number of issues matching the options
  1172. func CountIssuesByRepo(opts *IssuesOptions) (map[int64]int64, error) {
  1173. sess := x.NewSession()
  1174. defer sess.Close()
  1175. opts.setupSession(sess)
  1176. countsSlice := make([]*struct {
  1177. RepoID int64
  1178. Count int64
  1179. }, 0, 10)
  1180. if err := sess.GroupBy("issue.repo_id").
  1181. Select("issue.repo_id AS repo_id, COUNT(*) AS count").
  1182. Table("issue").
  1183. Find(&countsSlice); err != nil {
  1184. return nil, err
  1185. }
  1186. countMap := make(map[int64]int64, len(countsSlice))
  1187. for _, c := range countsSlice {
  1188. countMap[c.RepoID] = c.Count
  1189. }
  1190. return countMap, nil
  1191. }
  1192. // Issues returns a list of issues by given conditions.
  1193. func Issues(opts *IssuesOptions) ([]*Issue, error) {
  1194. sess := x.NewSession()
  1195. defer sess.Close()
  1196. opts.setupSession(sess)
  1197. sortIssuesSession(sess, opts.SortType)
  1198. issues := make([]*Issue, 0, setting.UI.IssuePagingNum)
  1199. if err := sess.Find(&issues); err != nil {
  1200. return nil, fmt.Errorf("Find: %v", err)
  1201. }
  1202. sess.Close()
  1203. if err := IssueList(issues).LoadAttributes(); err != nil {
  1204. return nil, fmt.Errorf("LoadAttributes: %v", err)
  1205. }
  1206. return issues, nil
  1207. }
  1208. // GetParticipantsByIssueID returns all users who are participated in comments of an issue.
  1209. func GetParticipantsByIssueID(issueID int64) ([]*User, error) {
  1210. return getParticipantsByIssueID(x, issueID)
  1211. }
  1212. func getParticipantsByIssueID(e Engine, issueID int64) ([]*User, error) {
  1213. userIDs := make([]int64, 0, 5)
  1214. if err := e.Table("comment").Cols("poster_id").
  1215. Where("`comment`.issue_id = ?", issueID).
  1216. And("`comment`.type in (?,?,?)", CommentTypeComment, CommentTypeCode, CommentTypeReview).
  1217. And("`user`.is_active = ?", true).
  1218. And("`user`.prohibit_login = ?", false).
  1219. Join("INNER", "`user`", "`user`.id = `comment`.poster_id").
  1220. Distinct("poster_id").
  1221. Find(&userIDs); err != nil {
  1222. return nil, fmt.Errorf("get poster IDs: %v", err)
  1223. }
  1224. if len(userIDs) == 0 {
  1225. return nil, nil
  1226. }
  1227. users := make([]*User, 0, len(userIDs))
  1228. return users, e.In("id", userIDs).Find(&users)
  1229. }
  1230. // UpdateIssueMentions updates issue-user relations for mentioned users.
  1231. func UpdateIssueMentions(ctx DBContext, issueID int64, mentions []*User) error {
  1232. if len(mentions) == 0 {
  1233. return nil
  1234. }
  1235. ids := make([]int64, len(mentions))
  1236. for i, u := range mentions {
  1237. ids[i] = u.ID
  1238. }
  1239. if err := UpdateIssueUsersByMentions(ctx, issueID, ids); err != nil {
  1240. return fmt.Errorf("UpdateIssueUsersByMentions: %v", err)
  1241. }
  1242. return nil
  1243. }
  1244. // IssueStats represents issue statistic information.
  1245. type IssueStats struct {
  1246. OpenCount, ClosedCount int64
  1247. YourRepositoriesCount int64
  1248. AssignCount int64
  1249. CreateCount int64
  1250. MentionCount int64
  1251. }
  1252. // Filter modes.
  1253. const (
  1254. FilterModeAll = iota
  1255. FilterModeAssign
  1256. FilterModeCreate
  1257. FilterModeMention
  1258. )
  1259. func parseCountResult(results []map[string][]byte) int64 {
  1260. if len(results) == 0 {
  1261. return 0
  1262. }
  1263. for _, result := range results[0] {
  1264. return com.StrTo(string(result)).MustInt64()
  1265. }
  1266. return 0
  1267. }
  1268. // IssueStatsOptions contains parameters accepted by GetIssueStats.
  1269. type IssueStatsOptions struct {
  1270. RepoID int64
  1271. Labels string
  1272. MilestoneID int64
  1273. AssigneeID int64
  1274. MentionedID int64
  1275. PosterID int64
  1276. IsPull util.OptionalBool
  1277. IssueIDs []int64
  1278. }
  1279. // GetIssueStats returns issue statistic information by given conditions.
  1280. func GetIssueStats(opts *IssueStatsOptions) (*IssueStats, error) {
  1281. stats := &IssueStats{}
  1282. countSession := func(opts *IssueStatsOptions) *xorm.Session {
  1283. sess := x.
  1284. Where("issue.repo_id = ?", opts.RepoID)
  1285. if len(opts.IssueIDs) > 0 {
  1286. sess.In("issue.id", opts.IssueIDs)
  1287. }
  1288. if len(opts.Labels) > 0 && opts.Labels != "0" {
  1289. labelIDs, err := base.StringsToInt64s(strings.Split(opts.Labels, ","))
  1290. if err != nil {
  1291. log.Warn("Malformed Labels argument: %s", opts.Labels)
  1292. } else {
  1293. for i, labelID := range labelIDs {
  1294. sess.Join("INNER", fmt.Sprintf("issue_label il%d", i),
  1295. fmt.Sprintf("issue.id = il%[1]d.issue_id AND il%[1]d.label_id = %[2]d", i, labelID))
  1296. }
  1297. }
  1298. }
  1299. if opts.MilestoneID > 0 {
  1300. sess.And("issue.milestone_id = ?", opts.MilestoneID)
  1301. }
  1302. if opts.AssigneeID > 0 {
  1303. sess.Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  1304. And("issue_assignees.assignee_id = ?", opts.AssigneeID)
  1305. }
  1306. if opts.PosterID > 0 {
  1307. sess.And("issue.poster_id = ?", opts.PosterID)
  1308. }
  1309. if opts.MentionedID > 0 {
  1310. sess.Join("INNER", "issue_user", "issue.id = issue_user.issue_id").
  1311. And("issue_user.uid = ?", opts.MentionedID).
  1312. And("issue_user.is_mentioned = ?", true)
  1313. }
  1314. switch opts.IsPull {
  1315. case util.OptionalBoolTrue:
  1316. sess.And("issue.is_pull=?", true)
  1317. case util.OptionalBoolFalse:
  1318. sess.And("issue.is_pull=?", false)
  1319. }
  1320. return sess
  1321. }
  1322. var err error
  1323. stats.OpenCount, err = countSession(opts).
  1324. And("issue.is_closed = ?", false).
  1325. Count(new(Issue))
  1326. if err != nil {
  1327. return stats, err
  1328. }
  1329. stats.ClosedCount, err = countSession(opts).
  1330. And("issue.is_closed = ?", true).
  1331. Count(new(Issue))
  1332. return stats, err
  1333. }
  1334. // UserIssueStatsOptions contains parameters accepted by GetUserIssueStats.
  1335. type UserIssueStatsOptions struct {
  1336. UserID int64
  1337. RepoID int64
  1338. UserRepoIDs []int64
  1339. FilterMode int
  1340. IsPull bool
  1341. IsClosed bool
  1342. }
  1343. // GetUserIssueStats returns issue statistic information for dashboard by given conditions.
  1344. func GetUserIssueStats(opts UserIssueStatsOptions) (*IssueStats, error) {
  1345. var err error
  1346. stats := &IssueStats{}
  1347. cond := builder.NewCond()
  1348. cond = cond.And(builder.Eq{"issue.is_pull": opts.IsPull})
  1349. if opts.RepoID > 0 {
  1350. cond = cond.And(builder.Eq{"issue.repo_id": opts.RepoID})
  1351. }
  1352. switch opts.FilterMode {
  1353. case FilterModeAll:
  1354. stats.OpenCount, err = x.Where(cond).And("is_closed = ?", false).
  1355. And(builder.In("issue.repo_id", opts.UserRepoIDs)).
  1356. Count(new(Issue))
  1357. if err != nil {
  1358. return nil, err
  1359. }
  1360. stats.ClosedCount, err = x.Where(cond).And("is_closed = ?", true).
  1361. And(builder.In("issue.repo_id", opts.UserRepoIDs)).
  1362. Count(new(Issue))
  1363. if err != nil {
  1364. return nil, err
  1365. }
  1366. case FilterModeAssign:
  1367. stats.OpenCount, err = x.Where(cond).And("issue.is_closed = ?", false).
  1368. Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  1369. And("issue_assignees.assignee_id = ?", opts.UserID).
  1370. Count(new(Issue))
  1371. if err != nil {
  1372. return nil, err
  1373. }
  1374. stats.ClosedCount, err = x.Where(cond).And("issue.is_closed = ?", true).
  1375. Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  1376. And("issue_assignees.assignee_id = ?", opts.UserID).
  1377. Count(new(Issue))
  1378. if err != nil {
  1379. return nil, err
  1380. }
  1381. case FilterModeCreate:
  1382. stats.OpenCount, err = x.Where(cond).And("is_closed = ?", false).
  1383. And("poster_id = ?", opts.UserID).
  1384. Count(new(Issue))
  1385. if err != nil {
  1386. return nil, err
  1387. }
  1388. stats.ClosedCount, err = x.Where(cond).And("is_closed = ?", true).
  1389. And("poster_id = ?", opts.UserID).
  1390. Count(new(Issue))
  1391. if err != nil {
  1392. return nil, err
  1393. }
  1394. case FilterModeMention:
  1395. stats.OpenCount, err = x.Where(cond).And("issue.is_closed = ?", false).
  1396. Join("INNER", "issue_user", "issue.id = issue_user.issue_id and issue_user.is_mentioned = ?", true).
  1397. And("issue_user.uid = ?", opts.UserID).
  1398. Count(new(Issue))
  1399. if err != nil {
  1400. return nil, err
  1401. }
  1402. stats.ClosedCount, err = x.Where(cond).And("issue.is_closed = ?", true).
  1403. Join("INNER", "issue_user", "issue.id = issue_user.issue_id and issue_user.is_mentioned = ?", true).
  1404. And("issue_user.uid = ?", opts.UserID).
  1405. Count(new(Issue))
  1406. if err != nil {
  1407. return nil, err
  1408. }
  1409. }
  1410. cond = cond.And(builder.Eq{"issue.is_closed": opts.IsClosed})
  1411. stats.AssignCount, err = x.Where(cond).
  1412. Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  1413. And("issue_assignees.assignee_id = ?", opts.UserID).
  1414. Count(new(Issue))
  1415. if err != nil {
  1416. return nil, err
  1417. }
  1418. stats.CreateCount, err = x.Where(cond).
  1419. And("poster_id = ?", opts.UserID).
  1420. Count(new(Issue))
  1421. if err != nil {
  1422. return nil, err
  1423. }
  1424. stats.MentionCount, err = x.Where(cond).
  1425. Join("INNER", "issue_user", "issue.id = issue_user.issue_id and issue_user.is_mentioned = ?", true).
  1426. And("issue_user.uid = ?", opts.UserID).
  1427. Count(new(Issue))
  1428. if err != nil {
  1429. return nil, err
  1430. }
  1431. stats.YourRepositoriesCount, err = x.Where(cond).
  1432. And(builder.In("issue.repo_id", opts.UserRepoIDs)).
  1433. Count(new(Issue))
  1434. if err != nil {
  1435. return nil, err
  1436. }
  1437. return stats, nil
  1438. }
  1439. // GetRepoIssueStats returns number of open and closed repository issues by given filter mode.
  1440. func GetRepoIssueStats(repoID, uid int64, filterMode int, isPull bool) (numOpen int64, numClosed int64) {
  1441. countSession := func(isClosed, isPull bool, repoID int64) *xorm.Session {
  1442. sess := x.
  1443. Where("is_closed = ?", isClosed).
  1444. And("is_pull = ?", isPull).
  1445. And("repo_id = ?", repoID)
  1446. return sess
  1447. }
  1448. openCountSession := countSession(false, isPull, repoID)
  1449. closedCountSession := countSession(true, isPull, repoID)
  1450. switch filterMode {
  1451. case FilterModeAssign:
  1452. openCountSession.Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  1453. And("issue_assignees.assignee_id = ?", uid)
  1454. closedCountSession.Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  1455. And("issue_assignees.assignee_id = ?", uid)
  1456. case FilterModeCreate:
  1457. openCountSession.And("poster_id = ?", uid)
  1458. closedCountSession.And("poster_id = ?", uid)
  1459. }
  1460. openResult, _ := openCountSession.Count(new(Issue))
  1461. closedResult, _ := closedCountSession.Count(new(Issue))
  1462. return openResult, closedResult
  1463. }
  1464. // SearchIssueIDsByKeyword search issues on database
  1465. func SearchIssueIDsByKeyword(kw string, repoID int64, limit, start int) (int64, []int64, error) {
  1466. var repoCond = builder.Eq{"repo_id": repoID}
  1467. var subQuery = builder.Select("id").From("issue").Where(repoCond)
  1468. var cond = builder.And(
  1469. repoCond,
  1470. builder.Or(
  1471. builder.Like{"name", kw},
  1472. builder.Like{"content", kw},
  1473. builder.In("id", builder.Select("issue_id").
  1474. From("comment").
  1475. Where(builder.And(
  1476. builder.Eq{"type": CommentTypeComment},
  1477. builder.In("issue_id", subQuery),
  1478. builder.Like{"content", kw},
  1479. )),
  1480. ),
  1481. ),
  1482. )
  1483. var ids = make([]int64, 0, limit)
  1484. err := x.Distinct("id").Table("issue").Where(cond).Limit(limit, start).Find(&ids)
  1485. if err != nil {
  1486. return 0, nil, err
  1487. }
  1488. total, err := x.Distinct("id").Table("issue").Where(cond).Count()
  1489. if err != nil {
  1490. return 0, nil, err
  1491. }
  1492. return total, ids, nil
  1493. }
  1494. func updateIssue(e Engine, issue *Issue) error {
  1495. _, err := e.ID(issue.ID).AllCols().Update(issue)
  1496. if err != nil {
  1497. return err
  1498. }
  1499. return nil
  1500. }
  1501. // UpdateIssue updates all fields of given issue.
  1502. func UpdateIssue(issue *Issue) error {
  1503. sess := x.NewSession()
  1504. defer sess.Close()
  1505. if err := sess.Begin(); err != nil {
  1506. return err
  1507. }
  1508. if err := updateIssue(sess, issue); err != nil {
  1509. return err
  1510. }
  1511. if err := issue.neuterCrossReferences(sess); err != nil {
  1512. return err
  1513. }
  1514. if err := issue.loadPoster(sess); err != nil {
  1515. return err
  1516. }
  1517. if err := issue.addCrossReferences(sess, issue.Poster); err != nil {
  1518. return err
  1519. }
  1520. return sess.Commit()
  1521. }
  1522. // UpdateIssueDeadline updates an issue deadline and adds comments. Setting a deadline to 0 means deleting it.
  1523. func UpdateIssueDeadline(issue *Issue, deadlineUnix timeutil.TimeStamp, doer *User) (err error) {
  1524. // if the deadline hasn't changed do nothing
  1525. if issue.DeadlineUnix == deadlineUnix {
  1526. return nil
  1527. }
  1528. sess := x.NewSession()
  1529. defer sess.Close()
  1530. if err := sess.Begin(); err != nil {
  1531. return err
  1532. }
  1533. // Update the deadline
  1534. if err = updateIssueCols(sess, &Issue{ID: issue.ID, DeadlineUnix: deadlineUnix}, "deadline_unix"); err != nil {
  1535. return err
  1536. }
  1537. // Make the comment
  1538. if _, err = createDeadlineComment(sess, doer, issue, deadlineUnix); err != nil {
  1539. return fmt.Errorf("createRemovedDueDateComment: %v", err)
  1540. }
  1541. return sess.Commit()
  1542. }
  1543. // Get Blocked By Dependencies, aka all issues this issue is blocked by.
  1544. func (issue *Issue) getBlockedByDependencies(e Engine) (issueDeps []*Issue, err error) {
  1545. return issueDeps, e.
  1546. Table("issue_dependency").
  1547. Select("issue.*").
  1548. Join("INNER", "issue", "issue.id = issue_dependency.dependency_id").
  1549. Where("issue_id = ?", issue.ID).
  1550. Find(&issueDeps)
  1551. }
  1552. // Get Blocking Dependencies, aka all issues this issue blocks.
  1553. func (issue *Issue) getBlockingDependencies(e Engine) (issueDeps []*Issue, err error) {
  1554. return issueDeps, e.
  1555. Table("issue_dependency").
  1556. Select("issue.*").
  1557. Join("INNER", "issue", "issue.id = issue_dependency.issue_id").
  1558. Where("dependency_id = ?", issue.ID).
  1559. Find(&issueDeps)
  1560. }
  1561. // BlockedByDependencies finds all Dependencies an issue is blocked by
  1562. func (issue *Issue) BlockedByDependencies() ([]*Issue, error) {
  1563. return issue.getBlockedByDependencies(x)
  1564. }
  1565. // BlockingDependencies returns all blocking dependencies, aka all other issues a given issue blocks
  1566. func (issue *Issue) BlockingDependencies() ([]*Issue, error) {
  1567. return issue.getBlockingDependencies(x)
  1568. }
  1569. func (issue *Issue) updateClosedNum(e Engine) (err error) {
  1570. if issue.IsPull {
  1571. _, err = e.Exec("UPDATE `repository` SET num_closed_pulls=(SELECT count(*) FROM issue WHERE repo_id=? AND is_pull=? AND is_closed=?) WHERE id=?",
  1572. issue.RepoID,
  1573. true,
  1574. true,
  1575. issue.RepoID,
  1576. )
  1577. } else {
  1578. _, err = e.Exec("UPDATE `repository` SET num_closed_issues=(SELECT count(*) FROM issue WHERE repo_id=? AND is_pull=? AND is_closed=?) WHERE id=?",
  1579. issue.RepoID,
  1580. false,
  1581. true,
  1582. issue.RepoID,
  1583. )
  1584. }
  1585. return
  1586. }
  1587. // ResolveMentionsByVisibility returns the users mentioned in an issue, removing those that
  1588. // don't have access to reading it. Teams are expanded into their users, but organizations are ignored.
  1589. func (issue *Issue) ResolveMentionsByVisibility(ctx DBContext, doer *User, mentions []string) (users []*User, err error) {
  1590. if len(mentions) == 0 {
  1591. return
  1592. }
  1593. if err = issue.loadRepo(ctx.e); err != nil {
  1594. return
  1595. }
  1596. resolved := make(map[string]bool, 20)
  1597. names := make([]string, 0, 20)
  1598. resolved[doer.LowerName] = true
  1599. for _, name := range mentions {
  1600. name := strings.ToLower(name)
  1601. if _, ok := resolved[name]; ok {
  1602. continue
  1603. }
  1604. resolved[name] = false
  1605. names = append(names, name)
  1606. }
  1607. if err := issue.Repo.getOwner(ctx.e); err != nil {
  1608. return nil, err
  1609. }
  1610. if issue.Repo.Owner.IsOrganization() {
  1611. // Since there can be users with names that match the name of a team,
  1612. // if the team exists and can read the issue, the team takes precedence.
  1613. teams := make([]*Team, 0, len(names))
  1614. if err := ctx.e.
  1615. Join("INNER", "team_repo", "team_repo.team_id = team.id").
  1616. Where("team_repo.repo_id=?", issue.Repo.ID).
  1617. In("team.lower_name", names).
  1618. Find(&teams); err != nil {
  1619. return nil, fmt.Errorf("find mentioned teams: %v", err)
  1620. }
  1621. if len(teams) != 0 {
  1622. checked := make([]int64, 0, len(teams))
  1623. unittype := UnitTypeIssues
  1624. if issue.IsPull {
  1625. unittype = UnitTypePullRequests
  1626. }
  1627. for _, team := range teams {
  1628. if team.Authorize >= AccessModeOwner {
  1629. checked = append(checked, team.ID)
  1630. resolved[team.LowerName] = true
  1631. continue
  1632. }
  1633. has, err := ctx.e.Get(&TeamUnit{OrgID: issue.Repo.Owner.ID, TeamID: team.ID, Type: unittype})
  1634. if err != nil {
  1635. return nil, fmt.Errorf("get team units (%d): %v", team.ID, err)
  1636. }
  1637. if has {
  1638. checked = append(checked, team.ID)
  1639. resolved[team.LowerName] = true
  1640. }
  1641. }
  1642. if len(checked) != 0 {
  1643. teamusers := make([]*User, 0, 20)
  1644. if err := ctx.e.
  1645. Join("INNER", "team_user", "team_user.uid = `user`.id").
  1646. In("`team_user`.team_id", checked).
  1647. And("`user`.is_active = ?", true).
  1648. And("`user`.prohibit_login = ?", false).
  1649. Find(&teamusers); err != nil {
  1650. return nil, fmt.Errorf("get teams users: %v", err)
  1651. }
  1652. if len(teamusers) > 0 {
  1653. users = make([]*User, 0, len(teamusers))
  1654. for _, user := range teamusers {
  1655. if already, ok := resolved[user.LowerName]; !ok || !already {
  1656. users = append(users, user)
  1657. resolved[user.LowerName] = true
  1658. }
  1659. }
  1660. }
  1661. }
  1662. }
  1663. // Remove names already in the list to avoid querying the database if pending names remain
  1664. names = make([]string, 0, len(resolved))
  1665. for name, already := range resolved {
  1666. if !already {
  1667. names = append(names, name)
  1668. }
  1669. }
  1670. if len(names) == 0 {
  1671. return
  1672. }
  1673. }
  1674. unchecked := make([]*User, 0, len(names))
  1675. if err := ctx.e.
  1676. Where("`user`.is_active = ?", true).
  1677. And("`user`.prohibit_login = ?", false).
  1678. In("`user`.lower_name", names).
  1679. Find(&unchecked); err != nil {
  1680. return nil, fmt.Errorf("find mentioned users: %v", err)
  1681. }
  1682. for _, user := range unchecked {
  1683. if already := resolved[user.LowerName]; already || user.IsOrganization() {
  1684. continue
  1685. }
  1686. // Normal users must have read access to the referencing issue
  1687. perm, err := getUserRepoPermission(ctx.e, issue.Repo, user)
  1688. if err != nil {
  1689. return nil, fmt.Errorf("getUserRepoPermission [%d]: %v", user.ID, err)
  1690. }
  1691. if !perm.CanReadIssuesOrPulls(issue.IsPull) {
  1692. continue
  1693. }
  1694. users = append(users, user)
  1695. }
  1696. return
  1697. }