You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1876 lines
51 KiB

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