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

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