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

11 years ago
Allow cross-repository dependencies on issues (#7901) * in progress changes for #7405, added ability to add cross-repo dependencies * removed unused repolink var * fixed query that was breaking ci tests; fixed check in issue dependency add so that the id of the issue and dependency is checked rather than the indexes * reverted removal of string in local files becasue these are done via crowdin, not updated manually * removed 'Select("issue.*")' from getBlockedByDependencies and getBlockingDependencies based on comments in PR review * changed getBlockedByDependencies and getBlockingDependencies to use a more xorm-like query, also updated the sidebar as a result * simplified the getBlockingDependencies and getBlockedByDependencies methods; changed the sidebar to show the dependencies in a different format where you can see the name of the repository * made some changes to the issue view in the dependencies (issue name on top, repo full name on separate line). Change view of issue in the dependency search results (also showing the full repo name on separate line) * replace call to FindUserAccessibleRepoIDs with SearchRepositoryByName. The former was hardcoded to use isPrivate = false on the repo search, but this code needed it to be true. The SearchRepositoryByName method is used more in the code including on the user's dashboard * some more tweaks to the layout of the issues when showing dependencies and in the search box when you add new dependencies * added Name to the RepositoryMeta struct * updated swagger doc * fixed total count for link header on SearchIssues * fixed indentation * fixed aligment of remove icon on dependencies in issue sidebar * removed unnecessary nil check (unnecessary because issue.loadRepo is called prior to this block) * reverting .css change, somehow missed or forgot that less is used * updated less file and generated css; updated sidebar template with styles to line up delete and issue index * added ordering to the blocked by/depends on queries * fixed sorting in issue dependency search and the depends on/blocks views to show issues from the current repo first, then by created date descending; added a "all cross repository dependencies" setting to allow this feature to be turned off, if turned off, the issue dependency search will work the way it did before (restricted to the current repository) * re-applied my swagger changes after merge * fixed split string condition in issue search * changed ALLOW_CROSS_REPOSITORY_DEPENDENCIES description to sound more global than just the issue dependency search; returning 400 in the cross repo issue search api method if not enabled; fixed bug where the issue count did not respect the state parameter * when adding a dependency to an issue, added a check to make sure the issue and dependency are in the same repo if cross repo dependencies is not enabled * updated sortIssuesSession call in PullRequests, another commit moved this method from pull.go to pull_list.go so I had to re-apply my change here * fixed incorrect setting of user id parameter in search repos call
5 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
4 years ago
4 years ago
issue search on my related repositories (#9758) * adding search capability to user's issues dashboard * global issue search * placement of search bar on issues dashboard * fixed some bugs in the issue dashboard search * added unit test because IssueIDs option was added to UserIssueStatsOptions * some renaming of fields in the issue dashboard code to be more clear; also trying to fix issue of searching the right repos based on the filter * added unit test fro GetRepoIDsForIssuesOptions; fixed search lost on pagination; using shown issue status for open/close count; removed some debugging * fix issue with all count showing incorrectly * removed todo comment left in by mistake * typo pulling wrong count * fxied all count being off when selecting repositories * setting the opts.IsClosed after pulling repos to search, this is done so that the list of repo ids to serach for the keyword is not limited, we need to get all the issue ids for the shown issue stats * added "accessibleRepositoryCondition" check on the query to pull the repo ids to search for issues, this is an added protection to ensure we don't search repos the user does not have access to * added code so that in the issues search, we won't use an in clause of issues ids that goes over 1000 * fixed unit test * using 950 as the limit for issue search, removed unneeded group by in GetRepoIDsForIssuesOptions, showing search on pulls dashboard page too (not just issues) Co-authored-by: guillep2k <18600385+guillep2k@users.noreply.github.com>
5 years ago
Shows total tracked time in issue and milestone list (#3341) * Show total tracked time in issue and milestone list Show total tracked time at issue page Signed-off-by: Jonas Franz <info@jonasfranz.software> * Optimizing TotalTimes by using SumInt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fixing wrong total times for milestones caused by a missing JOIN Adding unit tests for total times Signed-off-by: Jonas Franz <info@jonasfranz.software> * Logging error instead of ignoring it Signed-off-by: Jonas Franz <info@jonasfranz.software> * Correcting spelling mistakes Signed-off-by: Jonas Franz <info@jonasfranz.software> * Change error message to a short version Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add error handling to TotalTimes Add variable for totalTimes Signed-off-by: Jonas Franz <info@jonasfranz.de> * Introduce TotalTrackedTimes as variable of issue Load TotalTrackedTimes by loading attributes of IssueList Load TotalTrackedTimes by loading attributes of single issue Add Sec2Time as helper to use it in templates Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fixed test + gofmt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Load TotalTrackedTimes via MilestoneList instead of single requests Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add documentation for MilestoneList Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add documentation for MilestoneList Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix test Signed-off-by: Jonas Franz <info@jonasfranz.software> * Change comment from SQL query to description Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix unit test by using int64 instead of int Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix unit test by using int64 instead of int Signed-off-by: Jonas Franz <info@jonasfranz.software> * Check if timetracker is enabled Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix test by enabling timetracking Signed-off-by: Jonas Franz <info@jonasfranz.de>
7 years ago
Issue due date (#3794) * Started adding deadline to ui * Implemented basic issue due date managing * Improved UI for due date managing * Added at least write access to the repo in order to modify issue due dates * Ui improvements * Added issue comments creation when adding/modifying/removing a due date * Show due date in issue list * Added api support for issue due dates * Fixed lint suggestions * Added deadline to sdk * Updated css * Added support for adding/modifiying deadlines for pull requests via api * Fixed comments not created when updating or removing a deadline * update sdk (will do properly once go-gitea/go-sdk#103 is merged) * enhanced updateIssueDeadline * Removed unnessecary Issue.DeadlineString * UI improvements * Small improvments to comment creation + ui & validation improvements * Check if an issue is overdue is now a seperate function * Updated go-sdk with govendor as it was merged * Simplified isOverdue method * removed unessecary deadline to 0 set * Update swagger definitions * Added missing return * Added an explanary comment * Improved updateIssueDeadline method so it'll only update `deadline_unix` * Small changes and improvements * no need to explicitly load the issue when updating a deadline, just use whats already there * small optimisations * Added check if a deadline was modified before updating it * Moved comment creating logic into its own function * Code cleanup for creating deadline comment * locale improvement * When modifying a deadline, the old deadline is saved with the comment * small improvments to xorm session handling when updating an issue deadline + style nitpicks * style nitpicks * Moved checking for if the user has write acces to middleware
7 years ago
Issue due date (#3794) * Started adding deadline to ui * Implemented basic issue due date managing * Improved UI for due date managing * Added at least write access to the repo in order to modify issue due dates * Ui improvements * Added issue comments creation when adding/modifying/removing a due date * Show due date in issue list * Added api support for issue due dates * Fixed lint suggestions * Added deadline to sdk * Updated css * Added support for adding/modifiying deadlines for pull requests via api * Fixed comments not created when updating or removing a deadline * update sdk (will do properly once go-gitea/go-sdk#103 is merged) * enhanced updateIssueDeadline * Removed unnessecary Issue.DeadlineString * UI improvements * Small improvments to comment creation + ui & validation improvements * Check if an issue is overdue is now a seperate function * Updated go-sdk with govendor as it was merged * Simplified isOverdue method * removed unessecary deadline to 0 set * Update swagger definitions * Added missing return * Added an explanary comment * Improved updateIssueDeadline method so it'll only update `deadline_unix` * Small changes and improvements * no need to explicitly load the issue when updating a deadline, just use whats already there * small optimisations * Added check if a deadline was modified before updating it * Moved comment creating logic into its own function * Code cleanup for creating deadline comment * locale improvement * When modifying a deadline, the old deadline is saved with the comment * small improvments to xorm session handling when updating an issue deadline + style nitpicks * style nitpicks * Moved checking for if the user has write acces to middleware
7 years ago
Shows total tracked time in issue and milestone list (#3341) * Show total tracked time in issue and milestone list Show total tracked time at issue page Signed-off-by: Jonas Franz <info@jonasfranz.software> * Optimizing TotalTimes by using SumInt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fixing wrong total times for milestones caused by a missing JOIN Adding unit tests for total times Signed-off-by: Jonas Franz <info@jonasfranz.software> * Logging error instead of ignoring it Signed-off-by: Jonas Franz <info@jonasfranz.software> * Correcting spelling mistakes Signed-off-by: Jonas Franz <info@jonasfranz.software> * Change error message to a short version Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add error handling to TotalTimes Add variable for totalTimes Signed-off-by: Jonas Franz <info@jonasfranz.de> * Introduce TotalTrackedTimes as variable of issue Load TotalTrackedTimes by loading attributes of IssueList Load TotalTrackedTimes by loading attributes of single issue Add Sec2Time as helper to use it in templates Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fixed test + gofmt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Load TotalTrackedTimes via MilestoneList instead of single requests Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add documentation for MilestoneList Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add documentation for MilestoneList Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix test Signed-off-by: Jonas Franz <info@jonasfranz.software> * Change comment from SQL query to description Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix unit test by using int64 instead of int Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix unit test by using int64 instead of int Signed-off-by: Jonas Franz <info@jonasfranz.software> * Check if timetracker is enabled Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix test by enabling timetracking Signed-off-by: Jonas Franz <info@jonasfranz.de>
7 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
Shows total tracked time in issue and milestone list (#3341) * Show total tracked time in issue and milestone list Show total tracked time at issue page Signed-off-by: Jonas Franz <info@jonasfranz.software> * Optimizing TotalTimes by using SumInt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fixing wrong total times for milestones caused by a missing JOIN Adding unit tests for total times Signed-off-by: Jonas Franz <info@jonasfranz.software> * Logging error instead of ignoring it Signed-off-by: Jonas Franz <info@jonasfranz.software> * Correcting spelling mistakes Signed-off-by: Jonas Franz <info@jonasfranz.software> * Change error message to a short version Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add error handling to TotalTimes Add variable for totalTimes Signed-off-by: Jonas Franz <info@jonasfranz.de> * Introduce TotalTrackedTimes as variable of issue Load TotalTrackedTimes by loading attributes of IssueList Load TotalTrackedTimes by loading attributes of single issue Add Sec2Time as helper to use it in templates Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fixed test + gofmt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Load TotalTrackedTimes via MilestoneList instead of single requests Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add documentation for MilestoneList Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add documentation for MilestoneList Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix test Signed-off-by: Jonas Franz <info@jonasfranz.software> * Change comment from SQL query to description Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix unit test by using int64 instead of int Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix unit test by using int64 instead of int Signed-off-by: Jonas Franz <info@jonasfranz.software> * Check if timetracker is enabled Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix test by enabling timetracking Signed-off-by: Jonas Franz <info@jonasfranz.de>
7 years ago
Shows total tracked time in issue and milestone list (#3341) * Show total tracked time in issue and milestone list Show total tracked time at issue page Signed-off-by: Jonas Franz <info@jonasfranz.software> * Optimizing TotalTimes by using SumInt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fixing wrong total times for milestones caused by a missing JOIN Adding unit tests for total times Signed-off-by: Jonas Franz <info@jonasfranz.software> * Logging error instead of ignoring it Signed-off-by: Jonas Franz <info@jonasfranz.software> * Correcting spelling mistakes Signed-off-by: Jonas Franz <info@jonasfranz.software> * Change error message to a short version Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add error handling to TotalTimes Add variable for totalTimes Signed-off-by: Jonas Franz <info@jonasfranz.de> * Introduce TotalTrackedTimes as variable of issue Load TotalTrackedTimes by loading attributes of IssueList Load TotalTrackedTimes by loading attributes of single issue Add Sec2Time as helper to use it in templates Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fixed test + gofmt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Load TotalTrackedTimes via MilestoneList instead of single requests Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add documentation for MilestoneList Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add documentation for MilestoneList Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix test Signed-off-by: Jonas Franz <info@jonasfranz.software> * Change comment from SQL query to description Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix unit test by using int64 instead of int Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix unit test by using int64 instead of int Signed-off-by: Jonas Franz <info@jonasfranz.software> * Check if timetracker is enabled Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix test by enabling timetracking Signed-off-by: Jonas Franz <info@jonasfranz.de>
7 years ago
9 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
Add Organization Wide Labels (#10814) * Add organization wide labels Implement organization wide labels similar to organization wide webhooks. This lets you create individual labels for organizations that can be used for all repos under that organization (so being able to reuse the same label across multiple repos). This makes it possible for small organizations with many repos to use labels effectively. Fixes #7406 * Add migration * remove comments * fix tests * Update options/locale/locale_en-US.ini Removed unused translation string * show org labels in issue search label filter * Use more clear var name * rename migration after merge from master * comment typo * update migration again after rebase with master * check for orgID <=0 per guillep2k review * fmt * Apply suggestions from code review Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> * remove unused code * Make sure RepoID is 0 when searching orgID per code review * more changes/code review requests * More descriptive translation var per code review * func description/delete comment when issue label deleted instead of hiding it * remove comment * only use issues in that repo when calculating number of open issues for org label on repo label page * Add integration test for IssuesSearch API with labels * remove unused function * Update models/issue_label.go Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> * Use subquery in GetLabelIDsInReposByNames * Fix tests to use correct orgID * fix more tests * IssuesSearch api now uses new BuildLabelNamesIssueIDsCondition. Add a few more tests as well * update comment for clarity * Revert previous code change now that we can use the new BuildLabelNamesIssueIDsCondition * Don't sort repos by date in IssuesSearch API After much debugging I've found a strange issue where in some cases MySQL will return a different result than other enigines if a query is sorted by a null collumn. For example with our integration test data where we don't set updated_unix in repository fixtures: SELECT `id`, `owner_id`, `owner_name`, `lower_name`, `name`, `description`, `website`, `original_service_type`, `original_url`, `default_branch`, `num_watches`, `num_stars`, `num_forks`, `num_issues`, `num_closed_issues`, `num_pulls`, `num_closed_pulls`, `num_milestones`, `num_closed_milestones`, `is_private`, `is_empty`, `is_archived`, `is_mirror`, `status`, `is_fork`, `fork_id`, `is_template`, `template_id`, `size`, `is_fsck_enabled`, `close_issues_via_commit_in_any_branch`, `topics`, `avatar`, `created_unix`, `updated_unix` FROM `repository` ORDER BY updated_unix DESC LIMIT 15 OFFSET 45 Returns different results for MySQL than other engines. However, the similar query: SELECT `id`, `owner_id`, `owner_name`, `lower_name`, `name`, `description`, `website`, `original_service_type`, `original_url`, `default_branch`, `num_watches`, `num_stars`, `num_forks`, `num_issues`, `num_closed_issues`, `num_pulls`, `num_closed_pulls`, `num_milestones`, `num_closed_milestones`, `is_private`, `is_empty`, `is_archived`, `is_mirror`, `status`, `is_fork`, `fork_id`, `is_template`, `template_id`, `size`, `is_fsck_enabled`, `close_issues_via_commit_in_any_branch`, `topics`, `avatar`, `created_unix`, `updated_unix` FROM `repository` ORDER BY updated_unix DESC LIMIT 15 OFFSET 30 Returns the same results. This causes integration tests to fail on MySQL in certain cases but would never show up in a real installation. Since this API call always returns issues based on the optionally provided repo_priority_id or the issueID itself, there is no change to results by changing the repo sorting method used to get ids earlier in the function. * linter is back! * code review * remove now unused option * Fix newline at end of files * more unused code * update to master * check for matching ids before query * Update models/issue_label.go Co-Authored-By: 6543 <6543@obermui.de> * Update models/issue_label.go * update comments * Update routers/org/setting.go Co-authored-by: Lauris BH <lauris@nix.lv> Co-authored-by: guillep2k <18600385+guillep2k@users.noreply.github.com> Co-authored-by: 6543 <6543@obermui.de>
5 years ago
8 years ago
3 years ago
3 years ago
3 years ago
8 years ago
Add Organization Wide Labels (#10814) * Add organization wide labels Implement organization wide labels similar to organization wide webhooks. This lets you create individual labels for organizations that can be used for all repos under that organization (so being able to reuse the same label across multiple repos). This makes it possible for small organizations with many repos to use labels effectively. Fixes #7406 * Add migration * remove comments * fix tests * Update options/locale/locale_en-US.ini Removed unused translation string * show org labels in issue search label filter * Use more clear var name * rename migration after merge from master * comment typo * update migration again after rebase with master * check for orgID <=0 per guillep2k review * fmt * Apply suggestions from code review Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> * remove unused code * Make sure RepoID is 0 when searching orgID per code review * more changes/code review requests * More descriptive translation var per code review * func description/delete comment when issue label deleted instead of hiding it * remove comment * only use issues in that repo when calculating number of open issues for org label on repo label page * Add integration test for IssuesSearch API with labels * remove unused function * Update models/issue_label.go Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> * Use subquery in GetLabelIDsInReposByNames * Fix tests to use correct orgID * fix more tests * IssuesSearch api now uses new BuildLabelNamesIssueIDsCondition. Add a few more tests as well * update comment for clarity * Revert previous code change now that we can use the new BuildLabelNamesIssueIDsCondition * Don't sort repos by date in IssuesSearch API After much debugging I've found a strange issue where in some cases MySQL will return a different result than other enigines if a query is sorted by a null collumn. For example with our integration test data where we don't set updated_unix in repository fixtures: SELECT `id`, `owner_id`, `owner_name`, `lower_name`, `name`, `description`, `website`, `original_service_type`, `original_url`, `default_branch`, `num_watches`, `num_stars`, `num_forks`, `num_issues`, `num_closed_issues`, `num_pulls`, `num_closed_pulls`, `num_milestones`, `num_closed_milestones`, `is_private`, `is_empty`, `is_archived`, `is_mirror`, `status`, `is_fork`, `fork_id`, `is_template`, `template_id`, `size`, `is_fsck_enabled`, `close_issues_via_commit_in_any_branch`, `topics`, `avatar`, `created_unix`, `updated_unix` FROM `repository` ORDER BY updated_unix DESC LIMIT 15 OFFSET 45 Returns different results for MySQL than other engines. However, the similar query: SELECT `id`, `owner_id`, `owner_name`, `lower_name`, `name`, `description`, `website`, `original_service_type`, `original_url`, `default_branch`, `num_watches`, `num_stars`, `num_forks`, `num_issues`, `num_closed_issues`, `num_pulls`, `num_closed_pulls`, `num_milestones`, `num_closed_milestones`, `is_private`, `is_empty`, `is_archived`, `is_mirror`, `status`, `is_fork`, `fork_id`, `is_template`, `template_id`, `size`, `is_fsck_enabled`, `close_issues_via_commit_in_any_branch`, `topics`, `avatar`, `created_unix`, `updated_unix` FROM `repository` ORDER BY updated_unix DESC LIMIT 15 OFFSET 30 Returns the same results. This causes integration tests to fail on MySQL in certain cases but would never show up in a real installation. Since this API call always returns issues based on the optionally provided repo_priority_id or the issueID itself, there is no change to results by changing the repo sorting method used to get ids earlier in the function. * linter is back! * code review * remove now unused option * Fix newline at end of files * more unused code * update to master * check for matching ids before query * Update models/issue_label.go Co-Authored-By: 6543 <6543@obermui.de> * Update models/issue_label.go * update comments * Update routers/org/setting.go Co-authored-by: Lauris BH <lauris@nix.lv> Co-authored-by: guillep2k <18600385+guillep2k@users.noreply.github.com> Co-authored-by: 6543 <6543@obermui.de>
5 years ago
11 years ago
API add/generalize pagination (#9452) * paginate results * fixed deadlock * prevented breaking change * updated swagger * go fmt * fixed find topic * go mod tidy * go mod vendor with go1.13.5 * fixed repo find topics * fixed unit test * added Limit method to Engine struct; use engine variable when provided; fixed gitignore * use ItemsPerPage for default pagesize; fix GetWatchers, getOrgUsersByOrgID and GetStargazers; fix GetAllCommits headers; reverted some changed behaviors * set Page value on Home route * improved memory allocations * fixed response headers * removed logfiles * fixed import order * import order * improved swagger * added function to get models.ListOptions from context * removed pagesize diff on unit test * fixed imports * removed unnecessary struct field * fixed go fmt * scoped PR * code improvements * code improvements * go mod tidy * fixed import order * fixed commit statuses session * fixed files headers * fixed headers; added pagination for notifications * go mod tidy * go fmt * removed Private from user search options; added setting.UI.IssuePagingNum as default valeu on repo's issues list * Apply suggestions from code review Co-Authored-By: 6543 <6543@obermui.de> Co-Authored-By: zeripath <art27@cantab.net> * fixed build error * CI.restart() * fixed merge conflicts resolve * fixed conflicts resolve * improved FindTrackedTimesOptions.ToOptions() method * added backwards compatibility on ListReleases request; fixed issue tracked time ToSession * fixed build error; fixed swagger template * fixed swagger template * fixed ListReleases backwards compatibility * added page to user search route Co-authored-by: techknowlogick <matti@mdranta.net> Co-authored-by: 6543 <6543@obermui.de> Co-authored-by: zeripath <art27@cantab.net>
5 years ago
Allow cross-repository dependencies on issues (#7901) * in progress changes for #7405, added ability to add cross-repo dependencies * removed unused repolink var * fixed query that was breaking ci tests; fixed check in issue dependency add so that the id of the issue and dependency is checked rather than the indexes * reverted removal of string in local files becasue these are done via crowdin, not updated manually * removed 'Select("issue.*")' from getBlockedByDependencies and getBlockingDependencies based on comments in PR review * changed getBlockedByDependencies and getBlockingDependencies to use a more xorm-like query, also updated the sidebar as a result * simplified the getBlockingDependencies and getBlockedByDependencies methods; changed the sidebar to show the dependencies in a different format where you can see the name of the repository * made some changes to the issue view in the dependencies (issue name on top, repo full name on separate line). Change view of issue in the dependency search results (also showing the full repo name on separate line) * replace call to FindUserAccessibleRepoIDs with SearchRepositoryByName. The former was hardcoded to use isPrivate = false on the repo search, but this code needed it to be true. The SearchRepositoryByName method is used more in the code including on the user's dashboard * some more tweaks to the layout of the issues when showing dependencies and in the search box when you add new dependencies * added Name to the RepositoryMeta struct * updated swagger doc * fixed total count for link header on SearchIssues * fixed indentation * fixed aligment of remove icon on dependencies in issue sidebar * removed unnecessary nil check (unnecessary because issue.loadRepo is called prior to this block) * reverting .css change, somehow missed or forgot that less is used * updated less file and generated css; updated sidebar template with styles to line up delete and issue index * added ordering to the blocked by/depends on queries * fixed sorting in issue dependency search and the depends on/blocks views to show issues from the current repo first, then by created date descending; added a "all cross repository dependencies" setting to allow this feature to be turned off, if turned off, the issue dependency search will work the way it did before (restricted to the current repository) * re-applied my swagger changes after merge * fixed split string condition in issue search * changed ALLOW_CROSS_REPOSITORY_DEPENDENCIES description to sound more global than just the issue dependency search; returning 400 in the cross repo issue search api method if not enabled; fixed bug where the issue count did not respect the state parameter * when adding a dependency to an issue, added a check to make sure the issue and dependency are in the same repo if cross repo dependencies is not enabled * updated sortIssuesSession call in PullRequests, another commit moved this method from pull.go to pull_list.go so I had to re-apply my change here * fixed incorrect setting of user id parameter in search repos call
5 years ago
Allow cross-repository dependencies on issues (#7901) * in progress changes for #7405, added ability to add cross-repo dependencies * removed unused repolink var * fixed query that was breaking ci tests; fixed check in issue dependency add so that the id of the issue and dependency is checked rather than the indexes * reverted removal of string in local files becasue these are done via crowdin, not updated manually * removed 'Select("issue.*")' from getBlockedByDependencies and getBlockingDependencies based on comments in PR review * changed getBlockedByDependencies and getBlockingDependencies to use a more xorm-like query, also updated the sidebar as a result * simplified the getBlockingDependencies and getBlockedByDependencies methods; changed the sidebar to show the dependencies in a different format where you can see the name of the repository * made some changes to the issue view in the dependencies (issue name on top, repo full name on separate line). Change view of issue in the dependency search results (also showing the full repo name on separate line) * replace call to FindUserAccessibleRepoIDs with SearchRepositoryByName. The former was hardcoded to use isPrivate = false on the repo search, but this code needed it to be true. The SearchRepositoryByName method is used more in the code including on the user's dashboard * some more tweaks to the layout of the issues when showing dependencies and in the search box when you add new dependencies * added Name to the RepositoryMeta struct * updated swagger doc * fixed total count for link header on SearchIssues * fixed indentation * fixed aligment of remove icon on dependencies in issue sidebar * removed unnecessary nil check (unnecessary because issue.loadRepo is called prior to this block) * reverting .css change, somehow missed or forgot that less is used * updated less file and generated css; updated sidebar template with styles to line up delete and issue index * added ordering to the blocked by/depends on queries * fixed sorting in issue dependency search and the depends on/blocks views to show issues from the current repo first, then by created date descending; added a "all cross repository dependencies" setting to allow this feature to be turned off, if turned off, the issue dependency search will work the way it did before (restricted to the current repository) * re-applied my swagger changes after merge * fixed split string condition in issue search * changed ALLOW_CROSS_REPOSITORY_DEPENDENCIES description to sound more global than just the issue dependency search; returning 400 in the cross repo issue search api method if not enabled; fixed bug where the issue count did not respect the state parameter * when adding a dependency to an issue, added a check to make sure the issue and dependency are in the same repo if cross repo dependencies is not enabled * updated sortIssuesSession call in PullRequests, another commit moved this method from pull.go to pull_list.go so I had to re-apply my change here * fixed incorrect setting of user id parameter in search repos call
5 years ago
Allow cross-repository dependencies on issues (#7901) * in progress changes for #7405, added ability to add cross-repo dependencies * removed unused repolink var * fixed query that was breaking ci tests; fixed check in issue dependency add so that the id of the issue and dependency is checked rather than the indexes * reverted removal of string in local files becasue these are done via crowdin, not updated manually * removed 'Select("issue.*")' from getBlockedByDependencies and getBlockingDependencies based on comments in PR review * changed getBlockedByDependencies and getBlockingDependencies to use a more xorm-like query, also updated the sidebar as a result * simplified the getBlockingDependencies and getBlockedByDependencies methods; changed the sidebar to show the dependencies in a different format where you can see the name of the repository * made some changes to the issue view in the dependencies (issue name on top, repo full name on separate line). Change view of issue in the dependency search results (also showing the full repo name on separate line) * replace call to FindUserAccessibleRepoIDs with SearchRepositoryByName. The former was hardcoded to use isPrivate = false on the repo search, but this code needed it to be true. The SearchRepositoryByName method is used more in the code including on the user's dashboard * some more tweaks to the layout of the issues when showing dependencies and in the search box when you add new dependencies * added Name to the RepositoryMeta struct * updated swagger doc * fixed total count for link header on SearchIssues * fixed indentation * fixed aligment of remove icon on dependencies in issue sidebar * removed unnecessary nil check (unnecessary because issue.loadRepo is called prior to this block) * reverting .css change, somehow missed or forgot that less is used * updated less file and generated css; updated sidebar template with styles to line up delete and issue index * added ordering to the blocked by/depends on queries * fixed sorting in issue dependency search and the depends on/blocks views to show issues from the current repo first, then by created date descending; added a "all cross repository dependencies" setting to allow this feature to be turned off, if turned off, the issue dependency search will work the way it did before (restricted to the current repository) * re-applied my swagger changes after merge * fixed split string condition in issue search * changed ALLOW_CROSS_REPOSITORY_DEPENDENCIES description to sound more global than just the issue dependency search; returning 400 in the cross repo issue search api method if not enabled; fixed bug where the issue count did not respect the state parameter * when adding a dependency to an issue, added a check to make sure the issue and dependency are in the same repo if cross repo dependencies is not enabled * updated sortIssuesSession call in PullRequests, another commit moved this method from pull.go to pull_list.go so I had to re-apply my change here * fixed incorrect setting of user id parameter in search repos call
5 years ago
issue search on my related repositories (#9758) * adding search capability to user's issues dashboard * global issue search * placement of search bar on issues dashboard * fixed some bugs in the issue dashboard search * added unit test because IssueIDs option was added to UserIssueStatsOptions * some renaming of fields in the issue dashboard code to be more clear; also trying to fix issue of searching the right repos based on the filter * added unit test fro GetRepoIDsForIssuesOptions; fixed search lost on pagination; using shown issue status for open/close count; removed some debugging * fix issue with all count showing incorrectly * removed todo comment left in by mistake * typo pulling wrong count * fxied all count being off when selecting repositories * setting the opts.IsClosed after pulling repos to search, this is done so that the list of repo ids to serach for the keyword is not limited, we need to get all the issue ids for the shown issue stats * added "accessibleRepositoryCondition" check on the query to pull the repo ids to search for issues, this is an added protection to ensure we don't search repos the user does not have access to * added code so that in the issues search, we won't use an in clause of issues ids that goes over 1000 * fixed unit test * using 950 as the limit for issue search, removed unneeded group by in GetRepoIDsForIssuesOptions, showing search on pulls dashboard page too (not just issues) Co-authored-by: guillep2k <18600385+guillep2k@users.noreply.github.com>
5 years ago
11 years ago
11 years ago
issue search on my related repositories (#9758) * adding search capability to user's issues dashboard * global issue search * placement of search bar on issues dashboard * fixed some bugs in the issue dashboard search * added unit test because IssueIDs option was added to UserIssueStatsOptions * some renaming of fields in the issue dashboard code to be more clear; also trying to fix issue of searching the right repos based on the filter * added unit test fro GetRepoIDsForIssuesOptions; fixed search lost on pagination; using shown issue status for open/close count; removed some debugging * fix issue with all count showing incorrectly * removed todo comment left in by mistake * typo pulling wrong count * fxied all count being off when selecting repositories * setting the opts.IsClosed after pulling repos to search, this is done so that the list of repo ids to serach for the keyword is not limited, we need to get all the issue ids for the shown issue stats * added "accessibleRepositoryCondition" check on the query to pull the repo ids to search for issues, this is an added protection to ensure we don't search repos the user does not have access to * added code so that in the issues search, we won't use an in clause of issues ids that goes over 1000 * fixed unit test * using 950 as the limit for issue search, removed unneeded group by in GetRepoIDsForIssuesOptions, showing search on pulls dashboard page too (not just issues) Co-authored-by: guillep2k <18600385+guillep2k@users.noreply.github.com>
5 years ago
Allow cross-repository dependencies on issues (#7901) * in progress changes for #7405, added ability to add cross-repo dependencies * removed unused repolink var * fixed query that was breaking ci tests; fixed check in issue dependency add so that the id of the issue and dependency is checked rather than the indexes * reverted removal of string in local files becasue these are done via crowdin, not updated manually * removed 'Select("issue.*")' from getBlockedByDependencies and getBlockingDependencies based on comments in PR review * changed getBlockedByDependencies and getBlockingDependencies to use a more xorm-like query, also updated the sidebar as a result * simplified the getBlockingDependencies and getBlockedByDependencies methods; changed the sidebar to show the dependencies in a different format where you can see the name of the repository * made some changes to the issue view in the dependencies (issue name on top, repo full name on separate line). Change view of issue in the dependency search results (also showing the full repo name on separate line) * replace call to FindUserAccessibleRepoIDs with SearchRepositoryByName. The former was hardcoded to use isPrivate = false on the repo search, but this code needed it to be true. The SearchRepositoryByName method is used more in the code including on the user's dashboard * some more tweaks to the layout of the issues when showing dependencies and in the search box when you add new dependencies * added Name to the RepositoryMeta struct * updated swagger doc * fixed total count for link header on SearchIssues * fixed indentation * fixed aligment of remove icon on dependencies in issue sidebar * removed unnecessary nil check (unnecessary because issue.loadRepo is called prior to this block) * reverting .css change, somehow missed or forgot that less is used * updated less file and generated css; updated sidebar template with styles to line up delete and issue index * added ordering to the blocked by/depends on queries * fixed sorting in issue dependency search and the depends on/blocks views to show issues from the current repo first, then by created date descending; added a "all cross repository dependencies" setting to allow this feature to be turned off, if turned off, the issue dependency search will work the way it did before (restricted to the current repository) * re-applied my swagger changes after merge * fixed split string condition in issue search * changed ALLOW_CROSS_REPOSITORY_DEPENDENCIES description to sound more global than just the issue dependency search; returning 400 in the cross repo issue search api method if not enabled; fixed bug where the issue count did not respect the state parameter * when adding a dependency to an issue, added a check to make sure the issue and dependency are in the same repo if cross repo dependencies is not enabled * updated sortIssuesSession call in PullRequests, another commit moved this method from pull.go to pull_list.go so I had to re-apply my change here * fixed incorrect setting of user id parameter in search repos call
5 years ago
11 years ago
issue search on my related repositories (#9758) * adding search capability to user's issues dashboard * global issue search * placement of search bar on issues dashboard * fixed some bugs in the issue dashboard search * added unit test because IssueIDs option was added to UserIssueStatsOptions * some renaming of fields in the issue dashboard code to be more clear; also trying to fix issue of searching the right repos based on the filter * added unit test fro GetRepoIDsForIssuesOptions; fixed search lost on pagination; using shown issue status for open/close count; removed some debugging * fix issue with all count showing incorrectly * removed todo comment left in by mistake * typo pulling wrong count * fxied all count being off when selecting repositories * setting the opts.IsClosed after pulling repos to search, this is done so that the list of repo ids to serach for the keyword is not limited, we need to get all the issue ids for the shown issue stats * added "accessibleRepositoryCondition" check on the query to pull the repo ids to search for issues, this is an added protection to ensure we don't search repos the user does not have access to * added code so that in the issues search, we won't use an in clause of issues ids that goes over 1000 * fixed unit test * using 950 as the limit for issue search, removed unneeded group by in GetRepoIDsForIssuesOptions, showing search on pulls dashboard page too (not just issues) Co-authored-by: guillep2k <18600385+guillep2k@users.noreply.github.com>
5 years ago
[UI] IssuePage multi repo select (#8741) * Make repository list @ issues/PR page persist Will partially fix #6355 * Enable multiple selections in repo list @ issues/PR page Part of issue #6355 * Add RepoIDs to UserIssueStatsOptions to make "type" count correct when selecting one/multiple repos. * Replace variable "repo" with list "repos[]" and enable multiple selections of repositories from list by including/excluding RepoIDs in list. * * Remove redundant code * Add 'All' button Improves functionality of the page, so that backtracking is not necessary to reset the page * Remove redundant variable Completely replace 'RepoID' with 'RepoIDs' and remove redundant code * Add RepoIDs to label link * Revert part of code to previous version to troubleshoot build failure * Implement old and new pieces of code whilst adhering to multi select * Attempt to join the two versions Last commit passed tests but doesn't work in practice, this works in practice and hopefully passes the tests. * Update tests to desired state * Fix pagination implementation and tests * Pass repoIDs as `repos=[1,2,3...]` instead of several `repos[]=..` * Update tests file to reflect new functionality * Update template with new `repos` format * Implement new solution to show constant "total issues" count for "All" button * Correct behavior when passing zero to array * Comment out test url returning 404 This keeps returning 404 in the test despite working in practice, for the sake of running more tests I am commenting it out * Comment out another test url returning 404 Last attempt, if more tests crash I will uncomment the urls and request assistance. * Reenable tests and test fix * Re-enable tests * Make selecting "In your repositories" reset selection as passing IDs of repos belonging to other profiles causes breakage * Remove unnecessary (with multi-selection enable) code * Drop repo from repo map and total count if permission denied * Remove extra parenthesis * make template work again * find bug! * forgot the '#' at bugfixing * delete unused RepoID * compile regex only one time * make fmt * local variable = capital letter lower * check if repos query pattern is correct * pagination remove last , - make regex work again * use Replace instead of ReplaceAll; del delete * fix test * how did this test binary got in?!? dont forgot the "-p" at git add * ! * dont replace -> cut fisrt & last string Co-Authored-By: zeripath <art27@cantab.net> * jet another regex dont mind as long as it has the same result and is performatn ... Co-Authored-By: zeripath <art27@cantab.net> * dont use nonexisting repo for test * exclude /issues?type=created_by from test * add table to querys use same syntax in each query (table.colum) * add new issue for test * dont make a workaround or something else this need a refactor itself and is out of scope for this PR * fix misspell * CI.redo() * englisch txt update Co-Authored-By: zeripath <art27@cantab.net> * add sugestions * Tweak & Fix * CI.restart()
5 years ago
issue search on my related repositories (#9758) * adding search capability to user's issues dashboard * global issue search * placement of search bar on issues dashboard * fixed some bugs in the issue dashboard search * added unit test because IssueIDs option was added to UserIssueStatsOptions * some renaming of fields in the issue dashboard code to be more clear; also trying to fix issue of searching the right repos based on the filter * added unit test fro GetRepoIDsForIssuesOptions; fixed search lost on pagination; using shown issue status for open/close count; removed some debugging * fix issue with all count showing incorrectly * removed todo comment left in by mistake * typo pulling wrong count * fxied all count being off when selecting repositories * setting the opts.IsClosed after pulling repos to search, this is done so that the list of repo ids to serach for the keyword is not limited, we need to get all the issue ids for the shown issue stats * added "accessibleRepositoryCondition" check on the query to pull the repo ids to search for issues, this is an added protection to ensure we don't search repos the user does not have access to * added code so that in the issues search, we won't use an in clause of issues ids that goes over 1000 * fixed unit test * using 950 as the limit for issue search, removed unneeded group by in GetRepoIDsForIssuesOptions, showing search on pulls dashboard page too (not just issues) Co-authored-by: guillep2k <18600385+guillep2k@users.noreply.github.com>
5 years ago
[UI] IssuePage multi repo select (#8741) * Make repository list @ issues/PR page persist Will partially fix #6355 * Enable multiple selections in repo list @ issues/PR page Part of issue #6355 * Add RepoIDs to UserIssueStatsOptions to make "type" count correct when selecting one/multiple repos. * Replace variable "repo" with list "repos[]" and enable multiple selections of repositories from list by including/excluding RepoIDs in list. * * Remove redundant code * Add 'All' button Improves functionality of the page, so that backtracking is not necessary to reset the page * Remove redundant variable Completely replace 'RepoID' with 'RepoIDs' and remove redundant code * Add RepoIDs to label link * Revert part of code to previous version to troubleshoot build failure * Implement old and new pieces of code whilst adhering to multi select * Attempt to join the two versions Last commit passed tests but doesn't work in practice, this works in practice and hopefully passes the tests. * Update tests to desired state * Fix pagination implementation and tests * Pass repoIDs as `repos=[1,2,3...]` instead of several `repos[]=..` * Update tests file to reflect new functionality * Update template with new `repos` format * Implement new solution to show constant "total issues" count for "All" button * Correct behavior when passing zero to array * Comment out test url returning 404 This keeps returning 404 in the test despite working in practice, for the sake of running more tests I am commenting it out * Comment out another test url returning 404 Last attempt, if more tests crash I will uncomment the urls and request assistance. * Reenable tests and test fix * Re-enable tests * Make selecting "In your repositories" reset selection as passing IDs of repos belonging to other profiles causes breakage * Remove unnecessary (with multi-selection enable) code * Drop repo from repo map and total count if permission denied * Remove extra parenthesis * make template work again * find bug! * forgot the '#' at bugfixing * delete unused RepoID * compile regex only one time * make fmt * local variable = capital letter lower * check if repos query pattern is correct * pagination remove last , - make regex work again * use Replace instead of ReplaceAll; del delete * fix test * how did this test binary got in?!? dont forgot the "-p" at git add * ! * dont replace -> cut fisrt & last string Co-Authored-By: zeripath <art27@cantab.net> * jet another regex dont mind as long as it has the same result and is performatn ... Co-Authored-By: zeripath <art27@cantab.net> * dont use nonexisting repo for test * exclude /issues?type=created_by from test * add table to querys use same syntax in each query (table.colum) * add new issue for test * dont make a workaround or something else this need a refactor itself and is out of scope for this PR * fix misspell * CI.redo() * englisch txt update Co-Authored-By: zeripath <art27@cantab.net> * add sugestions * Tweak & Fix * CI.restart()
5 years ago
issue search on my related repositories (#9758) * adding search capability to user's issues dashboard * global issue search * placement of search bar on issues dashboard * fixed some bugs in the issue dashboard search * added unit test because IssueIDs option was added to UserIssueStatsOptions * some renaming of fields in the issue dashboard code to be more clear; also trying to fix issue of searching the right repos based on the filter * added unit test fro GetRepoIDsForIssuesOptions; fixed search lost on pagination; using shown issue status for open/close count; removed some debugging * fix issue with all count showing incorrectly * removed todo comment left in by mistake * typo pulling wrong count * fxied all count being off when selecting repositories * setting the opts.IsClosed after pulling repos to search, this is done so that the list of repo ids to serach for the keyword is not limited, we need to get all the issue ids for the shown issue stats * added "accessibleRepositoryCondition" check on the query to pull the repo ids to search for issues, this is an added protection to ensure we don't search repos the user does not have access to * added code so that in the issues search, we won't use an in clause of issues ids that goes over 1000 * fixed unit test * using 950 as the limit for issue search, removed unneeded group by in GetRepoIDsForIssuesOptions, showing search on pulls dashboard page too (not just issues) Co-authored-by: guillep2k <18600385+guillep2k@users.noreply.github.com>
5 years ago
[UI] IssuePage multi repo select (#8741) * Make repository list @ issues/PR page persist Will partially fix #6355 * Enable multiple selections in repo list @ issues/PR page Part of issue #6355 * Add RepoIDs to UserIssueStatsOptions to make "type" count correct when selecting one/multiple repos. * Replace variable "repo" with list "repos[]" and enable multiple selections of repositories from list by including/excluding RepoIDs in list. * * Remove redundant code * Add 'All' button Improves functionality of the page, so that backtracking is not necessary to reset the page * Remove redundant variable Completely replace 'RepoID' with 'RepoIDs' and remove redundant code * Add RepoIDs to label link * Revert part of code to previous version to troubleshoot build failure * Implement old and new pieces of code whilst adhering to multi select * Attempt to join the two versions Last commit passed tests but doesn't work in practice, this works in practice and hopefully passes the tests. * Update tests to desired state * Fix pagination implementation and tests * Pass repoIDs as `repos=[1,2,3...]` instead of several `repos[]=..` * Update tests file to reflect new functionality * Update template with new `repos` format * Implement new solution to show constant "total issues" count for "All" button * Correct behavior when passing zero to array * Comment out test url returning 404 This keeps returning 404 in the test despite working in practice, for the sake of running more tests I am commenting it out * Comment out another test url returning 404 Last attempt, if more tests crash I will uncomment the urls and request assistance. * Reenable tests and test fix * Re-enable tests * Make selecting "In your repositories" reset selection as passing IDs of repos belonging to other profiles causes breakage * Remove unnecessary (with multi-selection enable) code * Drop repo from repo map and total count if permission denied * Remove extra parenthesis * make template work again * find bug! * forgot the '#' at bugfixing * delete unused RepoID * compile regex only one time * make fmt * local variable = capital letter lower * check if repos query pattern is correct * pagination remove last , - make regex work again * use Replace instead of ReplaceAll; del delete * fix test * how did this test binary got in?!? dont forgot the "-p" at git add * ! * dont replace -> cut fisrt & last string Co-Authored-By: zeripath <art27@cantab.net> * jet another regex dont mind as long as it has the same result and is performatn ... Co-Authored-By: zeripath <art27@cantab.net> * dont use nonexisting repo for test * exclude /issues?type=created_by from test * add table to querys use same syntax in each query (table.colum) * add new issue for test * dont make a workaround or something else this need a refactor itself and is out of scope for this PR * fix misspell * CI.redo() * englisch txt update Co-Authored-By: zeripath <art27@cantab.net> * add sugestions * Tweak & Fix * CI.restart()
5 years ago
[UI] IssuePage multi repo select (#8741) * Make repository list @ issues/PR page persist Will partially fix #6355 * Enable multiple selections in repo list @ issues/PR page Part of issue #6355 * Add RepoIDs to UserIssueStatsOptions to make "type" count correct when selecting one/multiple repos. * Replace variable "repo" with list "repos[]" and enable multiple selections of repositories from list by including/excluding RepoIDs in list. * * Remove redundant code * Add 'All' button Improves functionality of the page, so that backtracking is not necessary to reset the page * Remove redundant variable Completely replace 'RepoID' with 'RepoIDs' and remove redundant code * Add RepoIDs to label link * Revert part of code to previous version to troubleshoot build failure * Implement old and new pieces of code whilst adhering to multi select * Attempt to join the two versions Last commit passed tests but doesn't work in practice, this works in practice and hopefully passes the tests. * Update tests to desired state * Fix pagination implementation and tests * Pass repoIDs as `repos=[1,2,3...]` instead of several `repos[]=..` * Update tests file to reflect new functionality * Update template with new `repos` format * Implement new solution to show constant "total issues" count for "All" button * Correct behavior when passing zero to array * Comment out test url returning 404 This keeps returning 404 in the test despite working in practice, for the sake of running more tests I am commenting it out * Comment out another test url returning 404 Last attempt, if more tests crash I will uncomment the urls and request assistance. * Reenable tests and test fix * Re-enable tests * Make selecting "In your repositories" reset selection as passing IDs of repos belonging to other profiles causes breakage * Remove unnecessary (with multi-selection enable) code * Drop repo from repo map and total count if permission denied * Remove extra parenthesis * make template work again * find bug! * forgot the '#' at bugfixing * delete unused RepoID * compile regex only one time * make fmt * local variable = capital letter lower * check if repos query pattern is correct * pagination remove last , - make regex work again * use Replace instead of ReplaceAll; del delete * fix test * how did this test binary got in?!? dont forgot the "-p" at git add * ! * dont replace -> cut fisrt & last string Co-Authored-By: zeripath <art27@cantab.net> * jet another regex dont mind as long as it has the same result and is performatn ... Co-Authored-By: zeripath <art27@cantab.net> * dont use nonexisting repo for test * exclude /issues?type=created_by from test * add table to querys use same syntax in each query (table.colum) * add new issue for test * dont make a workaround or something else this need a refactor itself and is out of scope for this PR * fix misspell * CI.redo() * englisch txt update Co-Authored-By: zeripath <art27@cantab.net> * add sugestions * Tweak & Fix * CI.restart()
5 years ago
[UI] IssuePage multi repo select (#8741) * Make repository list @ issues/PR page persist Will partially fix #6355 * Enable multiple selections in repo list @ issues/PR page Part of issue #6355 * Add RepoIDs to UserIssueStatsOptions to make "type" count correct when selecting one/multiple repos. * Replace variable "repo" with list "repos[]" and enable multiple selections of repositories from list by including/excluding RepoIDs in list. * * Remove redundant code * Add 'All' button Improves functionality of the page, so that backtracking is not necessary to reset the page * Remove redundant variable Completely replace 'RepoID' with 'RepoIDs' and remove redundant code * Add RepoIDs to label link * Revert part of code to previous version to troubleshoot build failure * Implement old and new pieces of code whilst adhering to multi select * Attempt to join the two versions Last commit passed tests but doesn't work in practice, this works in practice and hopefully passes the tests. * Update tests to desired state * Fix pagination implementation and tests * Pass repoIDs as `repos=[1,2,3...]` instead of several `repos[]=..` * Update tests file to reflect new functionality * Update template with new `repos` format * Implement new solution to show constant "total issues" count for "All" button * Correct behavior when passing zero to array * Comment out test url returning 404 This keeps returning 404 in the test despite working in practice, for the sake of running more tests I am commenting it out * Comment out another test url returning 404 Last attempt, if more tests crash I will uncomment the urls and request assistance. * Reenable tests and test fix * Re-enable tests * Make selecting "In your repositories" reset selection as passing IDs of repos belonging to other profiles causes breakage * Remove unnecessary (with multi-selection enable) code * Drop repo from repo map and total count if permission denied * Remove extra parenthesis * make template work again * find bug! * forgot the '#' at bugfixing * delete unused RepoID * compile regex only one time * make fmt * local variable = capital letter lower * check if repos query pattern is correct * pagination remove last , - make regex work again * use Replace instead of ReplaceAll; del delete * fix test * how did this test binary got in?!? dont forgot the "-p" at git add * ! * dont replace -> cut fisrt & last string Co-Authored-By: zeripath <art27@cantab.net> * jet another regex dont mind as long as it has the same result and is performatn ... Co-Authored-By: zeripath <art27@cantab.net> * dont use nonexisting repo for test * exclude /issues?type=created_by from test * add table to querys use same syntax in each query (table.colum) * add new issue for test * dont make a workaround or something else this need a refactor itself and is out of scope for this PR * fix misspell * CI.redo() * englisch txt update Co-Authored-By: zeripath <art27@cantab.net> * add sugestions * Tweak & Fix * CI.restart()
5 years ago
[UI] IssuePage multi repo select (#8741) * Make repository list @ issues/PR page persist Will partially fix #6355 * Enable multiple selections in repo list @ issues/PR page Part of issue #6355 * Add RepoIDs to UserIssueStatsOptions to make "type" count correct when selecting one/multiple repos. * Replace variable "repo" with list "repos[]" and enable multiple selections of repositories from list by including/excluding RepoIDs in list. * * Remove redundant code * Add 'All' button Improves functionality of the page, so that backtracking is not necessary to reset the page * Remove redundant variable Completely replace 'RepoID' with 'RepoIDs' and remove redundant code * Add RepoIDs to label link * Revert part of code to previous version to troubleshoot build failure * Implement old and new pieces of code whilst adhering to multi select * Attempt to join the two versions Last commit passed tests but doesn't work in practice, this works in practice and hopefully passes the tests. * Update tests to desired state * Fix pagination implementation and tests * Pass repoIDs as `repos=[1,2,3...]` instead of several `repos[]=..` * Update tests file to reflect new functionality * Update template with new `repos` format * Implement new solution to show constant "total issues" count for "All" button * Correct behavior when passing zero to array * Comment out test url returning 404 This keeps returning 404 in the test despite working in practice, for the sake of running more tests I am commenting it out * Comment out another test url returning 404 Last attempt, if more tests crash I will uncomment the urls and request assistance. * Reenable tests and test fix * Re-enable tests * Make selecting "In your repositories" reset selection as passing IDs of repos belonging to other profiles causes breakage * Remove unnecessary (with multi-selection enable) code * Drop repo from repo map and total count if permission denied * Remove extra parenthesis * make template work again * find bug! * forgot the '#' at bugfixing * delete unused RepoID * compile regex only one time * make fmt * local variable = capital letter lower * check if repos query pattern is correct * pagination remove last , - make regex work again * use Replace instead of ReplaceAll; del delete * fix test * how did this test binary got in?!? dont forgot the "-p" at git add * ! * dont replace -> cut fisrt & last string Co-Authored-By: zeripath <art27@cantab.net> * jet another regex dont mind as long as it has the same result and is performatn ... Co-Authored-By: zeripath <art27@cantab.net> * dont use nonexisting repo for test * exclude /issues?type=created_by from test * add table to querys use same syntax in each query (table.colum) * add new issue for test * dont make a workaround or something else this need a refactor itself and is out of scope for this PR * fix misspell * CI.redo() * englisch txt update Co-Authored-By: zeripath <art27@cantab.net> * add sugestions * Tweak & Fix * CI.restart()
5 years ago
Allow cross-repository dependencies on issues (#7901) * in progress changes for #7405, added ability to add cross-repo dependencies * removed unused repolink var * fixed query that was breaking ci tests; fixed check in issue dependency add so that the id of the issue and dependency is checked rather than the indexes * reverted removal of string in local files becasue these are done via crowdin, not updated manually * removed 'Select("issue.*")' from getBlockedByDependencies and getBlockingDependencies based on comments in PR review * changed getBlockedByDependencies and getBlockingDependencies to use a more xorm-like query, also updated the sidebar as a result * simplified the getBlockingDependencies and getBlockedByDependencies methods; changed the sidebar to show the dependencies in a different format where you can see the name of the repository * made some changes to the issue view in the dependencies (issue name on top, repo full name on separate line). Change view of issue in the dependency search results (also showing the full repo name on separate line) * replace call to FindUserAccessibleRepoIDs with SearchRepositoryByName. The former was hardcoded to use isPrivate = false on the repo search, but this code needed it to be true. The SearchRepositoryByName method is used more in the code including on the user's dashboard * some more tweaks to the layout of the issues when showing dependencies and in the search box when you add new dependencies * added Name to the RepositoryMeta struct * updated swagger doc * fixed total count for link header on SearchIssues * fixed indentation * fixed aligment of remove icon on dependencies in issue sidebar * removed unnecessary nil check (unnecessary because issue.loadRepo is called prior to this block) * reverting .css change, somehow missed or forgot that less is used * updated less file and generated css; updated sidebar template with styles to line up delete and issue index * added ordering to the blocked by/depends on queries * fixed sorting in issue dependency search and the depends on/blocks views to show issues from the current repo first, then by created date descending; added a "all cross repository dependencies" setting to allow this feature to be turned off, if turned off, the issue dependency search will work the way it did before (restricted to the current repository) * re-applied my swagger changes after merge * fixed split string condition in issue search * changed ALLOW_CROSS_REPOSITORY_DEPENDENCIES description to sound more global than just the issue dependency search; returning 400 in the cross repo issue search api method if not enabled; fixed bug where the issue count did not respect the state parameter * when adding a dependency to an issue, added a check to make sure the issue and dependency are in the same repo if cross repo dependencies is not enabled * updated sortIssuesSession call in PullRequests, another commit moved this method from pull.go to pull_list.go so I had to re-apply my change here * fixed incorrect setting of user id parameter in search repos call
5 years ago
Issue due date (#3794) * Started adding deadline to ui * Implemented basic issue due date managing * Improved UI for due date managing * Added at least write access to the repo in order to modify issue due dates * Ui improvements * Added issue comments creation when adding/modifying/removing a due date * Show due date in issue list * Added api support for issue due dates * Fixed lint suggestions * Added deadline to sdk * Updated css * Added support for adding/modifiying deadlines for pull requests via api * Fixed comments not created when updating or removing a deadline * update sdk (will do properly once go-gitea/go-sdk#103 is merged) * enhanced updateIssueDeadline * Removed unnessecary Issue.DeadlineString * UI improvements * Small improvments to comment creation + ui & validation improvements * Check if an issue is overdue is now a seperate function * Updated go-sdk with govendor as it was merged * Simplified isOverdue method * removed unessecary deadline to 0 set * Update swagger definitions * Added missing return * Added an explanary comment * Improved updateIssueDeadline method so it'll only update `deadline_unix` * Small changes and improvements * no need to explicitly load the issue when updating a deadline, just use whats already there * small optimisations * Added check if a deadline was modified before updating it * Moved comment creating logic into its own function * Code cleanup for creating deadline comment * locale improvement * When modifying a deadline, the old deadline is saved with the comment * small improvments to xorm session handling when updating an issue deadline + style nitpicks * style nitpicks * Moved checking for if the user has write acces to middleware
7 years ago
Issue due date (#3794) * Started adding deadline to ui * Implemented basic issue due date managing * Improved UI for due date managing * Added at least write access to the repo in order to modify issue due dates * Ui improvements * Added issue comments creation when adding/modifying/removing a due date * Show due date in issue list * Added api support for issue due dates * Fixed lint suggestions * Added deadline to sdk * Updated css * Added support for adding/modifiying deadlines for pull requests via api * Fixed comments not created when updating or removing a deadline * update sdk (will do properly once go-gitea/go-sdk#103 is merged) * enhanced updateIssueDeadline * Removed unnessecary Issue.DeadlineString * UI improvements * Small improvments to comment creation + ui & validation improvements * Check if an issue is overdue is now a seperate function * Updated go-sdk with govendor as it was merged * Simplified isOverdue method * removed unessecary deadline to 0 set * Update swagger definitions * Added missing return * Added an explanary comment * Improved updateIssueDeadline method so it'll only update `deadline_unix` * Small changes and improvements * no need to explicitly load the issue when updating a deadline, just use whats already there * small optimisations * Added check if a deadline was modified before updating it * Moved comment creating logic into its own function * Code cleanup for creating deadline comment * locale improvement * When modifying a deadline, the old deadline is saved with the comment * small improvments to xorm session handling when updating an issue deadline + style nitpicks * style nitpicks * Moved checking for if the user has write acces to middleware
7 years ago
Allow cross-repository dependencies on issues (#7901) * in progress changes for #7405, added ability to add cross-repo dependencies * removed unused repolink var * fixed query that was breaking ci tests; fixed check in issue dependency add so that the id of the issue and dependency is checked rather than the indexes * reverted removal of string in local files becasue these are done via crowdin, not updated manually * removed 'Select("issue.*")' from getBlockedByDependencies and getBlockingDependencies based on comments in PR review * changed getBlockedByDependencies and getBlockingDependencies to use a more xorm-like query, also updated the sidebar as a result * simplified the getBlockingDependencies and getBlockedByDependencies methods; changed the sidebar to show the dependencies in a different format where you can see the name of the repository * made some changes to the issue view in the dependencies (issue name on top, repo full name on separate line). Change view of issue in the dependency search results (also showing the full repo name on separate line) * replace call to FindUserAccessibleRepoIDs with SearchRepositoryByName. The former was hardcoded to use isPrivate = false on the repo search, but this code needed it to be true. The SearchRepositoryByName method is used more in the code including on the user's dashboard * some more tweaks to the layout of the issues when showing dependencies and in the search box when you add new dependencies * added Name to the RepositoryMeta struct * updated swagger doc * fixed total count for link header on SearchIssues * fixed indentation * fixed aligment of remove icon on dependencies in issue sidebar * removed unnecessary nil check (unnecessary because issue.loadRepo is called prior to this block) * reverting .css change, somehow missed or forgot that less is used * updated less file and generated css; updated sidebar template with styles to line up delete and issue index * added ordering to the blocked by/depends on queries * fixed sorting in issue dependency search and the depends on/blocks views to show issues from the current repo first, then by created date descending; added a "all cross repository dependencies" setting to allow this feature to be turned off, if turned off, the issue dependency search will work the way it did before (restricted to the current repository) * re-applied my swagger changes after merge * fixed split string condition in issue search * changed ALLOW_CROSS_REPOSITORY_DEPENDENCIES description to sound more global than just the issue dependency search; returning 400 in the cross repo issue search api method if not enabled; fixed bug where the issue count did not respect the state parameter * when adding a dependency to an issue, added a check to make sure the issue and dependency are in the same repo if cross repo dependencies is not enabled * updated sortIssuesSession call in PullRequests, another commit moved this method from pull.go to pull_list.go so I had to re-apply my change here * fixed incorrect setting of user id parameter in search repos call
5 years ago
Allow cross-repository dependencies on issues (#7901) * in progress changes for #7405, added ability to add cross-repo dependencies * removed unused repolink var * fixed query that was breaking ci tests; fixed check in issue dependency add so that the id of the issue and dependency is checked rather than the indexes * reverted removal of string in local files becasue these are done via crowdin, not updated manually * removed 'Select("issue.*")' from getBlockedByDependencies and getBlockingDependencies based on comments in PR review * changed getBlockedByDependencies and getBlockingDependencies to use a more xorm-like query, also updated the sidebar as a result * simplified the getBlockingDependencies and getBlockedByDependencies methods; changed the sidebar to show the dependencies in a different format where you can see the name of the repository * made some changes to the issue view in the dependencies (issue name on top, repo full name on separate line). Change view of issue in the dependency search results (also showing the full repo name on separate line) * replace call to FindUserAccessibleRepoIDs with SearchRepositoryByName. The former was hardcoded to use isPrivate = false on the repo search, but this code needed it to be true. The SearchRepositoryByName method is used more in the code including on the user's dashboard * some more tweaks to the layout of the issues when showing dependencies and in the search box when you add new dependencies * added Name to the RepositoryMeta struct * updated swagger doc * fixed total count for link header on SearchIssues * fixed indentation * fixed aligment of remove icon on dependencies in issue sidebar * removed unnecessary nil check (unnecessary because issue.loadRepo is called prior to this block) * reverting .css change, somehow missed or forgot that less is used * updated less file and generated css; updated sidebar template with styles to line up delete and issue index * added ordering to the blocked by/depends on queries * fixed sorting in issue dependency search and the depends on/blocks views to show issues from the current repo first, then by created date descending; added a "all cross repository dependencies" setting to allow this feature to be turned off, if turned off, the issue dependency search will work the way it did before (restricted to the current repository) * re-applied my swagger changes after merge * fixed split string condition in issue search * changed ALLOW_CROSS_REPOSITORY_DEPENDENCIES description to sound more global than just the issue dependency search; returning 400 in the cross repo issue search api method if not enabled; fixed bug where the issue count did not respect the state parameter * when adding a dependency to an issue, added a check to make sure the issue and dependency are in the same repo if cross repo dependencies is not enabled * updated sortIssuesSession call in PullRequests, another commit moved this method from pull.go to pull_list.go so I had to re-apply my change here * fixed incorrect setting of user id parameter in search repos call
5 years ago
Allow cross-repository dependencies on issues (#7901) * in progress changes for #7405, added ability to add cross-repo dependencies * removed unused repolink var * fixed query that was breaking ci tests; fixed check in issue dependency add so that the id of the issue and dependency is checked rather than the indexes * reverted removal of string in local files becasue these are done via crowdin, not updated manually * removed 'Select("issue.*")' from getBlockedByDependencies and getBlockingDependencies based on comments in PR review * changed getBlockedByDependencies and getBlockingDependencies to use a more xorm-like query, also updated the sidebar as a result * simplified the getBlockingDependencies and getBlockedByDependencies methods; changed the sidebar to show the dependencies in a different format where you can see the name of the repository * made some changes to the issue view in the dependencies (issue name on top, repo full name on separate line). Change view of issue in the dependency search results (also showing the full repo name on separate line) * replace call to FindUserAccessibleRepoIDs with SearchRepositoryByName. The former was hardcoded to use isPrivate = false on the repo search, but this code needed it to be true. The SearchRepositoryByName method is used more in the code including on the user's dashboard * some more tweaks to the layout of the issues when showing dependencies and in the search box when you add new dependencies * added Name to the RepositoryMeta struct * updated swagger doc * fixed total count for link header on SearchIssues * fixed indentation * fixed aligment of remove icon on dependencies in issue sidebar * removed unnecessary nil check (unnecessary because issue.loadRepo is called prior to this block) * reverting .css change, somehow missed or forgot that less is used * updated less file and generated css; updated sidebar template with styles to line up delete and issue index * added ordering to the blocked by/depends on queries * fixed sorting in issue dependency search and the depends on/blocks views to show issues from the current repo first, then by created date descending; added a "all cross repository dependencies" setting to allow this feature to be turned off, if turned off, the issue dependency search will work the way it did before (restricted to the current repository) * re-applied my swagger changes after merge * fixed split string condition in issue search * changed ALLOW_CROSS_REPOSITORY_DEPENDENCIES description to sound more global than just the issue dependency search; returning 400 in the cross repo issue search api method if not enabled; fixed bug where the issue count did not respect the state parameter * when adding a dependency to an issue, added a check to make sure the issue and dependency are in the same repo if cross repo dependencies is not enabled * updated sortIssuesSession call in PullRequests, another commit moved this method from pull.go to pull_list.go so I had to re-apply my change here * fixed incorrect setting of user id parameter in search repos call
5 years ago
Allow cross-repository dependencies on issues (#7901) * in progress changes for #7405, added ability to add cross-repo dependencies * removed unused repolink var * fixed query that was breaking ci tests; fixed check in issue dependency add so that the id of the issue and dependency is checked rather than the indexes * reverted removal of string in local files becasue these are done via crowdin, not updated manually * removed 'Select("issue.*")' from getBlockedByDependencies and getBlockingDependencies based on comments in PR review * changed getBlockedByDependencies and getBlockingDependencies to use a more xorm-like query, also updated the sidebar as a result * simplified the getBlockingDependencies and getBlockedByDependencies methods; changed the sidebar to show the dependencies in a different format where you can see the name of the repository * made some changes to the issue view in the dependencies (issue name on top, repo full name on separate line). Change view of issue in the dependency search results (also showing the full repo name on separate line) * replace call to FindUserAccessibleRepoIDs with SearchRepositoryByName. The former was hardcoded to use isPrivate = false on the repo search, but this code needed it to be true. The SearchRepositoryByName method is used more in the code including on the user's dashboard * some more tweaks to the layout of the issues when showing dependencies and in the search box when you add new dependencies * added Name to the RepositoryMeta struct * updated swagger doc * fixed total count for link header on SearchIssues * fixed indentation * fixed aligment of remove icon on dependencies in issue sidebar * removed unnecessary nil check (unnecessary because issue.loadRepo is called prior to this block) * reverting .css change, somehow missed or forgot that less is used * updated less file and generated css; updated sidebar template with styles to line up delete and issue index * added ordering to the blocked by/depends on queries * fixed sorting in issue dependency search and the depends on/blocks views to show issues from the current repo first, then by created date descending; added a "all cross repository dependencies" setting to allow this feature to be turned off, if turned off, the issue dependency search will work the way it did before (restricted to the current repository) * re-applied my swagger changes after merge * fixed split string condition in issue search * changed ALLOW_CROSS_REPOSITORY_DEPENDENCIES description to sound more global than just the issue dependency search; returning 400 in the cross repo issue search api method if not enabled; fixed bug where the issue count did not respect the state parameter * when adding a dependency to an issue, added a check to make sure the issue and dependency are in the same repo if cross repo dependencies is not enabled * updated sortIssuesSession call in PullRequests, another commit moved this method from pull.go to pull_list.go so I had to re-apply my change here * fixed incorrect setting of user id parameter in search repos call
5 years ago
Allow cross-repository dependencies on issues (#7901) * in progress changes for #7405, added ability to add cross-repo dependencies * removed unused repolink var * fixed query that was breaking ci tests; fixed check in issue dependency add so that the id of the issue and dependency is checked rather than the indexes * reverted removal of string in local files becasue these are done via crowdin, not updated manually * removed 'Select("issue.*")' from getBlockedByDependencies and getBlockingDependencies based on comments in PR review * changed getBlockedByDependencies and getBlockingDependencies to use a more xorm-like query, also updated the sidebar as a result * simplified the getBlockingDependencies and getBlockedByDependencies methods; changed the sidebar to show the dependencies in a different format where you can see the name of the repository * made some changes to the issue view in the dependencies (issue name on top, repo full name on separate line). Change view of issue in the dependency search results (also showing the full repo name on separate line) * replace call to FindUserAccessibleRepoIDs with SearchRepositoryByName. The former was hardcoded to use isPrivate = false on the repo search, but this code needed it to be true. The SearchRepositoryByName method is used more in the code including on the user's dashboard * some more tweaks to the layout of the issues when showing dependencies and in the search box when you add new dependencies * added Name to the RepositoryMeta struct * updated swagger doc * fixed total count for link header on SearchIssues * fixed indentation * fixed aligment of remove icon on dependencies in issue sidebar * removed unnecessary nil check (unnecessary because issue.loadRepo is called prior to this block) * reverting .css change, somehow missed or forgot that less is used * updated less file and generated css; updated sidebar template with styles to line up delete and issue index * added ordering to the blocked by/depends on queries * fixed sorting in issue dependency search and the depends on/blocks views to show issues from the current repo first, then by created date descending; added a "all cross repository dependencies" setting to allow this feature to be turned off, if turned off, the issue dependency search will work the way it did before (restricted to the current repository) * re-applied my swagger changes after merge * fixed split string condition in issue search * changed ALLOW_CROSS_REPOSITORY_DEPENDENCIES description to sound more global than just the issue dependency search; returning 400 in the cross repo issue search api method if not enabled; fixed bug where the issue count did not respect the state parameter * when adding a dependency to an issue, added a check to make sure the issue and dependency are in the same repo if cross repo dependencies is not enabled * updated sortIssuesSession call in PullRequests, another commit moved this method from pull.go to pull_list.go so I had to re-apply my change here * fixed incorrect setting of user id parameter in search repos call
5 years ago
Allow cross-repository dependencies on issues (#7901) * in progress changes for #7405, added ability to add cross-repo dependencies * removed unused repolink var * fixed query that was breaking ci tests; fixed check in issue dependency add so that the id of the issue and dependency is checked rather than the indexes * reverted removal of string in local files becasue these are done via crowdin, not updated manually * removed 'Select("issue.*")' from getBlockedByDependencies and getBlockingDependencies based on comments in PR review * changed getBlockedByDependencies and getBlockingDependencies to use a more xorm-like query, also updated the sidebar as a result * simplified the getBlockingDependencies and getBlockedByDependencies methods; changed the sidebar to show the dependencies in a different format where you can see the name of the repository * made some changes to the issue view in the dependencies (issue name on top, repo full name on separate line). Change view of issue in the dependency search results (also showing the full repo name on separate line) * replace call to FindUserAccessibleRepoIDs with SearchRepositoryByName. The former was hardcoded to use isPrivate = false on the repo search, but this code needed it to be true. The SearchRepositoryByName method is used more in the code including on the user's dashboard * some more tweaks to the layout of the issues when showing dependencies and in the search box when you add new dependencies * added Name to the RepositoryMeta struct * updated swagger doc * fixed total count for link header on SearchIssues * fixed indentation * fixed aligment of remove icon on dependencies in issue sidebar * removed unnecessary nil check (unnecessary because issue.loadRepo is called prior to this block) * reverting .css change, somehow missed or forgot that less is used * updated less file and generated css; updated sidebar template with styles to line up delete and issue index * added ordering to the blocked by/depends on queries * fixed sorting in issue dependency search and the depends on/blocks views to show issues from the current repo first, then by created date descending; added a "all cross repository dependencies" setting to allow this feature to be turned off, if turned off, the issue dependency search will work the way it did before (restricted to the current repository) * re-applied my swagger changes after merge * fixed split string condition in issue search * changed ALLOW_CROSS_REPOSITORY_DEPENDENCIES description to sound more global than just the issue dependency search; returning 400 in the cross repo issue search api method if not enabled; fixed bug where the issue count did not respect the state parameter * when adding a dependency to an issue, added a check to make sure the issue and dependency are in the same repo if cross repo dependencies is not enabled * updated sortIssuesSession call in PullRequests, another commit moved this method from pull.go to pull_list.go so I had to re-apply my change here * fixed incorrect setting of user id parameter in search repos call
5 years ago
Allow cross-repository dependencies on issues (#7901) * in progress changes for #7405, added ability to add cross-repo dependencies * removed unused repolink var * fixed query that was breaking ci tests; fixed check in issue dependency add so that the id of the issue and dependency is checked rather than the indexes * reverted removal of string in local files becasue these are done via crowdin, not updated manually * removed 'Select("issue.*")' from getBlockedByDependencies and getBlockingDependencies based on comments in PR review * changed getBlockedByDependencies and getBlockingDependencies to use a more xorm-like query, also updated the sidebar as a result * simplified the getBlockingDependencies and getBlockedByDependencies methods; changed the sidebar to show the dependencies in a different format where you can see the name of the repository * made some changes to the issue view in the dependencies (issue name on top, repo full name on separate line). Change view of issue in the dependency search results (also showing the full repo name on separate line) * replace call to FindUserAccessibleRepoIDs with SearchRepositoryByName. The former was hardcoded to use isPrivate = false on the repo search, but this code needed it to be true. The SearchRepositoryByName method is used more in the code including on the user's dashboard * some more tweaks to the layout of the issues when showing dependencies and in the search box when you add new dependencies * added Name to the RepositoryMeta struct * updated swagger doc * fixed total count for link header on SearchIssues * fixed indentation * fixed aligment of remove icon on dependencies in issue sidebar * removed unnecessary nil check (unnecessary because issue.loadRepo is called prior to this block) * reverting .css change, somehow missed or forgot that less is used * updated less file and generated css; updated sidebar template with styles to line up delete and issue index * added ordering to the blocked by/depends on queries * fixed sorting in issue dependency search and the depends on/blocks views to show issues from the current repo first, then by created date descending; added a "all cross repository dependencies" setting to allow this feature to be turned off, if turned off, the issue dependency search will work the way it did before (restricted to the current repository) * re-applied my swagger changes after merge * fixed split string condition in issue search * changed ALLOW_CROSS_REPOSITORY_DEPENDENCIES description to sound more global than just the issue dependency search; returning 400 in the cross repo issue search api method if not enabled; fixed bug where the issue count did not respect the state parameter * when adding a dependency to an issue, added a check to make sure the issue and dependency are in the same repo if cross repo dependencies is not enabled * updated sortIssuesSession call in PullRequests, another commit moved this method from pull.go to pull_list.go so I had to re-apply my change here * fixed incorrect setting of user id parameter in search repos call
5 years ago
Allow cross-repository dependencies on issues (#7901) * in progress changes for #7405, added ability to add cross-repo dependencies * removed unused repolink var * fixed query that was breaking ci tests; fixed check in issue dependency add so that the id of the issue and dependency is checked rather than the indexes * reverted removal of string in local files becasue these are done via crowdin, not updated manually * removed 'Select("issue.*")' from getBlockedByDependencies and getBlockingDependencies based on comments in PR review * changed getBlockedByDependencies and getBlockingDependencies to use a more xorm-like query, also updated the sidebar as a result * simplified the getBlockingDependencies and getBlockedByDependencies methods; changed the sidebar to show the dependencies in a different format where you can see the name of the repository * made some changes to the issue view in the dependencies (issue name on top, repo full name on separate line). Change view of issue in the dependency search results (also showing the full repo name on separate line) * replace call to FindUserAccessibleRepoIDs with SearchRepositoryByName. The former was hardcoded to use isPrivate = false on the repo search, but this code needed it to be true. The SearchRepositoryByName method is used more in the code including on the user's dashboard * some more tweaks to the layout of the issues when showing dependencies and in the search box when you add new dependencies * added Name to the RepositoryMeta struct * updated swagger doc * fixed total count for link header on SearchIssues * fixed indentation * fixed aligment of remove icon on dependencies in issue sidebar * removed unnecessary nil check (unnecessary because issue.loadRepo is called prior to this block) * reverting .css change, somehow missed or forgot that less is used * updated less file and generated css; updated sidebar template with styles to line up delete and issue index * added ordering to the blocked by/depends on queries * fixed sorting in issue dependency search and the depends on/blocks views to show issues from the current repo first, then by created date descending; added a "all cross repository dependencies" setting to allow this feature to be turned off, if turned off, the issue dependency search will work the way it did before (restricted to the current repository) * re-applied my swagger changes after merge * fixed split string condition in issue search * changed ALLOW_CROSS_REPOSITORY_DEPENDENCIES description to sound more global than just the issue dependency search; returning 400 in the cross repo issue search api method if not enabled; fixed bug where the issue count did not respect the state parameter * when adding a dependency to an issue, added a check to make sure the issue and dependency are in the same repo if cross repo dependencies is not enabled * updated sortIssuesSession call in PullRequests, another commit moved this method from pull.go to pull_list.go so I had to re-apply my change here * fixed incorrect setting of user id parameter in search repos call
5 years ago
Allow cross-repository dependencies on issues (#7901) * in progress changes for #7405, added ability to add cross-repo dependencies * removed unused repolink var * fixed query that was breaking ci tests; fixed check in issue dependency add so that the id of the issue and dependency is checked rather than the indexes * reverted removal of string in local files becasue these are done via crowdin, not updated manually * removed 'Select("issue.*")' from getBlockedByDependencies and getBlockingDependencies based on comments in PR review * changed getBlockedByDependencies and getBlockingDependencies to use a more xorm-like query, also updated the sidebar as a result * simplified the getBlockingDependencies and getBlockedByDependencies methods; changed the sidebar to show the dependencies in a different format where you can see the name of the repository * made some changes to the issue view in the dependencies (issue name on top, repo full name on separate line). Change view of issue in the dependency search results (also showing the full repo name on separate line) * replace call to FindUserAccessibleRepoIDs with SearchRepositoryByName. The former was hardcoded to use isPrivate = false on the repo search, but this code needed it to be true. The SearchRepositoryByName method is used more in the code including on the user's dashboard * some more tweaks to the layout of the issues when showing dependencies and in the search box when you add new dependencies * added Name to the RepositoryMeta struct * updated swagger doc * fixed total count for link header on SearchIssues * fixed indentation * fixed aligment of remove icon on dependencies in issue sidebar * removed unnecessary nil check (unnecessary because issue.loadRepo is called prior to this block) * reverting .css change, somehow missed or forgot that less is used * updated less file and generated css; updated sidebar template with styles to line up delete and issue index * added ordering to the blocked by/depends on queries * fixed sorting in issue dependency search and the depends on/blocks views to show issues from the current repo first, then by created date descending; added a "all cross repository dependencies" setting to allow this feature to be turned off, if turned off, the issue dependency search will work the way it did before (restricted to the current repository) * re-applied my swagger changes after merge * fixed split string condition in issue search * changed ALLOW_CROSS_REPOSITORY_DEPENDENCIES description to sound more global than just the issue dependency search; returning 400 in the cross repo issue search api method if not enabled; fixed bug where the issue count did not respect the state parameter * when adding a dependency to an issue, added a check to make sure the issue and dependency are in the same repo if cross repo dependencies is not enabled * updated sortIssuesSession call in PullRequests, another commit moved this method from pull.go to pull_list.go so I had to re-apply my change here * fixed incorrect setting of user id parameter in search repos call
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Copyright 2020 The Gitea Authors. All rights reserved.
  3. // Use of this source code is governed by a MIT-style
  4. // license that can be found in the LICENSE file.
  5. package models
  6. import (
  7. "fmt"
  8. "regexp"
  9. "sort"
  10. "strconv"
  11. "strings"
  12. "code.gitea.io/gitea/modules/base"
  13. "code.gitea.io/gitea/modules/log"
  14. "code.gitea.io/gitea/modules/setting"
  15. "code.gitea.io/gitea/modules/structs"
  16. api "code.gitea.io/gitea/modules/structs"
  17. "code.gitea.io/gitea/modules/timeutil"
  18. "code.gitea.io/gitea/modules/util"
  19. "github.com/unknwon/com"
  20. "xorm.io/builder"
  21. "xorm.io/xorm"
  22. )
  23. // Issue represents an issue or pull request of repository.
  24. type Issue struct {
  25. ID int64 `xorm:"pk autoincr"`
  26. RepoID int64 `xorm:"INDEX UNIQUE(repo_index)"`
  27. Repo *Repository `xorm:"-"`
  28. Index int64 `xorm:"UNIQUE(repo_index)"` // Index in one repository.
  29. PosterID int64 `xorm:"INDEX"`
  30. Poster *User `xorm:"-"`
  31. OriginalAuthor string
  32. OriginalAuthorID int64 `xorm:"index"`
  33. Title string `xorm:"name"`
  34. Content string `xorm:"TEXT"`
  35. RenderedContent string `xorm:"-"`
  36. Labels []*Label `xorm:"-"`
  37. MilestoneID int64 `xorm:"INDEX"`
  38. Milestone *Milestone `xorm:"-"`
  39. Priority int
  40. AssigneeID int64 `xorm:"-"`
  41. Assignee *User `xorm:"-"`
  42. IsClosed bool `xorm:"INDEX"`
  43. IsRead bool `xorm:"-"`
  44. IsPull bool `xorm:"INDEX"` // Indicates whether is a pull request or not.
  45. PullRequest *PullRequest `xorm:"-"`
  46. NumComments int
  47. Ref string
  48. DeadlineUnix timeutil.TimeStamp `xorm:"INDEX"`
  49. CreatedUnix timeutil.TimeStamp `xorm:"INDEX created"`
  50. UpdatedUnix timeutil.TimeStamp `xorm:"INDEX updated"`
  51. ClosedUnix timeutil.TimeStamp `xorm:"INDEX"`
  52. Attachments []*Attachment `xorm:"-"`
  53. Comments []*Comment `xorm:"-"`
  54. Reactions ReactionList `xorm:"-"`
  55. TotalTrackedTime int64 `xorm:"-"`
  56. Assignees []*User `xorm:"-"`
  57. // IsLocked limits commenting abilities to users on an issue
  58. // with write access
  59. IsLocked bool `xorm:"NOT NULL DEFAULT false"`
  60. //block_chain
  61. Amount int64
  62. IsTransformed bool `xorm:"INDEX NOT NULL DEFAULT false"`
  63. }
  64. var (
  65. issueTasksPat *regexp.Regexp
  66. issueTasksDonePat *regexp.Regexp
  67. )
  68. const issueTasksRegexpStr = `(^\s*[-*]\s\[[\sxX]\]\s.)|(\n\s*[-*]\s\[[\sxX]\]\s.)`
  69. const issueTasksDoneRegexpStr = `(^\s*[-*]\s\[[xX]\]\s.)|(\n\s*[-*]\s\[[xX]\]\s.)`
  70. const issueMaxDupIndexAttempts = 3
  71. const maxIssueIDs = 950
  72. func init() {
  73. issueTasksPat = regexp.MustCompile(issueTasksRegexpStr)
  74. issueTasksDonePat = regexp.MustCompile(issueTasksDoneRegexpStr)
  75. }
  76. func (issue *Issue) loadTotalTimes(e Engine) (err error) {
  77. opts := FindTrackedTimesOptions{IssueID: issue.ID}
  78. issue.TotalTrackedTime, err = opts.ToSession(e).SumInt(&TrackedTime{}, "time")
  79. if err != nil {
  80. return err
  81. }
  82. return nil
  83. }
  84. // IsOverdue checks if the issue is overdue
  85. func (issue *Issue) IsOverdue() bool {
  86. return timeutil.TimeStampNow() >= issue.DeadlineUnix
  87. }
  88. // LoadRepo loads issue's repository
  89. func (issue *Issue) LoadRepo() error {
  90. return issue.loadRepo(x)
  91. }
  92. func (issue *Issue) loadRepo(e Engine) (err error) {
  93. if issue.Repo == nil {
  94. issue.Repo, err = getRepositoryByID(e, issue.RepoID)
  95. if err != nil {
  96. return fmt.Errorf("getRepositoryByID [%d]: %v", issue.RepoID, err)
  97. }
  98. }
  99. return nil
  100. }
  101. // IsTimetrackerEnabled returns true if the repo enables timetracking
  102. func (issue *Issue) IsTimetrackerEnabled() bool {
  103. return issue.isTimetrackerEnabled(x)
  104. }
  105. func (issue *Issue) isTimetrackerEnabled(e Engine) bool {
  106. if err := issue.loadRepo(e); err != nil {
  107. log.Error(fmt.Sprintf("loadRepo: %v", err))
  108. return false
  109. }
  110. return issue.Repo.IsTimetrackerEnabled()
  111. }
  112. // GetPullRequest returns the issue pull request
  113. func (issue *Issue) GetPullRequest() (pr *PullRequest, err error) {
  114. if !issue.IsPull {
  115. return nil, fmt.Errorf("Issue is not a pull request")
  116. }
  117. pr, err = getPullRequestByIssueID(x, issue.ID)
  118. if err != nil {
  119. return nil, err
  120. }
  121. pr.Issue = issue
  122. return
  123. }
  124. // LoadLabels loads labels
  125. func (issue *Issue) LoadLabels() error {
  126. return issue.loadLabels(x)
  127. }
  128. func (issue *Issue) loadLabels(e Engine) (err error) {
  129. if issue.Labels == nil {
  130. issue.Labels, err = getLabelsByIssueID(e, issue.ID)
  131. if err != nil {
  132. return fmt.Errorf("getLabelsByIssueID [%d]: %v", issue.ID, err)
  133. }
  134. }
  135. return nil
  136. }
  137. // LoadPoster loads poster
  138. func (issue *Issue) LoadPoster() error {
  139. return issue.loadPoster(x)
  140. }
  141. func (issue *Issue) loadPoster(e Engine) (err error) {
  142. if issue.Poster == nil {
  143. issue.Poster, err = getUserByID(e, issue.PosterID)
  144. if err != nil {
  145. issue.PosterID = -1
  146. issue.Poster = NewGhostUser()
  147. if !IsErrUserNotExist(err) {
  148. return fmt.Errorf("getUserByID.(poster) [%d]: %v", issue.PosterID, err)
  149. }
  150. err = nil
  151. return
  152. }
  153. }
  154. return
  155. }
  156. func (issue *Issue) loadPullRequest(e Engine) (err error) {
  157. if issue.IsPull && issue.PullRequest == nil {
  158. issue.PullRequest, err = getPullRequestByIssueID(e, issue.ID)
  159. if err != nil {
  160. if IsErrPullRequestNotExist(err) {
  161. return err
  162. }
  163. return fmt.Errorf("getPullRequestByIssueID [%d]: %v", issue.ID, err)
  164. }
  165. issue.PullRequest.Issue = issue
  166. }
  167. return nil
  168. }
  169. // LoadPullRequest loads pull request info
  170. func (issue *Issue) LoadPullRequest() error {
  171. return issue.loadPullRequest(x)
  172. }
  173. func (issue *Issue) loadComments(e Engine) (err error) {
  174. return issue.loadCommentsByType(e, CommentTypeUnknown)
  175. }
  176. // LoadDiscussComments loads discuss comments
  177. func (issue *Issue) LoadDiscussComments() error {
  178. return issue.loadCommentsByType(x, CommentTypeComment)
  179. }
  180. func (issue *Issue) loadCommentsByType(e Engine, tp CommentType) (err error) {
  181. if issue.Comments != nil {
  182. return nil
  183. }
  184. issue.Comments, err = findComments(e, FindCommentsOptions{
  185. IssueID: issue.ID,
  186. Type: tp,
  187. })
  188. return err
  189. }
  190. func (issue *Issue) loadReactions(e Engine) (err error) {
  191. if issue.Reactions != nil {
  192. return nil
  193. }
  194. reactions, err := findReactions(e, FindReactionsOptions{
  195. IssueID: issue.ID,
  196. })
  197. if err != nil {
  198. return err
  199. }
  200. if err = issue.loadRepo(e); err != nil {
  201. return err
  202. }
  203. // Load reaction user data
  204. if _, err := ReactionList(reactions).loadUsers(e, issue.Repo); err != nil {
  205. return err
  206. }
  207. // Cache comments to map
  208. comments := make(map[int64]*Comment)
  209. for _, comment := range issue.Comments {
  210. comments[comment.ID] = comment
  211. }
  212. // Add reactions either to issue or comment
  213. for _, react := range reactions {
  214. if react.CommentID == 0 {
  215. issue.Reactions = append(issue.Reactions, react)
  216. } else if comment, ok := comments[react.CommentID]; ok {
  217. comment.Reactions = append(comment.Reactions, react)
  218. }
  219. }
  220. return nil
  221. }
  222. func (issue *Issue) loadMilestone(e Engine) (err error) {
  223. if issue.Milestone == nil && issue.MilestoneID > 0 {
  224. issue.Milestone, err = getMilestoneByRepoID(e, issue.RepoID, issue.MilestoneID)
  225. if err != nil && !IsErrMilestoneNotExist(err) {
  226. return fmt.Errorf("getMilestoneByRepoID [repo_id: %d, milestone_id: %d]: %v", issue.RepoID, issue.MilestoneID, err)
  227. }
  228. }
  229. return nil
  230. }
  231. func (issue *Issue) loadAttributes(e Engine) (err error) {
  232. if err = issue.loadRepo(e); err != nil {
  233. return
  234. }
  235. if err = issue.loadPoster(e); err != nil {
  236. return
  237. }
  238. if err = issue.loadLabels(e); err != nil {
  239. return
  240. }
  241. if err = issue.loadMilestone(e); err != nil {
  242. return
  243. }
  244. if err = issue.loadAssignees(e); err != nil {
  245. return
  246. }
  247. if err = issue.loadPullRequest(e); err != nil && !IsErrPullRequestNotExist(err) {
  248. // It is possible pull request is not yet created.
  249. return err
  250. }
  251. if issue.Attachments == nil {
  252. issue.Attachments, err = getAttachmentsByIssueID(e, issue.ID)
  253. if err != nil {
  254. return fmt.Errorf("getAttachmentsByIssueID [%d]: %v", issue.ID, err)
  255. }
  256. }
  257. if err = issue.loadComments(e); err != nil {
  258. return err
  259. }
  260. if err = CommentList(issue.Comments).loadAttributes(e); err != nil {
  261. return err
  262. }
  263. if issue.isTimetrackerEnabled(e) {
  264. if err = issue.loadTotalTimes(e); err != nil {
  265. return err
  266. }
  267. }
  268. return issue.loadReactions(e)
  269. }
  270. // LoadAttributes loads the attribute of this issue.
  271. func (issue *Issue) LoadAttributes() error {
  272. return issue.loadAttributes(x)
  273. }
  274. // LoadMilestone load milestone of this issue.
  275. func (issue *Issue) LoadMilestone() error {
  276. return issue.loadMilestone(x)
  277. }
  278. // GetIsRead load the `IsRead` field of the issue
  279. func (issue *Issue) GetIsRead(userID int64) error {
  280. issueUser := &IssueUser{IssueID: issue.ID, UID: userID}
  281. if has, err := x.Get(issueUser); err != nil {
  282. return err
  283. } else if !has {
  284. issue.IsRead = false
  285. return nil
  286. }
  287. issue.IsRead = issueUser.IsRead
  288. return nil
  289. }
  290. // APIURL returns the absolute APIURL to this issue.
  291. func (issue *Issue) APIURL() string {
  292. if issue.Repo == nil {
  293. err := issue.LoadRepo()
  294. if err != nil {
  295. log.Error("Issue[%d].APIURL(): %v", issue.ID, err)
  296. return ""
  297. }
  298. }
  299. return fmt.Sprintf("%s/issues/%d", issue.Repo.APIURL(), issue.Index)
  300. }
  301. // HTMLURL returns the absolute URL to this issue.
  302. func (issue *Issue) HTMLURL() string {
  303. var path string
  304. if issue.IsPull {
  305. path = "pulls"
  306. } else {
  307. path = "issues"
  308. }
  309. return fmt.Sprintf("%s/%s/%d", issue.Repo.HTMLURL(), path, issue.Index)
  310. }
  311. // DiffURL returns the absolute URL to this diff
  312. func (issue *Issue) DiffURL() string {
  313. if issue.IsPull {
  314. return fmt.Sprintf("%s/pulls/%d.diff", issue.Repo.HTMLURL(), issue.Index)
  315. }
  316. return ""
  317. }
  318. // PatchURL returns the absolute URL to this patch
  319. func (issue *Issue) PatchURL() string {
  320. if issue.IsPull {
  321. return fmt.Sprintf("%s/pulls/%d.patch", issue.Repo.HTMLURL(), issue.Index)
  322. }
  323. return ""
  324. }
  325. // State returns string representation of issue status.
  326. func (issue *Issue) State() api.StateType {
  327. if issue.IsClosed {
  328. return api.StateClosed
  329. }
  330. return api.StateOpen
  331. }
  332. // HashTag returns unique hash tag for issue.
  333. func (issue *Issue) HashTag() string {
  334. return "issue-" + com.ToStr(issue.ID)
  335. }
  336. // IsPoster returns true if given user by ID is the poster.
  337. func (issue *Issue) IsPoster(uid int64) bool {
  338. return issue.OriginalAuthorID == 0 && issue.PosterID == uid
  339. }
  340. func (issue *Issue) hasLabel(e Engine, labelID int64) bool {
  341. return hasIssueLabel(e, issue.ID, labelID)
  342. }
  343. // HasLabel returns true if issue has been labeled by given ID.
  344. func (issue *Issue) HasLabel(labelID int64) bool {
  345. return issue.hasLabel(x, labelID)
  346. }
  347. // ReplyReference returns tokenized address to use for email reply headers
  348. func (issue *Issue) ReplyReference() string {
  349. var path string
  350. if issue.IsPull {
  351. path = "pulls"
  352. } else {
  353. path = "issues"
  354. }
  355. return fmt.Sprintf("%s/%s/%d@%s", issue.Repo.FullName(), path, issue.Index, setting.Domain)
  356. }
  357. func (issue *Issue) addLabel(e *xorm.Session, label *Label, doer *User) error {
  358. return newIssueLabel(e, issue, label, doer)
  359. }
  360. func (issue *Issue) addLabels(e *xorm.Session, labels []*Label, doer *User) error {
  361. return newIssueLabels(e, issue, labels, doer)
  362. }
  363. func (issue *Issue) getLabels(e Engine) (err error) {
  364. if len(issue.Labels) > 0 {
  365. return nil
  366. }
  367. issue.Labels, err = getLabelsByIssueID(e, issue.ID)
  368. if err != nil {
  369. return fmt.Errorf("getLabelsByIssueID: %v", err)
  370. }
  371. return nil
  372. }
  373. func (issue *Issue) removeLabel(e *xorm.Session, doer *User, label *Label) error {
  374. return deleteIssueLabel(e, issue, label, doer)
  375. }
  376. func (issue *Issue) clearLabels(e *xorm.Session, doer *User) (err error) {
  377. if err = issue.getLabels(e); err != nil {
  378. return fmt.Errorf("getLabels: %v", err)
  379. }
  380. for i := range issue.Labels {
  381. if err = issue.removeLabel(e, doer, issue.Labels[i]); err != nil {
  382. return fmt.Errorf("removeLabel: %v", err)
  383. }
  384. }
  385. return nil
  386. }
  387. // ClearLabels removes all issue labels as the given user.
  388. // Triggers appropriate WebHooks, if any.
  389. func (issue *Issue) ClearLabels(doer *User) (err error) {
  390. sess := x.NewSession()
  391. defer sess.Close()
  392. if err = sess.Begin(); err != nil {
  393. return err
  394. }
  395. if err := issue.loadRepo(sess); err != nil {
  396. return err
  397. } else if err = issue.loadPullRequest(sess); err != nil {
  398. return err
  399. }
  400. perm, err := getUserRepoPermission(sess, issue.Repo, doer)
  401. if err != nil {
  402. return err
  403. }
  404. if !perm.CanWriteIssuesOrPulls(issue.IsPull) {
  405. return ErrRepoLabelNotExist{}
  406. }
  407. if err = issue.clearLabels(sess, doer); err != nil {
  408. return err
  409. }
  410. if err = sess.Commit(); err != nil {
  411. return fmt.Errorf("Commit: %v", err)
  412. }
  413. return nil
  414. }
  415. type labelSorter []*Label
  416. func (ts labelSorter) Len() int {
  417. return len([]*Label(ts))
  418. }
  419. func (ts labelSorter) Less(i, j int) bool {
  420. return []*Label(ts)[i].ID < []*Label(ts)[j].ID
  421. }
  422. func (ts labelSorter) Swap(i, j int) {
  423. []*Label(ts)[i], []*Label(ts)[j] = []*Label(ts)[j], []*Label(ts)[i]
  424. }
  425. // ReplaceLabels removes all current labels and add new labels to the issue.
  426. // Triggers appropriate WebHooks, if any.
  427. func (issue *Issue) ReplaceLabels(labels []*Label, doer *User) (err error) {
  428. sess := x.NewSession()
  429. defer sess.Close()
  430. if err = sess.Begin(); err != nil {
  431. return err
  432. }
  433. if err = issue.loadLabels(sess); err != nil {
  434. return err
  435. }
  436. sort.Sort(labelSorter(labels))
  437. sort.Sort(labelSorter(issue.Labels))
  438. var toAdd, toRemove []*Label
  439. addIndex, removeIndex := 0, 0
  440. for addIndex < len(labels) && removeIndex < len(issue.Labels) {
  441. addLabel := labels[addIndex]
  442. removeLabel := issue.Labels[removeIndex]
  443. if addLabel.ID == removeLabel.ID {
  444. addIndex++
  445. removeIndex++
  446. } else if addLabel.ID < removeLabel.ID {
  447. toAdd = append(toAdd, addLabel)
  448. addIndex++
  449. } else {
  450. toRemove = append(toRemove, removeLabel)
  451. removeIndex++
  452. }
  453. }
  454. toAdd = append(toAdd, labels[addIndex:]...)
  455. toRemove = append(toRemove, issue.Labels[removeIndex:]...)
  456. if len(toAdd) > 0 {
  457. if err = issue.addLabels(sess, toAdd, doer); err != nil {
  458. return fmt.Errorf("addLabels: %v", err)
  459. }
  460. }
  461. for _, l := range toRemove {
  462. if err = issue.removeLabel(sess, doer, l); err != nil {
  463. return fmt.Errorf("removeLabel: %v", err)
  464. }
  465. }
  466. return sess.Commit()
  467. }
  468. // ReadBy sets issue to be read by given user.
  469. func (issue *Issue) ReadBy(userID int64) error {
  470. if err := UpdateIssueUserByRead(userID, issue.ID); err != nil {
  471. return err
  472. }
  473. return setNotificationStatusReadIfUnread(x, userID, issue.ID)
  474. }
  475. func updateIssueCols(e Engine, issue *Issue, cols ...string) error {
  476. if _, err := e.ID(issue.ID).Cols(cols...).Update(issue); err != nil {
  477. return err
  478. }
  479. return nil
  480. }
  481. func (issue *Issue) changeStatus(e *xorm.Session, doer *User, isClosed, isMergePull bool) (*Comment, error) {
  482. // Reload the issue
  483. currentIssue, err := getIssueByID(e, issue.ID)
  484. if err != nil {
  485. return nil, err
  486. }
  487. // Nothing should be performed if current status is same as target status
  488. if currentIssue.IsClosed == isClosed {
  489. if !issue.IsPull {
  490. return nil, ErrIssueWasClosed{
  491. ID: issue.ID,
  492. }
  493. }
  494. return nil, ErrPullWasClosed{
  495. ID: issue.ID,
  496. }
  497. }
  498. issue.IsClosed = isClosed
  499. return issue.doChangeStatus(e, doer, isMergePull)
  500. }
  501. func (issue *Issue) doChangeStatus(e *xorm.Session, doer *User, isMergePull bool) (*Comment, error) {
  502. // Check for open dependencies
  503. if issue.IsClosed && issue.Repo.isDependenciesEnabled(e) {
  504. // 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
  505. noDeps, err := issueNoDependenciesLeft(e, issue)
  506. if err != nil {
  507. return nil, err
  508. }
  509. if !noDeps {
  510. return nil, ErrDependenciesLeft{issue.ID}
  511. }
  512. }
  513. if issue.IsClosed {
  514. issue.ClosedUnix = timeutil.TimeStampNow()
  515. } else {
  516. issue.ClosedUnix = 0
  517. }
  518. if err := updateIssueCols(e, issue, "is_closed", "closed_unix"); err != nil {
  519. return nil, err
  520. }
  521. // Update issue count of labels
  522. if err := issue.getLabels(e); err != nil {
  523. return nil, err
  524. }
  525. for idx := range issue.Labels {
  526. if err := updateLabelCols(e, issue.Labels[idx], "num_issues", "num_closed_issue"); err != nil {
  527. return nil, err
  528. }
  529. }
  530. // Update issue count of milestone
  531. if err := updateMilestoneClosedNum(e, issue.MilestoneID); err != nil {
  532. return nil, err
  533. }
  534. if err := issue.updateClosedNum(e); err != nil {
  535. return nil, err
  536. }
  537. // New action comment
  538. cmtType := CommentTypeClose
  539. if !issue.IsClosed {
  540. cmtType = CommentTypeReopen
  541. } else if isMergePull {
  542. cmtType = CommentTypeMergePull
  543. }
  544. return createComment(e, &CreateCommentOptions{
  545. Type: cmtType,
  546. Doer: doer,
  547. Repo: issue.Repo,
  548. Issue: issue,
  549. })
  550. }
  551. // ChangeStatus changes issue status to open or closed.
  552. func (issue *Issue) ChangeStatus(doer *User, isClosed bool) (*Comment, error) {
  553. sess := x.NewSession()
  554. defer sess.Close()
  555. if err := sess.Begin(); err != nil {
  556. return nil, err
  557. }
  558. if err := issue.loadRepo(sess); err != nil {
  559. return nil, err
  560. }
  561. if err := issue.loadPoster(sess); err != nil {
  562. return nil, err
  563. }
  564. comment, err := issue.changeStatus(sess, doer, isClosed, false)
  565. if err != nil {
  566. return nil, err
  567. }
  568. if err = sess.Commit(); err != nil {
  569. return nil, fmt.Errorf("Commit: %v", err)
  570. }
  571. return comment, nil
  572. }
  573. // ChangeTitle changes the title of this issue, as the given user.
  574. func (issue *Issue) ChangeTitle(doer *User, oldTitle string) (err error) {
  575. sess := x.NewSession()
  576. defer sess.Close()
  577. if err = sess.Begin(); err != nil {
  578. return err
  579. }
  580. if err = updateIssueCols(sess, issue, "name"); err != nil {
  581. return fmt.Errorf("updateIssueCols: %v", err)
  582. }
  583. if err = issue.loadRepo(sess); err != nil {
  584. return fmt.Errorf("loadRepo: %v", err)
  585. }
  586. var opts = &CreateCommentOptions{
  587. Type: CommentTypeChangeTitle,
  588. Doer: doer,
  589. Repo: issue.Repo,
  590. Issue: issue,
  591. OldTitle: oldTitle,
  592. NewTitle: issue.Title,
  593. }
  594. if _, err = createComment(sess, opts); err != nil {
  595. return fmt.Errorf("createComment: %v", err)
  596. }
  597. if err = issue.addCrossReferences(sess, doer, true); err != nil {
  598. return err
  599. }
  600. return sess.Commit()
  601. }
  602. // AddDeletePRBranchComment adds delete branch comment for pull request issue
  603. func AddDeletePRBranchComment(doer *User, repo *Repository, issueID int64, branchName string) error {
  604. issue, err := getIssueByID(x, issueID)
  605. if err != nil {
  606. return err
  607. }
  608. sess := x.NewSession()
  609. defer sess.Close()
  610. if err := sess.Begin(); err != nil {
  611. return err
  612. }
  613. var opts = &CreateCommentOptions{
  614. Type: CommentTypeDeleteBranch,
  615. Doer: doer,
  616. Repo: repo,
  617. Issue: issue,
  618. CommitSHA: branchName,
  619. }
  620. if _, err = createComment(sess, opts); err != nil {
  621. return err
  622. }
  623. return sess.Commit()
  624. }
  625. // UpdateAttachments update attachments by UUIDs for the issue
  626. func (issue *Issue) UpdateAttachments(uuids []string) (err error) {
  627. sess := x.NewSession()
  628. defer sess.Close()
  629. if err = sess.Begin(); err != nil {
  630. return err
  631. }
  632. attachments, err := getAttachmentsByUUIDs(sess, uuids)
  633. if err != nil {
  634. return fmt.Errorf("getAttachmentsByUUIDs [uuids: %v]: %v", uuids, err)
  635. }
  636. for i := 0; i < len(attachments); i++ {
  637. attachments[i].IssueID = issue.ID
  638. if err := updateAttachment(sess, attachments[i]); err != nil {
  639. return fmt.Errorf("update attachment [id: %d]: %v", attachments[i].ID, err)
  640. }
  641. }
  642. return sess.Commit()
  643. }
  644. // ChangeContent changes issue content, as the given user.
  645. func (issue *Issue) ChangeContent(doer *User, content string) (err error) {
  646. issue.Content = content
  647. sess := x.NewSession()
  648. defer sess.Close()
  649. if err = sess.Begin(); err != nil {
  650. return err
  651. }
  652. if err = updateIssueCols(sess, issue, "content"); err != nil {
  653. return fmt.Errorf("UpdateIssueCols: %v", err)
  654. }
  655. if err = issue.addCrossReferences(sess, doer, true); err != nil {
  656. return err
  657. }
  658. return sess.Commit()
  659. }
  660. // ChangeRef changes issue ref, as the given user.
  661. func (issue *Issue) ChangeRef(doer *User, newRef string) (err error) {
  662. oldRef := issue.Ref
  663. issue.Ref = newRef
  664. if oldRef == newRef {
  665. return nil
  666. }
  667. sess := x.NewSession()
  668. defer sess.Close()
  669. if err = sess.Begin(); err != nil {
  670. return err
  671. }
  672. if err = updateIssueCols(sess, issue, "ref"); err != nil {
  673. sess.Rollback()
  674. return fmt.Errorf("UpdateIssueCols: %v", err)
  675. }
  676. var opts = &CreateCommentOptions{
  677. Type: CommentTypeRef,
  678. Doer: doer,
  679. Repo: issue.Repo,
  680. Issue: issue,
  681. OldRef: oldRef,
  682. NewRef: newRef,
  683. }
  684. if _, err = createComment(sess, opts); err != nil {
  685. sess.Rollback()
  686. return err
  687. }
  688. return sess.Commit()
  689. }
  690. // GetTasks returns the amount of tasks in the issues content
  691. func (issue *Issue) GetTasks() int {
  692. return len(issueTasksPat.FindAllStringIndex(issue.Content, -1))
  693. }
  694. // GetTasksDone returns the amount of completed tasks in the issues content
  695. func (issue *Issue) GetTasksDone() int {
  696. return len(issueTasksDonePat.FindAllStringIndex(issue.Content, -1))
  697. }
  698. // GetLastEventTimestamp returns the last user visible event timestamp, either the creation of this issue or the close.
  699. func (issue *Issue) GetLastEventTimestamp() timeutil.TimeStamp {
  700. if issue.IsClosed {
  701. return issue.ClosedUnix
  702. }
  703. return issue.CreatedUnix
  704. }
  705. // GetLastEventLabel returns the localization label for the current issue.
  706. func (issue *Issue) GetLastEventLabel() string {
  707. if issue.IsClosed {
  708. if issue.IsPull && issue.PullRequest.HasMerged {
  709. return "repo.pulls.merged_by"
  710. }
  711. return "repo.issues.closed_by"
  712. }
  713. return "repo.issues.opened_by"
  714. }
  715. // GetLastComment return last comment for the current issue.
  716. func (issue *Issue) GetLastComment() (*Comment, error) {
  717. var c Comment
  718. exist, err := x.Where("type = ?", CommentTypeComment).
  719. And("issue_id = ?", issue.ID).Desc("id").Get(&c)
  720. if err != nil {
  721. return nil, err
  722. }
  723. if !exist {
  724. return nil, nil
  725. }
  726. return &c, nil
  727. }
  728. // GetLastEventLabelFake returns the localization label for the current issue without providing a link in the username.
  729. func (issue *Issue) GetLastEventLabelFake() string {
  730. if issue.IsClosed {
  731. if issue.IsPull && issue.PullRequest.HasMerged {
  732. return "repo.pulls.merged_by_fake"
  733. }
  734. return "repo.issues.closed_by_fake"
  735. }
  736. return "repo.issues.opened_by_fake"
  737. }
  738. // NewIssueOptions represents the options of a new issue.
  739. type NewIssueOptions struct {
  740. Repo *Repository
  741. Issue *Issue
  742. LabelIDs []int64
  743. Attachments []string // In UUID format.
  744. IsPull bool
  745. }
  746. func newIssue(e *xorm.Session, doer *User, opts NewIssueOptions) (err error) {
  747. opts.Issue.Title = strings.TrimSpace(opts.Issue.Title)
  748. if opts.Issue.MilestoneID > 0 {
  749. milestone, err := getMilestoneByRepoID(e, opts.Issue.RepoID, opts.Issue.MilestoneID)
  750. if err != nil && !IsErrMilestoneNotExist(err) {
  751. return fmt.Errorf("getMilestoneByID: %v", err)
  752. }
  753. // Assume milestone is invalid and drop silently.
  754. opts.Issue.MilestoneID = 0
  755. if milestone != nil {
  756. opts.Issue.MilestoneID = milestone.ID
  757. opts.Issue.Milestone = milestone
  758. }
  759. }
  760. // Milestone validation should happen before insert actual object.
  761. if _, err := e.SetExpr("`index`", "coalesce(MAX(`index`),0)+1").
  762. Where("repo_id=?", opts.Issue.RepoID).
  763. Insert(opts.Issue); err != nil {
  764. return ErrNewIssueInsert{err}
  765. }
  766. inserted, err := getIssueByID(e, opts.Issue.ID)
  767. if err != nil {
  768. return err
  769. }
  770. // Patch Index with the value calculated by the database
  771. opts.Issue.Index = inserted.Index
  772. if opts.Issue.MilestoneID > 0 {
  773. if _, err = e.Exec("UPDATE `milestone` SET num_issues=num_issues+1 WHERE id=?", opts.Issue.MilestoneID); err != nil {
  774. return err
  775. }
  776. var opts = &CreateCommentOptions{
  777. Type: CommentTypeMilestone,
  778. Doer: doer,
  779. Repo: opts.Repo,
  780. Issue: opts.Issue,
  781. OldMilestoneID: 0,
  782. MilestoneID: opts.Issue.MilestoneID,
  783. }
  784. if _, err = createComment(e, opts); err != nil {
  785. return err
  786. }
  787. }
  788. if opts.IsPull {
  789. _, err = e.Exec("UPDATE `repository` SET num_pulls = num_pulls + 1 WHERE id = ?", opts.Issue.RepoID)
  790. } else {
  791. _, err = e.Exec("UPDATE `repository` SET num_issues = num_issues + 1 WHERE id = ?", opts.Issue.RepoID)
  792. }
  793. if err != nil {
  794. return err
  795. }
  796. if len(opts.LabelIDs) > 0 {
  797. // During the session, SQLite3 driver cannot handle retrieve objects after update something.
  798. // So we have to get all needed labels first.
  799. labels := make([]*Label, 0, len(opts.LabelIDs))
  800. if err = e.In("id", opts.LabelIDs).Find(&labels); err != nil {
  801. return fmt.Errorf("find all labels [label_ids: %v]: %v", opts.LabelIDs, err)
  802. }
  803. if err = opts.Issue.loadPoster(e); err != nil {
  804. return err
  805. }
  806. for _, label := range labels {
  807. // Silently drop invalid labels.
  808. if label.RepoID != opts.Repo.ID && label.OrgID != opts.Repo.OwnerID {
  809. continue
  810. }
  811. if err = opts.Issue.addLabel(e, label, opts.Issue.Poster); err != nil {
  812. return fmt.Errorf("addLabel [id: %d]: %v", label.ID, err)
  813. }
  814. }
  815. }
  816. if err = newIssueUsers(e, opts.Repo, opts.Issue); err != nil {
  817. return err
  818. }
  819. if len(opts.Attachments) > 0 {
  820. attachments, err := getAttachmentsByUUIDs(e, opts.Attachments)
  821. if err != nil {
  822. return fmt.Errorf("getAttachmentsByUUIDs [uuids: %v]: %v", opts.Attachments, err)
  823. }
  824. for i := 0; i < len(attachments); i++ {
  825. attachments[i].IssueID = opts.Issue.ID
  826. if _, err = e.ID(attachments[i].ID).Update(attachments[i]); err != nil {
  827. return fmt.Errorf("update attachment [id: %d]: %v", attachments[i].ID, err)
  828. }
  829. }
  830. }
  831. if err = opts.Issue.loadAttributes(e); err != nil {
  832. return err
  833. }
  834. return opts.Issue.addCrossReferences(e, doer, false)
  835. }
  836. // NewIssue creates new issue with labels for repository.
  837. func NewIssue(repo *Repository, issue *Issue, labelIDs []int64, uuids []string) (err error) {
  838. // Retry several times in case INSERT fails due to duplicate key for (repo_id, index); see #7887
  839. i := 0
  840. for {
  841. if err = newIssueAttempt(repo, issue, labelIDs, uuids); err == nil {
  842. return nil
  843. }
  844. if !IsErrNewIssueInsert(err) {
  845. return err
  846. }
  847. if i++; i == issueMaxDupIndexAttempts {
  848. break
  849. }
  850. log.Error("NewIssue: error attempting to insert the new issue; will retry. Original error: %v", err)
  851. }
  852. return fmt.Errorf("NewIssue: too many errors attempting to insert the new issue. Last error was: %v", err)
  853. }
  854. func newIssueAttempt(repo *Repository, issue *Issue, labelIDs []int64, uuids []string) (err error) {
  855. sess := x.NewSession()
  856. defer sess.Close()
  857. if err = sess.Begin(); err != nil {
  858. return err
  859. }
  860. if err = newIssue(sess, issue.Poster, NewIssueOptions{
  861. Repo: repo,
  862. Issue: issue,
  863. LabelIDs: labelIDs,
  864. Attachments: uuids,
  865. }); err != nil {
  866. if IsErrUserDoesNotHaveAccessToRepo(err) || IsErrNewIssueInsert(err) {
  867. return err
  868. }
  869. return fmt.Errorf("newIssue: %v", err)
  870. }
  871. if err = sess.Commit(); err != nil {
  872. return fmt.Errorf("Commit: %v", err)
  873. }
  874. return nil
  875. }
  876. // GetIssueByIndex returns raw issue without loading attributes by index in a repository.
  877. func GetIssueByIndex(repoID, index int64) (*Issue, error) {
  878. issue := &Issue{
  879. RepoID: repoID,
  880. Index: index,
  881. }
  882. has, err := x.Get(issue)
  883. if err != nil {
  884. return nil, err
  885. } else if !has {
  886. return nil, ErrIssueNotExist{0, repoID, index}
  887. }
  888. return issue, nil
  889. }
  890. // GetIssueWithAttrsByIndex returns issue by index in a repository.
  891. func GetIssueWithAttrsByIndex(repoID, index int64) (*Issue, error) {
  892. issue, err := GetIssueByIndex(repoID, index)
  893. if err != nil {
  894. return nil, err
  895. }
  896. return issue, issue.LoadAttributes()
  897. }
  898. func getIssueByID(e Engine, id int64) (*Issue, error) {
  899. issue := new(Issue)
  900. has, err := e.ID(id).Get(issue)
  901. if err != nil {
  902. return nil, err
  903. } else if !has {
  904. return nil, ErrIssueNotExist{id, 0, 0}
  905. }
  906. return issue, nil
  907. }
  908. // GetIssueWithAttrsByID returns an issue with attributes by given ID.
  909. func GetIssueWithAttrsByID(id int64) (*Issue, error) {
  910. issue, err := getIssueByID(x, id)
  911. if err != nil {
  912. return nil, err
  913. }
  914. return issue, issue.loadAttributes(x)
  915. }
  916. // GetIssueByID returns an issue by given ID.
  917. func GetIssueByID(id int64) (*Issue, error) {
  918. return getIssueByID(x, id)
  919. }
  920. func getIssuesByIDs(e Engine, issueIDs []int64) ([]*Issue, error) {
  921. issues := make([]*Issue, 0, 10)
  922. return issues, e.In("id", issueIDs).Find(&issues)
  923. }
  924. func getIssueIDsByRepoID(e Engine, repoID int64) ([]int64, error) {
  925. var ids = make([]int64, 0, 10)
  926. err := e.Table("issue").Where("repo_id = ?", repoID).Find(&ids)
  927. return ids, err
  928. }
  929. // GetIssueIDsByRepoID returns all issue ids by repo id
  930. func GetIssueIDsByRepoID(repoID int64) ([]int64, error) {
  931. return getIssueIDsByRepoID(x, repoID)
  932. }
  933. // GetIssuesByIDs return issues with the given IDs.
  934. func GetIssuesByIDs(issueIDs []int64) ([]*Issue, error) {
  935. return getIssuesByIDs(x, issueIDs)
  936. }
  937. // IssuesOptions represents options of an issue.
  938. type IssuesOptions struct {
  939. ListOptions
  940. RepoIDs []int64 // include all repos if empty
  941. AssigneeID int64
  942. PosterID int64
  943. MentionedID int64
  944. MilestoneIDs []int64
  945. IsClosed util.OptionalBool
  946. IsPull util.OptionalBool
  947. LabelIDs []int64
  948. IncludedLabelNames []string
  949. ExcludedLabelNames []string
  950. SortType string
  951. IssueIDs []int64
  952. // prioritize issues from this repo
  953. PriorityRepoID int64
  954. }
  955. // sortIssuesSession sort an issues-related session based on the provided
  956. // sortType string
  957. func sortIssuesSession(sess *xorm.Session, sortType string, priorityRepoID int64) {
  958. switch sortType {
  959. case "oldest":
  960. sess.Asc("issue.created_unix")
  961. case "recentupdate":
  962. sess.Desc("issue.updated_unix")
  963. case "leastupdate":
  964. sess.Asc("issue.updated_unix")
  965. case "mostcomment":
  966. sess.Desc("issue.num_comments")
  967. case "leastcomment":
  968. sess.Asc("issue.num_comments")
  969. case "priority":
  970. sess.Desc("issue.priority")
  971. case "nearduedate":
  972. // 253370764800 is 01/01/9999 @ 12:00am (UTC)
  973. sess.OrderBy("CASE WHEN issue.deadline_unix = 0 THEN 253370764800 ELSE issue.deadline_unix END ASC")
  974. case "farduedate":
  975. sess.Desc("issue.deadline_unix")
  976. case "priorityrepo":
  977. sess.OrderBy("CASE WHEN issue.repo_id = " + strconv.FormatInt(priorityRepoID, 10) + " THEN 1 ELSE 2 END, issue.created_unix DESC")
  978. default:
  979. sess.Desc("issue.created_unix")
  980. }
  981. }
  982. func (opts *IssuesOptions) setupSession(sess *xorm.Session) {
  983. if opts.Page >= 0 && opts.PageSize > 0 {
  984. var start int
  985. if opts.Page == 0 {
  986. start = 0
  987. } else {
  988. start = (opts.Page - 1) * opts.PageSize
  989. }
  990. sess.Limit(opts.PageSize, start)
  991. }
  992. if len(opts.IssueIDs) > 0 {
  993. if len(opts.IssueIDs) > maxIssueIDs {
  994. opts.IssueIDs = opts.IssueIDs[:maxIssueIDs]
  995. }
  996. sess.In("issue.id", opts.IssueIDs)
  997. }
  998. if len(opts.RepoIDs) > 0 {
  999. // In case repository IDs are provided but actually no repository has issue.
  1000. sess.In("issue.repo_id", opts.RepoIDs)
  1001. }
  1002. switch opts.IsClosed {
  1003. case util.OptionalBoolTrue:
  1004. sess.And("issue.is_closed=?", true)
  1005. case util.OptionalBoolFalse:
  1006. sess.And("issue.is_closed=?", false)
  1007. }
  1008. if opts.AssigneeID > 0 {
  1009. sess.Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  1010. And("issue_assignees.assignee_id = ?", opts.AssigneeID)
  1011. }
  1012. if opts.PosterID > 0 {
  1013. sess.And("issue.poster_id=?", opts.PosterID)
  1014. }
  1015. if opts.MentionedID > 0 {
  1016. sess.Join("INNER", "issue_user", "issue.id = issue_user.issue_id").
  1017. And("issue_user.is_mentioned = ?", true).
  1018. And("issue_user.uid = ?", opts.MentionedID)
  1019. }
  1020. if len(opts.MilestoneIDs) > 0 {
  1021. sess.In("issue.milestone_id", opts.MilestoneIDs)
  1022. }
  1023. switch opts.IsPull {
  1024. case util.OptionalBoolTrue:
  1025. sess.And("issue.is_pull=?", true)
  1026. case util.OptionalBoolFalse:
  1027. sess.And("issue.is_pull=?", false)
  1028. }
  1029. if opts.LabelIDs != nil {
  1030. for i, labelID := range opts.LabelIDs {
  1031. if labelID > 0 {
  1032. sess.Join("INNER", fmt.Sprintf("issue_label il%d", i),
  1033. fmt.Sprintf("issue.id = il%[1]d.issue_id AND il%[1]d.label_id = %[2]d", i, labelID))
  1034. } else {
  1035. sess.Where("issue.id not in (select issue_id from issue_label where label_id = ?)", -labelID)
  1036. }
  1037. }
  1038. }
  1039. if len(opts.IncludedLabelNames) > 0 {
  1040. sess.In("issue.id", BuildLabelNamesIssueIDsCondition(opts.IncludedLabelNames))
  1041. }
  1042. if len(opts.ExcludedLabelNames) > 0 {
  1043. sess.And(builder.NotIn("issue.id", BuildLabelNamesIssueIDsCondition(opts.ExcludedLabelNames)))
  1044. }
  1045. }
  1046. // CountIssuesByRepo map from repoID to number of issues matching the options
  1047. func CountIssuesByRepo(opts *IssuesOptions) (map[int64]int64, error) {
  1048. sess := x.NewSession()
  1049. defer sess.Close()
  1050. opts.setupSession(sess)
  1051. countsSlice := make([]*struct {
  1052. RepoID int64
  1053. Count int64
  1054. }, 0, 10)
  1055. if err := sess.GroupBy("issue.repo_id").
  1056. Select("issue.repo_id AS repo_id, COUNT(*) AS count").
  1057. Table("issue").
  1058. Find(&countsSlice); err != nil {
  1059. return nil, err
  1060. }
  1061. countMap := make(map[int64]int64, len(countsSlice))
  1062. for _, c := range countsSlice {
  1063. countMap[c.RepoID] = c.Count
  1064. }
  1065. return countMap, nil
  1066. }
  1067. // GetRepoIDsForIssuesOptions find all repo ids for the given options
  1068. func GetRepoIDsForIssuesOptions(opts *IssuesOptions, user *User) ([]int64, error) {
  1069. repoIDs := make([]int64, 0, 5)
  1070. sess := x.NewSession()
  1071. defer sess.Close()
  1072. opts.setupSession(sess)
  1073. accessCond := accessibleRepositoryCondition(user)
  1074. if err := sess.Where(accessCond).
  1075. Join("INNER", "repository", "`issue`.repo_id = `repository`.id").
  1076. Distinct("issue.repo_id").
  1077. Table("issue").
  1078. Find(&repoIDs); err != nil {
  1079. return nil, err
  1080. }
  1081. return repoIDs, nil
  1082. }
  1083. // Issues returns a list of issues by given conditions.
  1084. func Issues(opts *IssuesOptions) ([]*Issue, error) {
  1085. sess := x.NewSession()
  1086. defer sess.Close()
  1087. opts.setupSession(sess)
  1088. sortIssuesSession(sess, opts.SortType, opts.PriorityRepoID)
  1089. issues := make([]*Issue, 0, setting.UI.IssuePagingNum)
  1090. if err := sess.Find(&issues); err != nil {
  1091. return nil, fmt.Errorf("Find: %v", err)
  1092. }
  1093. sess.Close()
  1094. if err := IssueList(issues).LoadAttributes(); err != nil {
  1095. return nil, fmt.Errorf("LoadAttributes: %v", err)
  1096. }
  1097. return issues, nil
  1098. }
  1099. // GetParticipantsIDsByIssueID returns the IDs of all users who participated in comments of an issue,
  1100. // but skips joining with `user` for performance reasons.
  1101. // User permissions must be verified elsewhere if required.
  1102. func GetParticipantsIDsByIssueID(issueID int64) ([]int64, error) {
  1103. userIDs := make([]int64, 0, 5)
  1104. return userIDs, x.Table("comment").
  1105. Cols("poster_id").
  1106. Where("issue_id = ?", issueID).
  1107. And("type in (?,?,?)", CommentTypeComment, CommentTypeCode, CommentTypeReview).
  1108. Distinct("poster_id").
  1109. Find(&userIDs)
  1110. }
  1111. // IsUserParticipantsOfIssue return true if user is participants of an issue
  1112. func IsUserParticipantsOfIssue(user *User, issue *Issue) bool {
  1113. userIDs, err := issue.getParticipantIDsByIssue(x)
  1114. if err != nil {
  1115. log.Error(err.Error())
  1116. return false
  1117. }
  1118. return util.IsInt64InSlice(user.ID, userIDs)
  1119. }
  1120. // UpdateIssueMentions updates issue-user relations for mentioned users.
  1121. func UpdateIssueMentions(ctx DBContext, issueID int64, mentions []*User) error {
  1122. if len(mentions) == 0 {
  1123. return nil
  1124. }
  1125. ids := make([]int64, len(mentions))
  1126. for i, u := range mentions {
  1127. ids[i] = u.ID
  1128. }
  1129. if err := UpdateIssueUsersByMentions(ctx, issueID, ids); err != nil {
  1130. return fmt.Errorf("UpdateIssueUsersByMentions: %v", err)
  1131. }
  1132. return nil
  1133. }
  1134. // IssueStats represents issue statistic information.
  1135. type IssueStats struct {
  1136. OpenCount, ClosedCount int64
  1137. YourRepositoriesCount int64
  1138. AssignCount int64
  1139. CreateCount int64
  1140. MentionCount int64
  1141. }
  1142. // Filter modes.
  1143. const (
  1144. FilterModeAll = iota
  1145. FilterModeAssign
  1146. FilterModeCreate
  1147. FilterModeMention
  1148. )
  1149. func parseCountResult(results []map[string][]byte) int64 {
  1150. if len(results) == 0 {
  1151. return 0
  1152. }
  1153. for _, result := range results[0] {
  1154. return com.StrTo(string(result)).MustInt64()
  1155. }
  1156. return 0
  1157. }
  1158. // IssueStatsOptions contains parameters accepted by GetIssueStats.
  1159. type IssueStatsOptions struct {
  1160. RepoID int64
  1161. Labels string
  1162. MilestoneID int64
  1163. AssigneeID int64
  1164. MentionedID int64
  1165. PosterID int64
  1166. IsPull util.OptionalBool
  1167. IssueIDs []int64
  1168. }
  1169. // GetIssueStats returns issue statistic information by given conditions.
  1170. func GetIssueStats(opts *IssueStatsOptions) (*IssueStats, error) {
  1171. if len(opts.IssueIDs) <= maxQueryParameters {
  1172. return getIssueStatsChunk(opts, opts.IssueIDs)
  1173. }
  1174. // If too long a list of IDs is provided, we get the statistics in
  1175. // smaller chunks and get accumulates. Note: this could potentially
  1176. // get us invalid results. The alternative is to insert the list of
  1177. // ids in a temporary table and join from them.
  1178. accum := &IssueStats{}
  1179. for i := 0; i < len(opts.IssueIDs); {
  1180. chunk := i + maxQueryParameters
  1181. if chunk > len(opts.IssueIDs) {
  1182. chunk = len(opts.IssueIDs)
  1183. }
  1184. stats, err := getIssueStatsChunk(opts, opts.IssueIDs[i:chunk])
  1185. if err != nil {
  1186. return nil, err
  1187. }
  1188. accum.OpenCount += stats.OpenCount
  1189. accum.ClosedCount += stats.ClosedCount
  1190. accum.YourRepositoriesCount += stats.YourRepositoriesCount
  1191. accum.AssignCount += stats.AssignCount
  1192. accum.CreateCount += stats.CreateCount
  1193. accum.OpenCount += stats.MentionCount
  1194. i = chunk
  1195. }
  1196. return accum, nil
  1197. }
  1198. func GetPullCountByUserAndRepoId(repoId int64, userId int64) int64 {
  1199. issue := new(Issue)
  1200. total, err := x.Where("is_pull=true and repo_id=? and poster_id=?", repoId, userId).Count(issue)
  1201. if err != nil {
  1202. return 0
  1203. }
  1204. return total
  1205. }
  1206. func getIssueStatsChunk(opts *IssueStatsOptions, issueIDs []int64) (*IssueStats, error) {
  1207. stats := &IssueStats{}
  1208. countSession := func(opts *IssueStatsOptions) *xorm.Session {
  1209. sess := x.
  1210. Where("issue.repo_id = ?", opts.RepoID)
  1211. if len(opts.IssueIDs) > 0 {
  1212. if len(opts.IssueIDs) > maxIssueIDs {
  1213. opts.IssueIDs = opts.IssueIDs[:maxIssueIDs]
  1214. }
  1215. sess.In("issue.id", opts.IssueIDs)
  1216. }
  1217. if len(opts.Labels) > 0 && opts.Labels != "0" {
  1218. labelIDs, err := base.StringsToInt64s(strings.Split(opts.Labels, ","))
  1219. if err != nil {
  1220. log.Warn("Malformed Labels argument: %s", opts.Labels)
  1221. } else {
  1222. for i, labelID := range labelIDs {
  1223. if labelID > 0 {
  1224. sess.Join("INNER", fmt.Sprintf("issue_label il%d", i),
  1225. fmt.Sprintf("issue.id = il%[1]d.issue_id AND il%[1]d.label_id = %[2]d", i, labelID))
  1226. } else {
  1227. sess.Where("issue.id NOT IN (SELECT issue_id FROM issue_label WHERE label_id = ?)", -labelID)
  1228. }
  1229. }
  1230. }
  1231. }
  1232. if opts.MilestoneID > 0 {
  1233. sess.And("issue.milestone_id = ?", opts.MilestoneID)
  1234. } else if opts.MilestoneID == -1 { //only search for issues do not have milestone
  1235. sess.And("issue.milestone_id = ?", 0)
  1236. }
  1237. if opts.AssigneeID > 0 {
  1238. sess.Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  1239. And("issue_assignees.assignee_id = ?", opts.AssigneeID)
  1240. }
  1241. if opts.PosterID > 0 {
  1242. sess.And("issue.poster_id = ?", opts.PosterID)
  1243. }
  1244. if opts.MentionedID > 0 {
  1245. sess.Join("INNER", "issue_user", "issue.id = issue_user.issue_id").
  1246. And("issue_user.uid = ?", opts.MentionedID).
  1247. And("issue_user.is_mentioned = ?", true)
  1248. }
  1249. switch opts.IsPull {
  1250. case util.OptionalBoolTrue:
  1251. sess.And("issue.is_pull=?", true)
  1252. case util.OptionalBoolFalse:
  1253. sess.And("issue.is_pull=?", false)
  1254. }
  1255. return sess
  1256. }
  1257. var err error
  1258. stats.OpenCount, err = countSession(opts).
  1259. And("issue.is_closed = ?", false).
  1260. Count(new(Issue))
  1261. if err != nil {
  1262. return stats, err
  1263. }
  1264. stats.ClosedCount, err = countSession(opts).
  1265. And("issue.is_closed = ?", true).
  1266. Count(new(Issue))
  1267. return stats, err
  1268. }
  1269. // UserIssueStatsOptions contains parameters accepted by GetUserIssueStats.
  1270. type UserIssueStatsOptions struct {
  1271. UserID int64
  1272. RepoIDs []int64
  1273. UserRepoIDs []int64
  1274. FilterMode int
  1275. IsPull bool
  1276. IsClosed bool
  1277. IssueIDs []int64
  1278. }
  1279. // GetUserIssueStats returns issue statistic information for dashboard by given conditions.
  1280. func GetUserIssueStats(opts UserIssueStatsOptions) (*IssueStats, error) {
  1281. var err error
  1282. stats := &IssueStats{}
  1283. cond := builder.NewCond()
  1284. cond = cond.And(builder.Eq{"issue.is_pull": opts.IsPull})
  1285. if len(opts.RepoIDs) > 0 {
  1286. cond = cond.And(builder.In("issue.repo_id", opts.RepoIDs))
  1287. }
  1288. if len(opts.IssueIDs) > 0 {
  1289. if len(opts.IssueIDs) > maxIssueIDs {
  1290. opts.IssueIDs = opts.IssueIDs[:maxIssueIDs]
  1291. }
  1292. cond = cond.And(builder.In("issue.id", opts.IssueIDs))
  1293. }
  1294. switch opts.FilterMode {
  1295. case FilterModeAll:
  1296. stats.OpenCount, err = x.Where(cond).And("issue.is_closed = ?", false).
  1297. And(builder.In("issue.repo_id", opts.UserRepoIDs)).
  1298. Count(new(Issue))
  1299. if err != nil {
  1300. return nil, err
  1301. }
  1302. stats.ClosedCount, err = x.Where(cond).And("issue.is_closed = ?", true).
  1303. And(builder.In("issue.repo_id", opts.UserRepoIDs)).
  1304. Count(new(Issue))
  1305. if err != nil {
  1306. return nil, err
  1307. }
  1308. case FilterModeAssign:
  1309. stats.OpenCount, err = x.Where(cond).And("issue.is_closed = ?", false).
  1310. Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  1311. And("issue_assignees.assignee_id = ?", opts.UserID).
  1312. Count(new(Issue))
  1313. if err != nil {
  1314. return nil, err
  1315. }
  1316. stats.ClosedCount, err = x.Where(cond).And("issue.is_closed = ?", true).
  1317. Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  1318. And("issue_assignees.assignee_id = ?", opts.UserID).
  1319. Count(new(Issue))
  1320. if err != nil {
  1321. return nil, err
  1322. }
  1323. case FilterModeCreate:
  1324. stats.OpenCount, err = x.Where(cond).And("issue.is_closed = ?", false).
  1325. And("issue.poster_id = ?", opts.UserID).
  1326. Count(new(Issue))
  1327. if err != nil {
  1328. return nil, err
  1329. }
  1330. stats.ClosedCount, err = x.Where(cond).And("issue.is_closed = ?", true).
  1331. And("issue.poster_id = ?", opts.UserID).
  1332. Count(new(Issue))
  1333. if err != nil {
  1334. return nil, err
  1335. }
  1336. case FilterModeMention:
  1337. stats.OpenCount, err = x.Where(cond).And("issue.is_closed = ?", false).
  1338. Join("INNER", "issue_user", "issue.id = issue_user.issue_id and issue_user.is_mentioned = ?", true).
  1339. And("issue_user.uid = ?", opts.UserID).
  1340. Count(new(Issue))
  1341. if err != nil {
  1342. return nil, err
  1343. }
  1344. stats.ClosedCount, err = x.Where(cond).And("issue.is_closed = ?", true).
  1345. Join("INNER", "issue_user", "issue.id = issue_user.issue_id and issue_user.is_mentioned = ?", true).
  1346. And("issue_user.uid = ?", opts.UserID).
  1347. Count(new(Issue))
  1348. if err != nil {
  1349. return nil, err
  1350. }
  1351. }
  1352. cond = cond.And(builder.Eq{"issue.is_closed": opts.IsClosed})
  1353. stats.AssignCount, err = x.Where(cond).
  1354. Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  1355. And("issue_assignees.assignee_id = ?", opts.UserID).
  1356. Count(new(Issue))
  1357. if err != nil {
  1358. return nil, err
  1359. }
  1360. stats.CreateCount, err = x.Where(cond).
  1361. And("poster_id = ?", opts.UserID).
  1362. Count(new(Issue))
  1363. if err != nil {
  1364. return nil, err
  1365. }
  1366. stats.MentionCount, err = x.Where(cond).
  1367. Join("INNER", "issue_user", "issue.id = issue_user.issue_id and issue_user.is_mentioned = ?", true).
  1368. And("issue_user.uid = ?", opts.UserID).
  1369. Count(new(Issue))
  1370. if err != nil {
  1371. return nil, err
  1372. }
  1373. stats.YourRepositoriesCount, err = x.Where(cond).
  1374. And(builder.In("issue.repo_id", opts.UserRepoIDs)).
  1375. Count(new(Issue))
  1376. if err != nil {
  1377. return nil, err
  1378. }
  1379. return stats, nil
  1380. }
  1381. // GetRepoIssueStats returns number of open and closed repository issues by given filter mode.
  1382. func GetRepoIssueStats(repoID, uid int64, filterMode int, isPull bool) (numOpen int64, numClosed int64) {
  1383. countSession := func(isClosed, isPull bool, repoID int64) *xorm.Session {
  1384. sess := x.
  1385. Where("is_closed = ?", isClosed).
  1386. And("is_pull = ?", isPull).
  1387. And("repo_id = ?", repoID)
  1388. return sess
  1389. }
  1390. openCountSession := countSession(false, isPull, repoID)
  1391. closedCountSession := countSession(true, isPull, repoID)
  1392. switch filterMode {
  1393. case FilterModeAssign:
  1394. openCountSession.Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  1395. And("issue_assignees.assignee_id = ?", uid)
  1396. closedCountSession.Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  1397. And("issue_assignees.assignee_id = ?", uid)
  1398. case FilterModeCreate:
  1399. openCountSession.And("poster_id = ?", uid)
  1400. closedCountSession.And("poster_id = ?", uid)
  1401. }
  1402. openResult, _ := openCountSession.Count(new(Issue))
  1403. closedResult, _ := closedCountSession.Count(new(Issue))
  1404. return openResult, closedResult
  1405. }
  1406. // SearchIssueIDsByKeyword search issues on database
  1407. func SearchIssueIDsByKeyword(kw string, repoIDs []int64, limit, start int) (int64, []int64, error) {
  1408. var repoCond = builder.In("repo_id", repoIDs)
  1409. var subQuery = builder.Select("id").From("issue").Where(repoCond)
  1410. var cond = builder.And(
  1411. repoCond,
  1412. builder.Or(
  1413. builder.Like{"name", kw},
  1414. builder.Like{"content", kw},
  1415. builder.In("id", builder.Select("issue_id").
  1416. From("comment").
  1417. Where(builder.And(
  1418. builder.Eq{"type": CommentTypeComment},
  1419. builder.In("issue_id", subQuery),
  1420. builder.Like{"content", kw},
  1421. )),
  1422. ),
  1423. ),
  1424. )
  1425. var ids = make([]int64, 0, limit)
  1426. err := x.Distinct("id").Table("issue").Where(cond).Limit(limit, start).Find(&ids)
  1427. if err != nil {
  1428. return 0, nil, err
  1429. }
  1430. total, err := x.Distinct("id").Table("issue").Where(cond).Count()
  1431. if err != nil {
  1432. return 0, nil, err
  1433. }
  1434. return total, ids, nil
  1435. }
  1436. // UpdateIssueByAPI updates all allowed fields of given issue.
  1437. // If the issue status is changed a statusChangeComment is returned
  1438. // similarly if the title is changed the titleChanged bool is set to true
  1439. func UpdateIssueByAPI(issue *Issue, doer *User) (statusChangeComment *Comment, titleChanged bool, err error) {
  1440. sess := x.NewSession()
  1441. defer sess.Close()
  1442. if err := sess.Begin(); err != nil {
  1443. return nil, false, err
  1444. }
  1445. if err := issue.loadRepo(sess); err != nil {
  1446. return nil, false, fmt.Errorf("loadRepo: %v", err)
  1447. }
  1448. // Reload the issue
  1449. currentIssue, err := getIssueByID(sess, issue.ID)
  1450. if err != nil {
  1451. return nil, false, err
  1452. }
  1453. if _, err := sess.ID(issue.ID).Cols(
  1454. "name", "content", "milestone_id", "priority",
  1455. "deadline_unix", "updated_unix", "is_locked").
  1456. Update(issue); err != nil {
  1457. return nil, false, err
  1458. }
  1459. titleChanged = currentIssue.Title != issue.Title
  1460. if titleChanged {
  1461. var opts = &CreateCommentOptions{
  1462. Type: CommentTypeChangeTitle,
  1463. Doer: doer,
  1464. Repo: issue.Repo,
  1465. Issue: issue,
  1466. OldTitle: currentIssue.Title,
  1467. NewTitle: issue.Title,
  1468. }
  1469. _, err := createComment(sess, opts)
  1470. if err != nil {
  1471. return nil, false, fmt.Errorf("createComment: %v", err)
  1472. }
  1473. }
  1474. if currentIssue.IsClosed != issue.IsClosed {
  1475. statusChangeComment, err = issue.doChangeStatus(sess, doer, false)
  1476. if err != nil {
  1477. return nil, false, err
  1478. }
  1479. }
  1480. if err := issue.addCrossReferences(sess, doer, true); err != nil {
  1481. return nil, false, err
  1482. }
  1483. return statusChangeComment, titleChanged, sess.Commit()
  1484. }
  1485. // UpdateIssueDeadline updates an issue deadline and adds comments. Setting a deadline to 0 means deleting it.
  1486. func UpdateIssueDeadline(issue *Issue, deadlineUnix timeutil.TimeStamp, doer *User) (err error) {
  1487. // if the deadline hasn't changed do nothing
  1488. if issue.DeadlineUnix == deadlineUnix {
  1489. return nil
  1490. }
  1491. sess := x.NewSession()
  1492. defer sess.Close()
  1493. if err := sess.Begin(); err != nil {
  1494. return err
  1495. }
  1496. // Update the deadline
  1497. if err = updateIssueCols(sess, &Issue{ID: issue.ID, DeadlineUnix: deadlineUnix}, "deadline_unix"); err != nil {
  1498. return err
  1499. }
  1500. // Make the comment
  1501. if _, err = createDeadlineComment(sess, doer, issue, deadlineUnix); err != nil {
  1502. return fmt.Errorf("createRemovedDueDateComment: %v", err)
  1503. }
  1504. return sess.Commit()
  1505. }
  1506. // DependencyInfo represents high level information about an issue which is a dependency of another issue.
  1507. type DependencyInfo struct {
  1508. Issue `xorm:"extends"`
  1509. Repository `xorm:"extends"`
  1510. }
  1511. // getParticipantIDsByIssue returns all userIDs who are participated in comments of an issue and issue author
  1512. func (issue *Issue) getParticipantIDsByIssue(e Engine) ([]int64, error) {
  1513. if issue == nil {
  1514. return nil, nil
  1515. }
  1516. userIDs := make([]int64, 0, 5)
  1517. if err := e.Table("comment").Cols("poster_id").
  1518. Where("`comment`.issue_id = ?", issue.ID).
  1519. And("`comment`.type in (?,?,?)", CommentTypeComment, CommentTypeCode, CommentTypeReview).
  1520. And("`user`.is_active = ?", true).
  1521. And("`user`.prohibit_login = ?", false).
  1522. Join("INNER", "`user`", "`user`.id = `comment`.poster_id").
  1523. Distinct("poster_id").
  1524. Find(&userIDs); err != nil {
  1525. return nil, fmt.Errorf("get poster IDs: %v", err)
  1526. }
  1527. if !util.IsInt64InSlice(issue.PosterID, userIDs) {
  1528. return append(userIDs, issue.PosterID), nil
  1529. }
  1530. return userIDs, nil
  1531. }
  1532. // Get Blocked By Dependencies, aka all issues this issue is blocked by.
  1533. func (issue *Issue) getBlockedByDependencies(e Engine) (issueDeps []*DependencyInfo, err error) {
  1534. return issueDeps, e.
  1535. Table("issue").
  1536. Join("INNER", "repository", "repository.id = issue.repo_id").
  1537. Join("INNER", "issue_dependency", "issue_dependency.dependency_id = issue.id").
  1538. Where("issue_id = ?", issue.ID).
  1539. //sort by repo id then created date, with the issues of the same repo at the beginning of the list
  1540. OrderBy("CASE WHEN issue.repo_id = " + strconv.FormatInt(issue.RepoID, 10) + " THEN 0 ELSE issue.repo_id END, issue.created_unix DESC").
  1541. Find(&issueDeps)
  1542. }
  1543. // Get Blocking Dependencies, aka all issues this issue blocks.
  1544. func (issue *Issue) getBlockingDependencies(e Engine) (issueDeps []*DependencyInfo, err error) {
  1545. return issueDeps, e.
  1546. Table("issue").
  1547. Join("INNER", "repository", "repository.id = issue.repo_id").
  1548. Join("INNER", "issue_dependency", "issue_dependency.issue_id = issue.id").
  1549. Where("dependency_id = ?", issue.ID).
  1550. //sort by repo id then created date, with the issues of the same repo at the beginning of the list
  1551. OrderBy("CASE WHEN issue.repo_id = " + strconv.FormatInt(issue.RepoID, 10) + " THEN 0 ELSE issue.repo_id END, issue.created_unix DESC").
  1552. Find(&issueDeps)
  1553. }
  1554. // BlockedByDependencies finds all Dependencies an issue is blocked by
  1555. func (issue *Issue) BlockedByDependencies() ([]*DependencyInfo, 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() ([]*DependencyInfo, error) {
  1560. return issue.getBlockingDependencies(x)
  1561. }
  1562. func (issue *Issue) updateClosedNum(e Engine) (err error) {
  1563. if issue.IsPull {
  1564. _, err = e.Exec("UPDATE `repository` SET num_closed_pulls=(SELECT count(*) FROM issue WHERE repo_id=? AND is_pull=? AND is_closed=?) WHERE id=?",
  1565. issue.RepoID,
  1566. true,
  1567. true,
  1568. issue.RepoID,
  1569. )
  1570. } else {
  1571. _, err = e.Exec("UPDATE `repository` SET num_closed_issues=(SELECT count(*) FROM issue WHERE repo_id=? AND is_pull=? AND is_closed=?) WHERE id=?",
  1572. issue.RepoID,
  1573. false,
  1574. true,
  1575. issue.RepoID,
  1576. )
  1577. }
  1578. return
  1579. }
  1580. // ResolveMentionsByVisibility returns the users mentioned in an issue, removing those that
  1581. // don't have access to reading it. Teams are expanded into their users, but organizations are ignored.
  1582. func (issue *Issue) ResolveMentionsByVisibility(ctx DBContext, doer *User, mentions []string) (users []*User, err error) {
  1583. if len(mentions) == 0 {
  1584. return
  1585. }
  1586. if err = issue.loadRepo(ctx.e); err != nil {
  1587. return
  1588. }
  1589. resolved := make(map[string]bool, 20)
  1590. names := make([]string, 0, 20)
  1591. resolved[doer.LowerName] = true
  1592. for _, name := range mentions {
  1593. name := strings.ToLower(name)
  1594. if _, ok := resolved[name]; ok {
  1595. continue
  1596. }
  1597. resolved[name] = false
  1598. names = append(names, name)
  1599. }
  1600. if err := issue.Repo.getOwner(ctx.e); err != nil {
  1601. return nil, err
  1602. }
  1603. if issue.Repo.Owner.IsOrganization() {
  1604. // Since there can be users with names that match the name of a team,
  1605. // if the team exists and can read the issue, the team takes precedence.
  1606. teams := make([]*Team, 0, len(names))
  1607. if err := ctx.e.
  1608. Join("INNER", "team_repo", "team_repo.team_id = team.id").
  1609. Where("team_repo.repo_id=?", issue.Repo.ID).
  1610. In("team.lower_name", names).
  1611. Find(&teams); err != nil {
  1612. return nil, fmt.Errorf("find mentioned teams: %v", err)
  1613. }
  1614. if len(teams) != 0 {
  1615. checked := make([]int64, 0, len(teams))
  1616. unittype := UnitTypeIssues
  1617. if issue.IsPull {
  1618. unittype = UnitTypePullRequests
  1619. }
  1620. for _, team := range teams {
  1621. if team.Authorize >= AccessModeOwner {
  1622. checked = append(checked, team.ID)
  1623. resolved[team.LowerName] = true
  1624. continue
  1625. }
  1626. has, err := ctx.e.Get(&TeamUnit{OrgID: issue.Repo.Owner.ID, TeamID: team.ID, Type: unittype})
  1627. if err != nil {
  1628. return nil, fmt.Errorf("get team units (%d): %v", team.ID, err)
  1629. }
  1630. if has {
  1631. checked = append(checked, team.ID)
  1632. resolved[team.LowerName] = true
  1633. }
  1634. }
  1635. if len(checked) != 0 {
  1636. teamusers := make([]*User, 0, 20)
  1637. if err := ctx.e.
  1638. Join("INNER", "team_user", "team_user.uid = `user`.id").
  1639. In("`team_user`.team_id", checked).
  1640. And("`user`.is_active = ?", true).
  1641. And("`user`.prohibit_login = ?", false).
  1642. Find(&teamusers); err != nil {
  1643. return nil, fmt.Errorf("get teams users: %v", err)
  1644. }
  1645. if len(teamusers) > 0 {
  1646. users = make([]*User, 0, len(teamusers))
  1647. for _, user := range teamusers {
  1648. if already, ok := resolved[user.LowerName]; !ok || !already {
  1649. users = append(users, user)
  1650. resolved[user.LowerName] = true
  1651. }
  1652. }
  1653. }
  1654. }
  1655. }
  1656. // Remove names already in the list to avoid querying the database if pending names remain
  1657. names = make([]string, 0, len(resolved))
  1658. for name, already := range resolved {
  1659. if !already {
  1660. names = append(names, name)
  1661. }
  1662. }
  1663. if len(names) == 0 {
  1664. return
  1665. }
  1666. }
  1667. unchecked := make([]*User, 0, len(names))
  1668. if err := ctx.e.
  1669. Where("`user`.is_active = ?", true).
  1670. And("`user`.prohibit_login = ?", false).
  1671. In("`user`.lower_name", names).
  1672. Find(&unchecked); err != nil {
  1673. return nil, fmt.Errorf("find mentioned users: %v", err)
  1674. }
  1675. for _, user := range unchecked {
  1676. if already := resolved[user.LowerName]; already || user.IsOrganization() {
  1677. continue
  1678. }
  1679. // Normal users must have read access to the referencing issue
  1680. perm, err := getUserRepoPermission(ctx.e, issue.Repo, user)
  1681. if err != nil {
  1682. return nil, fmt.Errorf("getUserRepoPermission [%d]: %v", user.ID, err)
  1683. }
  1684. if !perm.CanReadIssuesOrPulls(issue.IsPull) {
  1685. continue
  1686. }
  1687. users = append(users, user)
  1688. }
  1689. return
  1690. }
  1691. // UpdateIssuesMigrationsByType updates all migrated repositories' issues from gitServiceType to replace originalAuthorID to posterID
  1692. func UpdateIssuesMigrationsByType(gitServiceType structs.GitServiceType, originalAuthorID string, posterID int64) error {
  1693. _, err := x.Table("issue").
  1694. Where("repo_id IN (SELECT id FROM repository WHERE original_service_type = ?)", gitServiceType).
  1695. And("original_author_id = ?", originalAuthorID).
  1696. Update(map[string]interface{}{
  1697. "poster_id": posterID,
  1698. "original_author": "",
  1699. "original_author_id": 0,
  1700. })
  1701. return err
  1702. }
  1703. // UpdateReactionsMigrationsByType updates all migrated repositories' reactions from gitServiceType to replace originalAuthorID to posterID
  1704. func UpdateReactionsMigrationsByType(gitServiceType structs.GitServiceType, originalAuthorID string, userID int64) error {
  1705. _, err := x.Table("reaction").
  1706. Where("original_author_id = ?", originalAuthorID).
  1707. And(migratedIssueCond(gitServiceType)).
  1708. Update(map[string]interface{}{
  1709. "user_id": userID,
  1710. "original_author": "",
  1711. "original_author_id": 0,
  1712. })
  1713. return err
  1714. }