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
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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965
  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. sess := x.NewSession()
  665. defer sess.Close()
  666. if err = sess.Begin(); err != nil {
  667. return err
  668. }
  669. if err = updateIssueCols(sess, issue, "ref"); err != nil {
  670. sess.Rollback()
  671. return fmt.Errorf("UpdateIssueCols: %v", err)
  672. }
  673. var opts = &CreateCommentOptions{
  674. Type: CommentTypeRef,
  675. Doer: doer,
  676. Repo: issue.Repo,
  677. Issue: issue,
  678. OldRef: oldRef,
  679. NewRef: newRef,
  680. }
  681. if _, err = createComment(sess, opts); err != nil {
  682. sess.Rollback()
  683. return err
  684. }
  685. return sess.Commit()
  686. }
  687. // GetTasks returns the amount of tasks in the issues content
  688. func (issue *Issue) GetTasks() int {
  689. return len(issueTasksPat.FindAllStringIndex(issue.Content, -1))
  690. }
  691. // GetTasksDone returns the amount of completed tasks in the issues content
  692. func (issue *Issue) GetTasksDone() int {
  693. return len(issueTasksDonePat.FindAllStringIndex(issue.Content, -1))
  694. }
  695. // GetLastEventTimestamp returns the last user visible event timestamp, either the creation of this issue or the close.
  696. func (issue *Issue) GetLastEventTimestamp() timeutil.TimeStamp {
  697. if issue.IsClosed {
  698. return issue.ClosedUnix
  699. }
  700. return issue.CreatedUnix
  701. }
  702. // GetLastEventLabel returns the localization label for the current issue.
  703. func (issue *Issue) GetLastEventLabel() string {
  704. if issue.IsClosed {
  705. if issue.IsPull && issue.PullRequest.HasMerged {
  706. return "repo.pulls.merged_by"
  707. }
  708. return "repo.issues.closed_by"
  709. }
  710. return "repo.issues.opened_by"
  711. }
  712. // GetLastComment return last comment for the current issue.
  713. func (issue *Issue) GetLastComment() (*Comment, error) {
  714. var c Comment
  715. exist, err := x.Where("type = ?", CommentTypeComment).
  716. And("issue_id = ?", issue.ID).Desc("id").Get(&c)
  717. if err != nil {
  718. return nil, err
  719. }
  720. if !exist {
  721. return nil, nil
  722. }
  723. return &c, nil
  724. }
  725. // GetLastEventLabelFake returns the localization label for the current issue without providing a link in the username.
  726. func (issue *Issue) GetLastEventLabelFake() string {
  727. if issue.IsClosed {
  728. if issue.IsPull && issue.PullRequest.HasMerged {
  729. return "repo.pulls.merged_by_fake"
  730. }
  731. return "repo.issues.closed_by_fake"
  732. }
  733. return "repo.issues.opened_by_fake"
  734. }
  735. // NewIssueOptions represents the options of a new issue.
  736. type NewIssueOptions struct {
  737. Repo *Repository
  738. Issue *Issue
  739. LabelIDs []int64
  740. Attachments []string // In UUID format.
  741. IsPull bool
  742. }
  743. func newIssue(e *xorm.Session, doer *User, opts NewIssueOptions) (err error) {
  744. opts.Issue.Title = strings.TrimSpace(opts.Issue.Title)
  745. if opts.Issue.MilestoneID > 0 {
  746. milestone, err := getMilestoneByRepoID(e, opts.Issue.RepoID, opts.Issue.MilestoneID)
  747. if err != nil && !IsErrMilestoneNotExist(err) {
  748. return fmt.Errorf("getMilestoneByID: %v", err)
  749. }
  750. // Assume milestone is invalid and drop silently.
  751. opts.Issue.MilestoneID = 0
  752. if milestone != nil {
  753. opts.Issue.MilestoneID = milestone.ID
  754. opts.Issue.Milestone = milestone
  755. }
  756. }
  757. // Milestone validation should happen before insert actual object.
  758. if _, err := e.SetExpr("`index`", "coalesce(MAX(`index`),0)+1").
  759. Where("repo_id=?", opts.Issue.RepoID).
  760. Insert(opts.Issue); err != nil {
  761. return ErrNewIssueInsert{err}
  762. }
  763. inserted, err := getIssueByID(e, opts.Issue.ID)
  764. if err != nil {
  765. return err
  766. }
  767. // Patch Index with the value calculated by the database
  768. opts.Issue.Index = inserted.Index
  769. if opts.Issue.MilestoneID > 0 {
  770. if _, err = e.Exec("UPDATE `milestone` SET num_issues=num_issues+1 WHERE id=?", opts.Issue.MilestoneID); err != nil {
  771. return err
  772. }
  773. var opts = &CreateCommentOptions{
  774. Type: CommentTypeMilestone,
  775. Doer: doer,
  776. Repo: opts.Repo,
  777. Issue: opts.Issue,
  778. OldMilestoneID: 0,
  779. MilestoneID: opts.Issue.MilestoneID,
  780. }
  781. if _, err = createComment(e, opts); err != nil {
  782. return err
  783. }
  784. }
  785. if opts.IsPull {
  786. _, err = e.Exec("UPDATE `repository` SET num_pulls = num_pulls + 1 WHERE id = ?", opts.Issue.RepoID)
  787. } else {
  788. _, err = e.Exec("UPDATE `repository` SET num_issues = num_issues + 1 WHERE id = ?", opts.Issue.RepoID)
  789. }
  790. if err != nil {
  791. return err
  792. }
  793. if len(opts.LabelIDs) > 0 {
  794. // During the session, SQLite3 driver cannot handle retrieve objects after update something.
  795. // So we have to get all needed labels first.
  796. labels := make([]*Label, 0, len(opts.LabelIDs))
  797. if err = e.In("id", opts.LabelIDs).Find(&labels); err != nil {
  798. return fmt.Errorf("find all labels [label_ids: %v]: %v", opts.LabelIDs, err)
  799. }
  800. if err = opts.Issue.loadPoster(e); err != nil {
  801. return err
  802. }
  803. for _, label := range labels {
  804. // Silently drop invalid labels.
  805. if label.RepoID != opts.Repo.ID && label.OrgID != opts.Repo.OwnerID {
  806. continue
  807. }
  808. if err = opts.Issue.addLabel(e, label, opts.Issue.Poster); err != nil {
  809. return fmt.Errorf("addLabel [id: %d]: %v", label.ID, err)
  810. }
  811. }
  812. }
  813. if err = newIssueUsers(e, opts.Repo, opts.Issue); err != nil {
  814. return err
  815. }
  816. if len(opts.Attachments) > 0 {
  817. attachments, err := getAttachmentsByUUIDs(e, opts.Attachments)
  818. if err != nil {
  819. return fmt.Errorf("getAttachmentsByUUIDs [uuids: %v]: %v", opts.Attachments, err)
  820. }
  821. for i := 0; i < len(attachments); i++ {
  822. attachments[i].IssueID = opts.Issue.ID
  823. if _, err = e.ID(attachments[i].ID).Update(attachments[i]); err != nil {
  824. return fmt.Errorf("update attachment [id: %d]: %v", attachments[i].ID, err)
  825. }
  826. }
  827. }
  828. if err = opts.Issue.loadAttributes(e); err != nil {
  829. return err
  830. }
  831. return opts.Issue.addCrossReferences(e, doer, false)
  832. }
  833. // NewIssue creates new issue with labels for repository.
  834. func NewIssue(repo *Repository, issue *Issue, labelIDs []int64, uuids []string) (err error) {
  835. // Retry several times in case INSERT fails due to duplicate key for (repo_id, index); see #7887
  836. i := 0
  837. for {
  838. if err = newIssueAttempt(repo, issue, labelIDs, uuids); err == nil {
  839. return nil
  840. }
  841. if !IsErrNewIssueInsert(err) {
  842. return err
  843. }
  844. if i++; i == issueMaxDupIndexAttempts {
  845. break
  846. }
  847. log.Error("NewIssue: error attempting to insert the new issue; will retry. Original error: %v", err)
  848. }
  849. return fmt.Errorf("NewIssue: too many errors attempting to insert the new issue. Last error was: %v", err)
  850. }
  851. func newIssueAttempt(repo *Repository, issue *Issue, labelIDs []int64, uuids []string) (err error) {
  852. sess := x.NewSession()
  853. defer sess.Close()
  854. if err = sess.Begin(); err != nil {
  855. return err
  856. }
  857. if err = newIssue(sess, issue.Poster, NewIssueOptions{
  858. Repo: repo,
  859. Issue: issue,
  860. LabelIDs: labelIDs,
  861. Attachments: uuids,
  862. }); err != nil {
  863. if IsErrUserDoesNotHaveAccessToRepo(err) || IsErrNewIssueInsert(err) {
  864. return err
  865. }
  866. return fmt.Errorf("newIssue: %v", err)
  867. }
  868. if err = sess.Commit(); err != nil {
  869. return fmt.Errorf("Commit: %v", err)
  870. }
  871. return nil
  872. }
  873. // GetIssueByIndex returns raw issue without loading attributes by index in a repository.
  874. func GetIssueByIndex(repoID, index int64) (*Issue, error) {
  875. issue := &Issue{
  876. RepoID: repoID,
  877. Index: index,
  878. }
  879. has, err := x.Get(issue)
  880. if err != nil {
  881. return nil, err
  882. } else if !has {
  883. return nil, ErrIssueNotExist{0, repoID, index}
  884. }
  885. return issue, nil
  886. }
  887. // GetIssueWithAttrsByIndex returns issue by index in a repository.
  888. func GetIssueWithAttrsByIndex(repoID, index int64) (*Issue, error) {
  889. issue, err := GetIssueByIndex(repoID, index)
  890. if err != nil {
  891. return nil, err
  892. }
  893. return issue, issue.LoadAttributes()
  894. }
  895. func getIssueByID(e Engine, id int64) (*Issue, error) {
  896. issue := new(Issue)
  897. has, err := e.ID(id).Get(issue)
  898. if err != nil {
  899. return nil, err
  900. } else if !has {
  901. return nil, ErrIssueNotExist{id, 0, 0}
  902. }
  903. return issue, nil
  904. }
  905. // GetIssueWithAttrsByID returns an issue with attributes by given ID.
  906. func GetIssueWithAttrsByID(id int64) (*Issue, error) {
  907. issue, err := getIssueByID(x, id)
  908. if err != nil {
  909. return nil, err
  910. }
  911. return issue, issue.loadAttributes(x)
  912. }
  913. // GetIssueByID returns an issue by given ID.
  914. func GetIssueByID(id int64) (*Issue, error) {
  915. return getIssueByID(x, id)
  916. }
  917. func getIssuesByIDs(e Engine, issueIDs []int64) ([]*Issue, error) {
  918. issues := make([]*Issue, 0, 10)
  919. return issues, e.In("id", issueIDs).Find(&issues)
  920. }
  921. func getIssueIDsByRepoID(e Engine, repoID int64) ([]int64, error) {
  922. var ids = make([]int64, 0, 10)
  923. err := e.Table("issue").Where("repo_id = ?", repoID).Find(&ids)
  924. return ids, err
  925. }
  926. // GetIssueIDsByRepoID returns all issue ids by repo id
  927. func GetIssueIDsByRepoID(repoID int64) ([]int64, error) {
  928. return getIssueIDsByRepoID(x, repoID)
  929. }
  930. // GetIssuesByIDs return issues with the given IDs.
  931. func GetIssuesByIDs(issueIDs []int64) ([]*Issue, error) {
  932. return getIssuesByIDs(x, issueIDs)
  933. }
  934. // IssuesOptions represents options of an issue.
  935. type IssuesOptions struct {
  936. ListOptions
  937. RepoIDs []int64 // include all repos if empty
  938. AssigneeID int64
  939. PosterID int64
  940. MentionedID int64
  941. MilestoneIDs []int64
  942. IsClosed util.OptionalBool
  943. IsPull util.OptionalBool
  944. LabelIDs []int64
  945. IncludedLabelNames []string
  946. ExcludedLabelNames []string
  947. SortType string
  948. IssueIDs []int64
  949. // prioritize issues from this repo
  950. PriorityRepoID int64
  951. }
  952. // sortIssuesSession sort an issues-related session based on the provided
  953. // sortType string
  954. func sortIssuesSession(sess *xorm.Session, sortType string, priorityRepoID int64) {
  955. switch sortType {
  956. case "oldest":
  957. sess.Asc("issue.created_unix")
  958. case "recentupdate":
  959. sess.Desc("issue.updated_unix")
  960. case "leastupdate":
  961. sess.Asc("issue.updated_unix")
  962. case "mostcomment":
  963. sess.Desc("issue.num_comments")
  964. case "leastcomment":
  965. sess.Asc("issue.num_comments")
  966. case "priority":
  967. sess.Desc("issue.priority")
  968. case "nearduedate":
  969. // 253370764800 is 01/01/9999 @ 12:00am (UTC)
  970. sess.OrderBy("CASE WHEN issue.deadline_unix = 0 THEN 253370764800 ELSE issue.deadline_unix END ASC")
  971. case "farduedate":
  972. sess.Desc("issue.deadline_unix")
  973. case "priorityrepo":
  974. sess.OrderBy("CASE WHEN issue.repo_id = " + strconv.FormatInt(priorityRepoID, 10) + " THEN 1 ELSE 2 END, issue.created_unix DESC")
  975. default:
  976. sess.Desc("issue.created_unix")
  977. }
  978. }
  979. func (opts *IssuesOptions) setupSession(sess *xorm.Session) {
  980. if opts.Page >= 0 && opts.PageSize > 0 {
  981. var start int
  982. if opts.Page == 0 {
  983. start = 0
  984. } else {
  985. start = (opts.Page - 1) * opts.PageSize
  986. }
  987. sess.Limit(opts.PageSize, start)
  988. }
  989. if len(opts.IssueIDs) > 0 {
  990. if len(opts.IssueIDs) > maxIssueIDs {
  991. opts.IssueIDs = opts.IssueIDs[:maxIssueIDs]
  992. }
  993. sess.In("issue.id", opts.IssueIDs)
  994. }
  995. if len(opts.RepoIDs) > 0 {
  996. // In case repository IDs are provided but actually no repository has issue.
  997. sess.In("issue.repo_id", opts.RepoIDs)
  998. }
  999. switch opts.IsClosed {
  1000. case util.OptionalBoolTrue:
  1001. sess.And("issue.is_closed=?", true)
  1002. case util.OptionalBoolFalse:
  1003. sess.And("issue.is_closed=?", false)
  1004. }
  1005. if opts.AssigneeID > 0 {
  1006. sess.Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  1007. And("issue_assignees.assignee_id = ?", opts.AssigneeID)
  1008. }
  1009. if opts.PosterID > 0 {
  1010. sess.And("issue.poster_id=?", opts.PosterID)
  1011. }
  1012. if opts.MentionedID > 0 {
  1013. sess.Join("INNER", "issue_user", "issue.id = issue_user.issue_id").
  1014. And("issue_user.is_mentioned = ?", true).
  1015. And("issue_user.uid = ?", opts.MentionedID)
  1016. }
  1017. if len(opts.MilestoneIDs) > 0 {
  1018. sess.In("issue.milestone_id", opts.MilestoneIDs)
  1019. }
  1020. switch opts.IsPull {
  1021. case util.OptionalBoolTrue:
  1022. sess.And("issue.is_pull=?", true)
  1023. case util.OptionalBoolFalse:
  1024. sess.And("issue.is_pull=?", false)
  1025. }
  1026. if opts.LabelIDs != nil {
  1027. for i, labelID := range opts.LabelIDs {
  1028. if labelID > 0 {
  1029. sess.Join("INNER", fmt.Sprintf("issue_label il%d", i),
  1030. fmt.Sprintf("issue.id = il%[1]d.issue_id AND il%[1]d.label_id = %[2]d", i, labelID))
  1031. } else {
  1032. sess.Where("issue.id not in (select issue_id from issue_label where label_id = ?)", -labelID)
  1033. }
  1034. }
  1035. }
  1036. if len(opts.IncludedLabelNames) > 0 {
  1037. sess.In("issue.id", BuildLabelNamesIssueIDsCondition(opts.IncludedLabelNames))
  1038. }
  1039. if len(opts.ExcludedLabelNames) > 0 {
  1040. sess.And(builder.NotIn("issue.id", BuildLabelNamesIssueIDsCondition(opts.ExcludedLabelNames)))
  1041. }
  1042. }
  1043. // CountIssuesByRepo map from repoID to number of issues matching the options
  1044. func CountIssuesByRepo(opts *IssuesOptions) (map[int64]int64, error) {
  1045. sess := x.NewSession()
  1046. defer sess.Close()
  1047. opts.setupSession(sess)
  1048. countsSlice := make([]*struct {
  1049. RepoID int64
  1050. Count int64
  1051. }, 0, 10)
  1052. if err := sess.GroupBy("issue.repo_id").
  1053. Select("issue.repo_id AS repo_id, COUNT(*) AS count").
  1054. Table("issue").
  1055. Find(&countsSlice); err != nil {
  1056. return nil, err
  1057. }
  1058. countMap := make(map[int64]int64, len(countsSlice))
  1059. for _, c := range countsSlice {
  1060. countMap[c.RepoID] = c.Count
  1061. }
  1062. return countMap, nil
  1063. }
  1064. // GetRepoIDsForIssuesOptions find all repo ids for the given options
  1065. func GetRepoIDsForIssuesOptions(opts *IssuesOptions, user *User) ([]int64, error) {
  1066. repoIDs := make([]int64, 0, 5)
  1067. sess := x.NewSession()
  1068. defer sess.Close()
  1069. opts.setupSession(sess)
  1070. accessCond := accessibleRepositoryCondition(user)
  1071. if err := sess.Where(accessCond).
  1072. Join("INNER", "repository", "`issue`.repo_id = `repository`.id").
  1073. Distinct("issue.repo_id").
  1074. Table("issue").
  1075. Find(&repoIDs); err != nil {
  1076. return nil, err
  1077. }
  1078. return repoIDs, nil
  1079. }
  1080. // Issues returns a list of issues by given conditions.
  1081. func Issues(opts *IssuesOptions) ([]*Issue, error) {
  1082. sess := x.NewSession()
  1083. defer sess.Close()
  1084. opts.setupSession(sess)
  1085. sortIssuesSession(sess, opts.SortType, opts.PriorityRepoID)
  1086. issues := make([]*Issue, 0, setting.UI.IssuePagingNum)
  1087. if err := sess.Find(&issues); err != nil {
  1088. return nil, fmt.Errorf("Find: %v", err)
  1089. }
  1090. sess.Close()
  1091. if err := IssueList(issues).LoadAttributes(); err != nil {
  1092. return nil, fmt.Errorf("LoadAttributes: %v", err)
  1093. }
  1094. return issues, nil
  1095. }
  1096. // GetParticipantsIDsByIssueID returns the IDs of all users who participated in comments of an issue,
  1097. // but skips joining with `user` for performance reasons.
  1098. // User permissions must be verified elsewhere if required.
  1099. func GetParticipantsIDsByIssueID(issueID int64) ([]int64, error) {
  1100. userIDs := make([]int64, 0, 5)
  1101. return userIDs, x.Table("comment").
  1102. Cols("poster_id").
  1103. Where("issue_id = ?", issueID).
  1104. And("type in (?,?,?)", CommentTypeComment, CommentTypeCode, CommentTypeReview).
  1105. Distinct("poster_id").
  1106. Find(&userIDs)
  1107. }
  1108. // IsUserParticipantsOfIssue return true if user is participants of an issue
  1109. func IsUserParticipantsOfIssue(user *User, issue *Issue) bool {
  1110. userIDs, err := issue.getParticipantIDsByIssue(x)
  1111. if err != nil {
  1112. log.Error(err.Error())
  1113. return false
  1114. }
  1115. return util.IsInt64InSlice(user.ID, userIDs)
  1116. }
  1117. // UpdateIssueMentions updates issue-user relations for mentioned users.
  1118. func UpdateIssueMentions(ctx DBContext, issueID int64, mentions []*User) error {
  1119. if len(mentions) == 0 {
  1120. return nil
  1121. }
  1122. ids := make([]int64, len(mentions))
  1123. for i, u := range mentions {
  1124. ids[i] = u.ID
  1125. }
  1126. if err := UpdateIssueUsersByMentions(ctx, issueID, ids); err != nil {
  1127. return fmt.Errorf("UpdateIssueUsersByMentions: %v", err)
  1128. }
  1129. return nil
  1130. }
  1131. // IssueStats represents issue statistic information.
  1132. type IssueStats struct {
  1133. OpenCount, ClosedCount int64
  1134. YourRepositoriesCount int64
  1135. AssignCount int64
  1136. CreateCount int64
  1137. MentionCount int64
  1138. }
  1139. // Filter modes.
  1140. const (
  1141. FilterModeAll = iota
  1142. FilterModeAssign
  1143. FilterModeCreate
  1144. FilterModeMention
  1145. )
  1146. func parseCountResult(results []map[string][]byte) int64 {
  1147. if len(results) == 0 {
  1148. return 0
  1149. }
  1150. for _, result := range results[0] {
  1151. return com.StrTo(string(result)).MustInt64()
  1152. }
  1153. return 0
  1154. }
  1155. // IssueStatsOptions contains parameters accepted by GetIssueStats.
  1156. type IssueStatsOptions struct {
  1157. RepoID int64
  1158. Labels string
  1159. MilestoneID int64
  1160. AssigneeID int64
  1161. MentionedID int64
  1162. PosterID int64
  1163. IsPull util.OptionalBool
  1164. IssueIDs []int64
  1165. }
  1166. // GetIssueStats returns issue statistic information by given conditions.
  1167. func GetIssueStats(opts *IssueStatsOptions) (*IssueStats, error) {
  1168. if len(opts.IssueIDs) <= maxQueryParameters {
  1169. return getIssueStatsChunk(opts, opts.IssueIDs)
  1170. }
  1171. // If too long a list of IDs is provided, we get the statistics in
  1172. // smaller chunks and get accumulates. Note: this could potentially
  1173. // get us invalid results. The alternative is to insert the list of
  1174. // ids in a temporary table and join from them.
  1175. accum := &IssueStats{}
  1176. for i := 0; i < len(opts.IssueIDs); {
  1177. chunk := i + maxQueryParameters
  1178. if chunk > len(opts.IssueIDs) {
  1179. chunk = len(opts.IssueIDs)
  1180. }
  1181. stats, err := getIssueStatsChunk(opts, opts.IssueIDs[i:chunk])
  1182. if err != nil {
  1183. return nil, err
  1184. }
  1185. accum.OpenCount += stats.OpenCount
  1186. accum.ClosedCount += stats.ClosedCount
  1187. accum.YourRepositoriesCount += stats.YourRepositoriesCount
  1188. accum.AssignCount += stats.AssignCount
  1189. accum.CreateCount += stats.CreateCount
  1190. accum.OpenCount += stats.MentionCount
  1191. i = chunk
  1192. }
  1193. return accum, nil
  1194. }
  1195. func GetPullCountByUserAndRepoId(repoId int64, userId int64) int64 {
  1196. issue := new(Issue)
  1197. total, err := x.Where("is_pull=true and repo_id=? and poster_id=?", repoId, userId).Count(issue)
  1198. if err != nil {
  1199. return 0
  1200. }
  1201. return total
  1202. }
  1203. func getIssueStatsChunk(opts *IssueStatsOptions, issueIDs []int64) (*IssueStats, error) {
  1204. stats := &IssueStats{}
  1205. countSession := func(opts *IssueStatsOptions) *xorm.Session {
  1206. sess := x.
  1207. Where("issue.repo_id = ?", opts.RepoID)
  1208. if len(opts.IssueIDs) > 0 {
  1209. if len(opts.IssueIDs) > maxIssueIDs {
  1210. opts.IssueIDs = opts.IssueIDs[:maxIssueIDs]
  1211. }
  1212. sess.In("issue.id", opts.IssueIDs)
  1213. }
  1214. if len(opts.Labels) > 0 && opts.Labels != "0" {
  1215. labelIDs, err := base.StringsToInt64s(strings.Split(opts.Labels, ","))
  1216. if err != nil {
  1217. log.Warn("Malformed Labels argument: %s", opts.Labels)
  1218. } else {
  1219. for i, labelID := range labelIDs {
  1220. if labelID > 0 {
  1221. sess.Join("INNER", fmt.Sprintf("issue_label il%d", i),
  1222. fmt.Sprintf("issue.id = il%[1]d.issue_id AND il%[1]d.label_id = %[2]d", i, labelID))
  1223. } else {
  1224. sess.Where("issue.id NOT IN (SELECT issue_id FROM issue_label WHERE label_id = ?)", -labelID)
  1225. }
  1226. }
  1227. }
  1228. }
  1229. if opts.MilestoneID > 0 {
  1230. sess.And("issue.milestone_id = ?", opts.MilestoneID)
  1231. } else if opts.MilestoneID == -1 { //only search for issues do not have milestone
  1232. sess.And("issue.milestone_id = ?", 0)
  1233. }
  1234. if opts.AssigneeID > 0 {
  1235. sess.Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  1236. And("issue_assignees.assignee_id = ?", opts.AssigneeID)
  1237. }
  1238. if opts.PosterID > 0 {
  1239. sess.And("issue.poster_id = ?", opts.PosterID)
  1240. }
  1241. if opts.MentionedID > 0 {
  1242. sess.Join("INNER", "issue_user", "issue.id = issue_user.issue_id").
  1243. And("issue_user.uid = ?", opts.MentionedID).
  1244. And("issue_user.is_mentioned = ?", true)
  1245. }
  1246. switch opts.IsPull {
  1247. case util.OptionalBoolTrue:
  1248. sess.And("issue.is_pull=?", true)
  1249. case util.OptionalBoolFalse:
  1250. sess.And("issue.is_pull=?", false)
  1251. }
  1252. return sess
  1253. }
  1254. var err error
  1255. stats.OpenCount, err = countSession(opts).
  1256. And("issue.is_closed = ?", false).
  1257. Count(new(Issue))
  1258. if err != nil {
  1259. return stats, err
  1260. }
  1261. stats.ClosedCount, err = countSession(opts).
  1262. And("issue.is_closed = ?", true).
  1263. Count(new(Issue))
  1264. return stats, err
  1265. }
  1266. // UserIssueStatsOptions contains parameters accepted by GetUserIssueStats.
  1267. type UserIssueStatsOptions struct {
  1268. UserID int64
  1269. RepoIDs []int64
  1270. UserRepoIDs []int64
  1271. FilterMode int
  1272. IsPull bool
  1273. IsClosed bool
  1274. IssueIDs []int64
  1275. }
  1276. // GetUserIssueStats returns issue statistic information for dashboard by given conditions.
  1277. func GetUserIssueStats(opts UserIssueStatsOptions) (*IssueStats, error) {
  1278. var err error
  1279. stats := &IssueStats{}
  1280. cond := builder.NewCond()
  1281. cond = cond.And(builder.Eq{"issue.is_pull": opts.IsPull})
  1282. if len(opts.RepoIDs) > 0 {
  1283. cond = cond.And(builder.In("issue.repo_id", opts.RepoIDs))
  1284. }
  1285. if len(opts.IssueIDs) > 0 {
  1286. if len(opts.IssueIDs) > maxIssueIDs {
  1287. opts.IssueIDs = opts.IssueIDs[:maxIssueIDs]
  1288. }
  1289. cond = cond.And(builder.In("issue.id", opts.IssueIDs))
  1290. }
  1291. switch opts.FilterMode {
  1292. case FilterModeAll:
  1293. stats.OpenCount, err = x.Where(cond).And("issue.is_closed = ?", false).
  1294. And(builder.In("issue.repo_id", opts.UserRepoIDs)).
  1295. Count(new(Issue))
  1296. if err != nil {
  1297. return nil, err
  1298. }
  1299. stats.ClosedCount, err = x.Where(cond).And("issue.is_closed = ?", true).
  1300. And(builder.In("issue.repo_id", opts.UserRepoIDs)).
  1301. Count(new(Issue))
  1302. if err != nil {
  1303. return nil, err
  1304. }
  1305. case FilterModeAssign:
  1306. stats.OpenCount, err = x.Where(cond).And("issue.is_closed = ?", false).
  1307. Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  1308. And("issue_assignees.assignee_id = ?", opts.UserID).
  1309. Count(new(Issue))
  1310. if err != nil {
  1311. return nil, err
  1312. }
  1313. stats.ClosedCount, err = x.Where(cond).And("issue.is_closed = ?", true).
  1314. Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  1315. And("issue_assignees.assignee_id = ?", opts.UserID).
  1316. Count(new(Issue))
  1317. if err != nil {
  1318. return nil, err
  1319. }
  1320. case FilterModeCreate:
  1321. stats.OpenCount, err = x.Where(cond).And("issue.is_closed = ?", false).
  1322. And("issue.poster_id = ?", opts.UserID).
  1323. Count(new(Issue))
  1324. if err != nil {
  1325. return nil, err
  1326. }
  1327. stats.ClosedCount, err = x.Where(cond).And("issue.is_closed = ?", true).
  1328. And("issue.poster_id = ?", opts.UserID).
  1329. Count(new(Issue))
  1330. if err != nil {
  1331. return nil, err
  1332. }
  1333. case FilterModeMention:
  1334. stats.OpenCount, err = x.Where(cond).And("issue.is_closed = ?", false).
  1335. Join("INNER", "issue_user", "issue.id = issue_user.issue_id and issue_user.is_mentioned = ?", true).
  1336. And("issue_user.uid = ?", opts.UserID).
  1337. Count(new(Issue))
  1338. if err != nil {
  1339. return nil, err
  1340. }
  1341. stats.ClosedCount, err = x.Where(cond).And("issue.is_closed = ?", true).
  1342. Join("INNER", "issue_user", "issue.id = issue_user.issue_id and issue_user.is_mentioned = ?", true).
  1343. And("issue_user.uid = ?", opts.UserID).
  1344. Count(new(Issue))
  1345. if err != nil {
  1346. return nil, err
  1347. }
  1348. }
  1349. cond = cond.And(builder.Eq{"issue.is_closed": opts.IsClosed})
  1350. stats.AssignCount, err = x.Where(cond).
  1351. Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  1352. And("issue_assignees.assignee_id = ?", opts.UserID).
  1353. Count(new(Issue))
  1354. if err != nil {
  1355. return nil, err
  1356. }
  1357. stats.CreateCount, err = x.Where(cond).
  1358. And("poster_id = ?", opts.UserID).
  1359. Count(new(Issue))
  1360. if err != nil {
  1361. return nil, err
  1362. }
  1363. stats.MentionCount, err = x.Where(cond).
  1364. Join("INNER", "issue_user", "issue.id = issue_user.issue_id and issue_user.is_mentioned = ?", true).
  1365. And("issue_user.uid = ?", opts.UserID).
  1366. Count(new(Issue))
  1367. if err != nil {
  1368. return nil, err
  1369. }
  1370. stats.YourRepositoriesCount, err = x.Where(cond).
  1371. And(builder.In("issue.repo_id", opts.UserRepoIDs)).
  1372. Count(new(Issue))
  1373. if err != nil {
  1374. return nil, err
  1375. }
  1376. return stats, nil
  1377. }
  1378. // GetRepoIssueStats returns number of open and closed repository issues by given filter mode.
  1379. func GetRepoIssueStats(repoID, uid int64, filterMode int, isPull bool) (numOpen int64, numClosed int64) {
  1380. countSession := func(isClosed, isPull bool, repoID int64) *xorm.Session {
  1381. sess := x.
  1382. Where("is_closed = ?", isClosed).
  1383. And("is_pull = ?", isPull).
  1384. And("repo_id = ?", repoID)
  1385. return sess
  1386. }
  1387. openCountSession := countSession(false, isPull, repoID)
  1388. closedCountSession := countSession(true, isPull, repoID)
  1389. switch filterMode {
  1390. case FilterModeAssign:
  1391. openCountSession.Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  1392. And("issue_assignees.assignee_id = ?", uid)
  1393. closedCountSession.Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  1394. And("issue_assignees.assignee_id = ?", uid)
  1395. case FilterModeCreate:
  1396. openCountSession.And("poster_id = ?", uid)
  1397. closedCountSession.And("poster_id = ?", uid)
  1398. }
  1399. openResult, _ := openCountSession.Count(new(Issue))
  1400. closedResult, _ := closedCountSession.Count(new(Issue))
  1401. return openResult, closedResult
  1402. }
  1403. // SearchIssueIDsByKeyword search issues on database
  1404. func SearchIssueIDsByKeyword(kw string, repoIDs []int64, limit, start int) (int64, []int64, error) {
  1405. var repoCond = builder.In("repo_id", repoIDs)
  1406. var subQuery = builder.Select("id").From("issue").Where(repoCond)
  1407. var cond = builder.And(
  1408. repoCond,
  1409. builder.Or(
  1410. builder.Like{"name", kw},
  1411. builder.Like{"content", kw},
  1412. builder.In("id", builder.Select("issue_id").
  1413. From("comment").
  1414. Where(builder.And(
  1415. builder.Eq{"type": CommentTypeComment},
  1416. builder.In("issue_id", subQuery),
  1417. builder.Like{"content", kw},
  1418. )),
  1419. ),
  1420. ),
  1421. )
  1422. var ids = make([]int64, 0, limit)
  1423. err := x.Distinct("id").Table("issue").Where(cond).Limit(limit, start).Find(&ids)
  1424. if err != nil {
  1425. return 0, nil, err
  1426. }
  1427. total, err := x.Distinct("id").Table("issue").Where(cond).Count()
  1428. if err != nil {
  1429. return 0, nil, err
  1430. }
  1431. return total, ids, nil
  1432. }
  1433. // UpdateIssueByAPI updates all allowed fields of given issue.
  1434. // If the issue status is changed a statusChangeComment is returned
  1435. // similarly if the title is changed the titleChanged bool is set to true
  1436. func UpdateIssueByAPI(issue *Issue, doer *User) (statusChangeComment *Comment, titleChanged bool, err error) {
  1437. sess := x.NewSession()
  1438. defer sess.Close()
  1439. if err := sess.Begin(); err != nil {
  1440. return nil, false, err
  1441. }
  1442. if err := issue.loadRepo(sess); err != nil {
  1443. return nil, false, fmt.Errorf("loadRepo: %v", err)
  1444. }
  1445. // Reload the issue
  1446. currentIssue, err := getIssueByID(sess, issue.ID)
  1447. if err != nil {
  1448. return nil, false, err
  1449. }
  1450. if _, err := sess.ID(issue.ID).Cols(
  1451. "name", "content", "milestone_id", "priority",
  1452. "deadline_unix", "updated_unix", "is_locked").
  1453. Update(issue); err != nil {
  1454. return nil, false, err
  1455. }
  1456. titleChanged = currentIssue.Title != issue.Title
  1457. if titleChanged {
  1458. var opts = &CreateCommentOptions{
  1459. Type: CommentTypeChangeTitle,
  1460. Doer: doer,
  1461. Repo: issue.Repo,
  1462. Issue: issue,
  1463. OldTitle: currentIssue.Title,
  1464. NewTitle: issue.Title,
  1465. }
  1466. _, err := createComment(sess, opts)
  1467. if err != nil {
  1468. return nil, false, fmt.Errorf("createComment: %v", err)
  1469. }
  1470. }
  1471. if currentIssue.IsClosed != issue.IsClosed {
  1472. statusChangeComment, err = issue.doChangeStatus(sess, doer, false)
  1473. if err != nil {
  1474. return nil, false, err
  1475. }
  1476. }
  1477. if err := issue.addCrossReferences(sess, doer, true); err != nil {
  1478. return nil, false, err
  1479. }
  1480. return statusChangeComment, titleChanged, sess.Commit()
  1481. }
  1482. // UpdateIssueDeadline updates an issue deadline and adds comments. Setting a deadline to 0 means deleting it.
  1483. func UpdateIssueDeadline(issue *Issue, deadlineUnix timeutil.TimeStamp, doer *User) (err error) {
  1484. // if the deadline hasn't changed do nothing
  1485. if issue.DeadlineUnix == deadlineUnix {
  1486. return nil
  1487. }
  1488. sess := x.NewSession()
  1489. defer sess.Close()
  1490. if err := sess.Begin(); err != nil {
  1491. return err
  1492. }
  1493. // Update the deadline
  1494. if err = updateIssueCols(sess, &Issue{ID: issue.ID, DeadlineUnix: deadlineUnix}, "deadline_unix"); err != nil {
  1495. return err
  1496. }
  1497. // Make the comment
  1498. if _, err = createDeadlineComment(sess, doer, issue, deadlineUnix); err != nil {
  1499. return fmt.Errorf("createRemovedDueDateComment: %v", err)
  1500. }
  1501. return sess.Commit()
  1502. }
  1503. // DependencyInfo represents high level information about an issue which is a dependency of another issue.
  1504. type DependencyInfo struct {
  1505. Issue `xorm:"extends"`
  1506. Repository `xorm:"extends"`
  1507. }
  1508. // getParticipantIDsByIssue returns all userIDs who are participated in comments of an issue and issue author
  1509. func (issue *Issue) getParticipantIDsByIssue(e Engine) ([]int64, error) {
  1510. if issue == nil {
  1511. return nil, nil
  1512. }
  1513. userIDs := make([]int64, 0, 5)
  1514. if err := e.Table("comment").Cols("poster_id").
  1515. Where("`comment`.issue_id = ?", issue.ID).
  1516. And("`comment`.type in (?,?,?)", CommentTypeComment, CommentTypeCode, CommentTypeReview).
  1517. And("`user`.is_active = ?", true).
  1518. And("`user`.prohibit_login = ?", false).
  1519. Join("INNER", "`user`", "`user`.id = `comment`.poster_id").
  1520. Distinct("poster_id").
  1521. Find(&userIDs); err != nil {
  1522. return nil, fmt.Errorf("get poster IDs: %v", err)
  1523. }
  1524. if !util.IsInt64InSlice(issue.PosterID, userIDs) {
  1525. return append(userIDs, issue.PosterID), nil
  1526. }
  1527. return userIDs, nil
  1528. }
  1529. // Get Blocked By Dependencies, aka all issues this issue is blocked by.
  1530. func (issue *Issue) getBlockedByDependencies(e Engine) (issueDeps []*DependencyInfo, err error) {
  1531. return issueDeps, e.
  1532. Table("issue").
  1533. Join("INNER", "repository", "repository.id = issue.repo_id").
  1534. Join("INNER", "issue_dependency", "issue_dependency.dependency_id = issue.id").
  1535. Where("issue_id = ?", issue.ID).
  1536. //sort by repo id then created date, with the issues of the same repo at the beginning of the list
  1537. OrderBy("CASE WHEN issue.repo_id = " + strconv.FormatInt(issue.RepoID, 10) + " THEN 0 ELSE issue.repo_id END, issue.created_unix DESC").
  1538. Find(&issueDeps)
  1539. }
  1540. // Get Blocking Dependencies, aka all issues this issue blocks.
  1541. func (issue *Issue) getBlockingDependencies(e Engine) (issueDeps []*DependencyInfo, err error) {
  1542. return issueDeps, e.
  1543. Table("issue").
  1544. Join("INNER", "repository", "repository.id = issue.repo_id").
  1545. Join("INNER", "issue_dependency", "issue_dependency.issue_id = issue.id").
  1546. Where("dependency_id = ?", issue.ID).
  1547. //sort by repo id then created date, with the issues of the same repo at the beginning of the list
  1548. OrderBy("CASE WHEN issue.repo_id = " + strconv.FormatInt(issue.RepoID, 10) + " THEN 0 ELSE issue.repo_id END, issue.created_unix DESC").
  1549. Find(&issueDeps)
  1550. }
  1551. // BlockedByDependencies finds all Dependencies an issue is blocked by
  1552. func (issue *Issue) BlockedByDependencies() ([]*DependencyInfo, error) {
  1553. return issue.getBlockedByDependencies(x)
  1554. }
  1555. // BlockingDependencies returns all blocking dependencies, aka all other issues a given issue blocks
  1556. func (issue *Issue) BlockingDependencies() ([]*DependencyInfo, error) {
  1557. return issue.getBlockingDependencies(x)
  1558. }
  1559. func (issue *Issue) updateClosedNum(e Engine) (err error) {
  1560. if issue.IsPull {
  1561. _, err = e.Exec("UPDATE `repository` SET num_closed_pulls=(SELECT count(*) FROM issue WHERE repo_id=? AND is_pull=? AND is_closed=?) WHERE id=?",
  1562. issue.RepoID,
  1563. true,
  1564. true,
  1565. issue.RepoID,
  1566. )
  1567. } else {
  1568. _, err = e.Exec("UPDATE `repository` SET num_closed_issues=(SELECT count(*) FROM issue WHERE repo_id=? AND is_pull=? AND is_closed=?) WHERE id=?",
  1569. issue.RepoID,
  1570. false,
  1571. true,
  1572. issue.RepoID,
  1573. )
  1574. }
  1575. return
  1576. }
  1577. // ResolveMentionsByVisibility returns the users mentioned in an issue, removing those that
  1578. // don't have access to reading it. Teams are expanded into their users, but organizations are ignored.
  1579. func (issue *Issue) ResolveMentionsByVisibility(ctx DBContext, doer *User, mentions []string) (users []*User, err error) {
  1580. if len(mentions) == 0 {
  1581. return
  1582. }
  1583. if err = issue.loadRepo(ctx.e); err != nil {
  1584. return
  1585. }
  1586. resolved := make(map[string]bool, 20)
  1587. names := make([]string, 0, 20)
  1588. resolved[doer.LowerName] = true
  1589. for _, name := range mentions {
  1590. name := strings.ToLower(name)
  1591. if _, ok := resolved[name]; ok {
  1592. continue
  1593. }
  1594. resolved[name] = false
  1595. names = append(names, name)
  1596. }
  1597. if err := issue.Repo.getOwner(ctx.e); err != nil {
  1598. return nil, err
  1599. }
  1600. if issue.Repo.Owner.IsOrganization() {
  1601. // Since there can be users with names that match the name of a team,
  1602. // if the team exists and can read the issue, the team takes precedence.
  1603. teams := make([]*Team, 0, len(names))
  1604. if err := ctx.e.
  1605. Join("INNER", "team_repo", "team_repo.team_id = team.id").
  1606. Where("team_repo.repo_id=?", issue.Repo.ID).
  1607. In("team.lower_name", names).
  1608. Find(&teams); err != nil {
  1609. return nil, fmt.Errorf("find mentioned teams: %v", err)
  1610. }
  1611. if len(teams) != 0 {
  1612. checked := make([]int64, 0, len(teams))
  1613. unittype := UnitTypeIssues
  1614. if issue.IsPull {
  1615. unittype = UnitTypePullRequests
  1616. }
  1617. for _, team := range teams {
  1618. if team.Authorize >= AccessModeOwner {
  1619. checked = append(checked, team.ID)
  1620. resolved[team.LowerName] = true
  1621. continue
  1622. }
  1623. has, err := ctx.e.Get(&TeamUnit{OrgID: issue.Repo.Owner.ID, TeamID: team.ID, Type: unittype})
  1624. if err != nil {
  1625. return nil, fmt.Errorf("get team units (%d): %v", team.ID, err)
  1626. }
  1627. if has {
  1628. checked = append(checked, team.ID)
  1629. resolved[team.LowerName] = true
  1630. }
  1631. }
  1632. if len(checked) != 0 {
  1633. teamusers := make([]*User, 0, 20)
  1634. if err := ctx.e.
  1635. Join("INNER", "team_user", "team_user.uid = `user`.id").
  1636. In("`team_user`.team_id", checked).
  1637. And("`user`.is_active = ?", true).
  1638. And("`user`.prohibit_login = ?", false).
  1639. Find(&teamusers); err != nil {
  1640. return nil, fmt.Errorf("get teams users: %v", err)
  1641. }
  1642. if len(teamusers) > 0 {
  1643. users = make([]*User, 0, len(teamusers))
  1644. for _, user := range teamusers {
  1645. if already, ok := resolved[user.LowerName]; !ok || !already {
  1646. users = append(users, user)
  1647. resolved[user.LowerName] = true
  1648. }
  1649. }
  1650. }
  1651. }
  1652. }
  1653. // Remove names already in the list to avoid querying the database if pending names remain
  1654. names = make([]string, 0, len(resolved))
  1655. for name, already := range resolved {
  1656. if !already {
  1657. names = append(names, name)
  1658. }
  1659. }
  1660. if len(names) == 0 {
  1661. return
  1662. }
  1663. }
  1664. unchecked := make([]*User, 0, len(names))
  1665. if err := ctx.e.
  1666. Where("`user`.is_active = ?", true).
  1667. And("`user`.prohibit_login = ?", false).
  1668. In("`user`.lower_name", names).
  1669. Find(&unchecked); err != nil {
  1670. return nil, fmt.Errorf("find mentioned users: %v", err)
  1671. }
  1672. for _, user := range unchecked {
  1673. if already := resolved[user.LowerName]; already || user.IsOrganization() {
  1674. continue
  1675. }
  1676. // Normal users must have read access to the referencing issue
  1677. perm, err := getUserRepoPermission(ctx.e, issue.Repo, user)
  1678. if err != nil {
  1679. return nil, fmt.Errorf("getUserRepoPermission [%d]: %v", user.ID, err)
  1680. }
  1681. if !perm.CanReadIssuesOrPulls(issue.IsPull) {
  1682. continue
  1683. }
  1684. users = append(users, user)
  1685. }
  1686. return
  1687. }
  1688. // UpdateIssuesMigrationsByType updates all migrated repositories' issues from gitServiceType to replace originalAuthorID to posterID
  1689. func UpdateIssuesMigrationsByType(gitServiceType structs.GitServiceType, originalAuthorID string, posterID int64) error {
  1690. _, err := x.Table("issue").
  1691. Where("repo_id IN (SELECT id FROM repository WHERE original_service_type = ?)", gitServiceType).
  1692. And("original_author_id = ?", originalAuthorID).
  1693. Update(map[string]interface{}{
  1694. "poster_id": posterID,
  1695. "original_author": "",
  1696. "original_author_id": 0,
  1697. })
  1698. return err
  1699. }
  1700. // UpdateReactionsMigrationsByType updates all migrated repositories' reactions from gitServiceType to replace originalAuthorID to posterID
  1701. func UpdateReactionsMigrationsByType(gitServiceType structs.GitServiceType, originalAuthorID string, userID int64) error {
  1702. _, err := x.Table("reaction").
  1703. Where("original_author_id = ?", originalAuthorID).
  1704. And(migratedIssueCond(gitServiceType)).
  1705. Update(map[string]interface{}{
  1706. "user_id": userID,
  1707. "original_author": "",
  1708. "original_author_id": 0,
  1709. })
  1710. return err
  1711. }