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.

2022 lines
55 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
4 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
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
8 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 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
7 years ago
7 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
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
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
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
4 years ago
10 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()
4 years ago
issue search on my related repositories (#9758) * adding search capability to user's issues dashboard * global issue search * placement of search bar on issues dashboard * fixed some bugs in the issue dashboard search * added unit test because IssueIDs option was added to UserIssueStatsOptions * some renaming of fields in the issue dashboard code to be more clear; also trying to fix issue of searching the right repos based on the filter * added unit test fro GetRepoIDsForIssuesOptions; fixed search lost on pagination; using shown issue status for open/close count; removed some debugging * fix issue with all count showing incorrectly * removed todo comment left in by mistake * typo pulling wrong count * fxied all count being off when selecting repositories * setting the opts.IsClosed after pulling repos to search, this is done so that the list of repo ids to serach for the keyword is not limited, we need to get all the issue ids for the shown issue stats * added "accessibleRepositoryCondition" check on the query to pull the repo ids to search for issues, this is an added protection to ensure we don't search repos the user does not have access to * added code so that in the issues search, we won't use an in clause of issues ids that goes over 1000 * fixed unit test * using 950 as the limit for issue search, removed unneeded group by in GetRepoIDsForIssuesOptions, showing search on pulls dashboard page too (not just issues) Co-authored-by: guillep2k <18600385+guillep2k@users.noreply.github.com>
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()
4 years ago
issue search on my related repositories (#9758) * adding search capability to user's issues dashboard * global issue search * placement of search bar on issues dashboard * fixed some bugs in the issue dashboard search * added unit test because IssueIDs option was added to UserIssueStatsOptions * some renaming of fields in the issue dashboard code to be more clear; also trying to fix issue of searching the right repos based on the filter * added unit test fro GetRepoIDsForIssuesOptions; fixed search lost on pagination; using shown issue status for open/close count; removed some debugging * fix issue with all count showing incorrectly * removed todo comment left in by mistake * typo pulling wrong count * fxied all count being off when selecting repositories * setting the opts.IsClosed after pulling repos to search, this is done so that the list of repo ids to serach for the keyword is not limited, we need to get all the issue ids for the shown issue stats * added "accessibleRepositoryCondition" check on the query to pull the repo ids to search for issues, this is an added protection to ensure we don't search repos the user does not have access to * added code so that in the issues search, we won't use an in clause of issues ids that goes over 1000 * fixed unit test * using 950 as the limit for issue search, removed unneeded group by in GetRepoIDsForIssuesOptions, showing search on pulls dashboard page too (not just issues) Co-authored-by: guillep2k <18600385+guillep2k@users.noreply.github.com>
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()
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()
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()
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()
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
4 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
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
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
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
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
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
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
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
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
4 years ago
Add a storage layer for attachments (#11387) * Add a storage layer for attachments * Fix some bug * fix test * Fix copyright head and lint * Fix bug * Add setting for minio and flags for migrate-storage * Add documents * fix lint * Add test for minio store type on attachments * fix test * fix test * Apply suggestions from code review Co-authored-by: guillep2k <18600385+guillep2k@users.noreply.github.com> * Add warning when storage migrated successfully * Fix drone * fix test * rebase * Fix test * display the error on console * Move minio test to amd64 since minio docker don't support arm64 * refactor the codes * add trace * Fix test * remove log on xorm * Fi download bug * Add a storage layer for attachments * Add setting for minio and flags for migrate-storage * fix lint * Add test for minio store type on attachments * Apply suggestions from code review Co-authored-by: guillep2k <18600385+guillep2k@users.noreply.github.com> * Fix drone * fix test * Fix test * display the error on console * Move minio test to amd64 since minio docker don't support arm64 * refactor the codes * add trace * Fix test * Add URL function to serve attachments directly from S3/Minio * Add ability to enable/disable redirection in attachment configuration * Fix typo * Add a storage layer for attachments * Add setting for minio and flags for migrate-storage * fix lint * Add test for minio store type on attachments * Apply suggestions from code review Co-authored-by: guillep2k <18600385+guillep2k@users.noreply.github.com> * Fix drone * fix test * Fix test * display the error on console * Move minio test to amd64 since minio docker don't support arm64 * don't change unrelated files * Fix lint * Fix build * update go.mod and go.sum * Use github.com/minio/minio-go/v6 * Remove unused function * Upgrade minio to v7 and some other improvements * fix lint * Fix go mod Co-authored-by: guillep2k <18600385+guillep2k@users.noreply.github.com> Co-authored-by: Tyler <tystuyfzand@gmail.com>
3 years ago
Add a storage layer for attachments (#11387) * Add a storage layer for attachments * Fix some bug * fix test * Fix copyright head and lint * Fix bug * Add setting for minio and flags for migrate-storage * Add documents * fix lint * Add test for minio store type on attachments * fix test * fix test * Apply suggestions from code review Co-authored-by: guillep2k <18600385+guillep2k@users.noreply.github.com> * Add warning when storage migrated successfully * Fix drone * fix test * rebase * Fix test * display the error on console * Move minio test to amd64 since minio docker don't support arm64 * refactor the codes * add trace * Fix test * remove log on xorm * Fi download bug * Add a storage layer for attachments * Add setting for minio and flags for migrate-storage * fix lint * Add test for minio store type on attachments * Apply suggestions from code review Co-authored-by: guillep2k <18600385+guillep2k@users.noreply.github.com> * Fix drone * fix test * Fix test * display the error on console * Move minio test to amd64 since minio docker don't support arm64 * refactor the codes * add trace * Fix test * Add URL function to serve attachments directly from S3/Minio * Add ability to enable/disable redirection in attachment configuration * Fix typo * Add a storage layer for attachments * Add setting for minio and flags for migrate-storage * fix lint * Add test for minio store type on attachments * Apply suggestions from code review Co-authored-by: guillep2k <18600385+guillep2k@users.noreply.github.com> * Fix drone * fix test * Fix test * display the error on console * Move minio test to amd64 since minio docker don't support arm64 * don't change unrelated files * Fix lint * Fix build * update go.mod and go.sum * Use github.com/minio/minio-go/v6 * Remove unused function * Upgrade minio to v7 and some other improvements * fix lint * Fix go mod Co-authored-by: guillep2k <18600385+guillep2k@users.noreply.github.com> Co-authored-by: Tyler <tystuyfzand@gmail.com>
3 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. Project *Project `xorm:"-"`
  40. Priority int
  41. AssigneeID int64 `xorm:"-"`
  42. Assignee *User `xorm:"-"`
  43. IsClosed bool `xorm:"INDEX"`
  44. IsRead bool `xorm:"-"`
  45. IsPull bool `xorm:"INDEX"` // Indicates whether is a pull request or not.
  46. PullRequest *PullRequest `xorm:"-"`
  47. NumComments int
  48. Ref string
  49. DeadlineUnix timeutil.TimeStamp `xorm:"INDEX"`
  50. CreatedUnix timeutil.TimeStamp `xorm:"INDEX created"`
  51. UpdatedUnix timeutil.TimeStamp `xorm:"INDEX updated"`
  52. ClosedUnix timeutil.TimeStamp `xorm:"INDEX"`
  53. Attachments []*Attachment `xorm:"-"`
  54. Comments []*Comment `xorm:"-"`
  55. Reactions ReactionList `xorm:"-"`
  56. TotalTrackedTime int64 `xorm:"-"`
  57. Assignees []*User `xorm:"-"`
  58. // IsLocked limits commenting abilities to users on an issue
  59. // with write access
  60. IsLocked bool `xorm:"NOT NULL DEFAULT false"`
  61. }
  62. var (
  63. issueTasksPat *regexp.Regexp
  64. issueTasksDonePat *regexp.Regexp
  65. )
  66. const issueTasksRegexpStr = `(^\s*[-*]\s\[[\sxX]\]\s.)|(\n\s*[-*]\s\[[\sxX]\]\s.)`
  67. const issueTasksDoneRegexpStr = `(^\s*[-*]\s\[[xX]\]\s.)|(\n\s*[-*]\s\[[xX]\]\s.)`
  68. const issueMaxDupIndexAttempts = 3
  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.Milestone.ID != issue.MilestoneID) && 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.loadProject(e); err != nil {
  242. return
  243. }
  244. if err = issue.loadAssignees(e); err != nil {
  245. return
  246. }
  247. if err = issue.loadPullRequest(e); err != nil && !IsErrPullRequestNotExist(err) {
  248. // It is possible pull request is not yet created.
  249. return err
  250. }
  251. if issue.Attachments == nil {
  252. issue.Attachments, err = getAttachmentsByIssueID(e, issue.ID)
  253. if err != nil {
  254. return fmt.Errorf("getAttachmentsByIssueID [%d]: %v", issue.ID, err)
  255. }
  256. }
  257. if err = issue.loadComments(e); err != nil {
  258. return err
  259. }
  260. if err = CommentList(issue.Comments).loadAttributes(e); err != nil {
  261. return err
  262. }
  263. if issue.isTimetrackerEnabled(e) {
  264. if err = issue.loadTotalTimes(e); err != nil {
  265. return err
  266. }
  267. }
  268. return issue.loadReactions(e)
  269. }
  270. // LoadAttributes loads the attribute of this issue.
  271. func (issue *Issue) LoadAttributes() error {
  272. return issue.loadAttributes(x)
  273. }
  274. // LoadMilestone load milestone of this issue.
  275. func (issue *Issue) LoadMilestone() error {
  276. return issue.loadMilestone(x)
  277. }
  278. // GetIsRead load the `IsRead` field of the issue
  279. func (issue *Issue) GetIsRead(userID int64) error {
  280. issueUser := &IssueUser{IssueID: issue.ID, UID: userID}
  281. if has, err := x.Get(issueUser); err != nil {
  282. return err
  283. } else if !has {
  284. issue.IsRead = false
  285. return nil
  286. }
  287. issue.IsRead = issueUser.IsRead
  288. return nil
  289. }
  290. // APIURL returns the absolute APIURL to this issue.
  291. func (issue *Issue) APIURL() string {
  292. if issue.Repo == nil {
  293. err := issue.LoadRepo()
  294. if err != nil {
  295. log.Error("Issue[%d].APIURL(): %v", issue.ID, err)
  296. return ""
  297. }
  298. }
  299. return fmt.Sprintf("%s/issues/%d", issue.Repo.APIURL(), issue.Index)
  300. }
  301. // HTMLURL returns the absolute URL to this issue.
  302. func (issue *Issue) HTMLURL() string {
  303. var path string
  304. if issue.IsPull {
  305. path = "pulls"
  306. } else {
  307. path = "issues"
  308. }
  309. return fmt.Sprintf("%s/%s/%d", issue.Repo.HTMLURL(), path, issue.Index)
  310. }
  311. // DiffURL returns the absolute URL to this diff
  312. func (issue *Issue) DiffURL() string {
  313. if issue.IsPull {
  314. return fmt.Sprintf("%s/pulls/%d.diff", issue.Repo.HTMLURL(), issue.Index)
  315. }
  316. return ""
  317. }
  318. // PatchURL returns the absolute URL to this patch
  319. func (issue *Issue) PatchURL() string {
  320. if issue.IsPull {
  321. return fmt.Sprintf("%s/pulls/%d.patch", issue.Repo.HTMLURL(), issue.Index)
  322. }
  323. return ""
  324. }
  325. // State returns string representation of issue status.
  326. func (issue *Issue) State() api.StateType {
  327. if issue.IsClosed {
  328. return api.StateClosed
  329. }
  330. return api.StateOpen
  331. }
  332. // HashTag returns unique hash tag for issue.
  333. func (issue *Issue) HashTag() string {
  334. return "issue-" + com.ToStr(issue.ID)
  335. }
  336. // IsPoster returns true if given user by ID is the poster.
  337. func (issue *Issue) IsPoster(uid int64) bool {
  338. return issue.OriginalAuthorID == 0 && issue.PosterID == uid
  339. }
  340. func (issue *Issue) hasLabel(e Engine, labelID int64) bool {
  341. return hasIssueLabel(e, issue.ID, labelID)
  342. }
  343. // HasLabel returns true if issue has been labeled by given ID.
  344. func (issue *Issue) HasLabel(labelID int64) bool {
  345. return issue.hasLabel(x, labelID)
  346. }
  347. // ReplyReference returns tokenized address to use for email reply headers
  348. func (issue *Issue) ReplyReference() string {
  349. var path string
  350. if issue.IsPull {
  351. path = "pulls"
  352. } else {
  353. path = "issues"
  354. }
  355. return fmt.Sprintf("%s/%s/%d@%s", issue.Repo.FullName(), path, issue.Index, setting.Domain)
  356. }
  357. func (issue *Issue) addLabel(e *xorm.Session, label *Label, doer *User) error {
  358. return newIssueLabel(e, issue, label, doer)
  359. }
  360. func (issue *Issue) addLabels(e *xorm.Session, labels []*Label, doer *User) error {
  361. return newIssueLabels(e, issue, labels, doer)
  362. }
  363. func (issue *Issue) getLabels(e Engine) (err error) {
  364. if len(issue.Labels) > 0 {
  365. return nil
  366. }
  367. issue.Labels, err = getLabelsByIssueID(e, issue.ID)
  368. if err != nil {
  369. return fmt.Errorf("getLabelsByIssueID: %v", err)
  370. }
  371. return nil
  372. }
  373. func (issue *Issue) removeLabel(e *xorm.Session, doer *User, label *Label) error {
  374. return deleteIssueLabel(e, issue, label, doer)
  375. }
  376. func (issue *Issue) clearLabels(e *xorm.Session, doer *User) (err error) {
  377. if err = issue.getLabels(e); err != nil {
  378. return fmt.Errorf("getLabels: %v", err)
  379. }
  380. for i := range issue.Labels {
  381. if err = issue.removeLabel(e, doer, issue.Labels[i]); err != nil {
  382. return fmt.Errorf("removeLabel: %v", err)
  383. }
  384. }
  385. return nil
  386. }
  387. // ClearLabels removes all issue labels as the given user.
  388. // Triggers appropriate WebHooks, if any.
  389. func (issue *Issue) ClearLabels(doer *User) (err error) {
  390. sess := x.NewSession()
  391. defer sess.Close()
  392. if err = sess.Begin(); err != nil {
  393. return err
  394. }
  395. if err := issue.loadRepo(sess); err != nil {
  396. return err
  397. } else if err = issue.loadPullRequest(sess); err != nil {
  398. return err
  399. }
  400. perm, err := getUserRepoPermission(sess, issue.Repo, doer)
  401. if err != nil {
  402. return err
  403. }
  404. if !perm.CanWriteIssuesOrPulls(issue.IsPull) {
  405. return ErrRepoLabelNotExist{}
  406. }
  407. if err = issue.clearLabels(sess, doer); err != nil {
  408. return err
  409. }
  410. if err = sess.Commit(); err != nil {
  411. return fmt.Errorf("Commit: %v", err)
  412. }
  413. return nil
  414. }
  415. type labelSorter []*Label
  416. func (ts labelSorter) Len() int {
  417. return len([]*Label(ts))
  418. }
  419. func (ts labelSorter) Less(i, j int) bool {
  420. return []*Label(ts)[i].ID < []*Label(ts)[j].ID
  421. }
  422. func (ts labelSorter) Swap(i, j int) {
  423. []*Label(ts)[i], []*Label(ts)[j] = []*Label(ts)[j], []*Label(ts)[i]
  424. }
  425. // ReplaceLabels removes all current labels and add new labels to the issue.
  426. // Triggers appropriate WebHooks, if any.
  427. func (issue *Issue) ReplaceLabels(labels []*Label, doer *User) (err error) {
  428. sess := x.NewSession()
  429. defer sess.Close()
  430. if err = sess.Begin(); err != nil {
  431. return err
  432. }
  433. if err = issue.loadLabels(sess); err != nil {
  434. return err
  435. }
  436. sort.Sort(labelSorter(labels))
  437. sort.Sort(labelSorter(issue.Labels))
  438. var toAdd, toRemove []*Label
  439. addIndex, removeIndex := 0, 0
  440. for addIndex < len(labels) && removeIndex < len(issue.Labels) {
  441. addLabel := labels[addIndex]
  442. removeLabel := issue.Labels[removeIndex]
  443. if addLabel.ID == removeLabel.ID {
  444. addIndex++
  445. removeIndex++
  446. } else if addLabel.ID < removeLabel.ID {
  447. toAdd = append(toAdd, addLabel)
  448. addIndex++
  449. } else {
  450. toRemove = append(toRemove, removeLabel)
  451. removeIndex++
  452. }
  453. }
  454. toAdd = append(toAdd, labels[addIndex:]...)
  455. toRemove = append(toRemove, issue.Labels[removeIndex:]...)
  456. if len(toAdd) > 0 {
  457. if err = issue.addLabels(sess, toAdd, doer); err != nil {
  458. return fmt.Errorf("addLabels: %v", err)
  459. }
  460. }
  461. for _, l := range toRemove {
  462. if err = issue.removeLabel(sess, doer, l); err != nil {
  463. return fmt.Errorf("removeLabel: %v", err)
  464. }
  465. }
  466. return sess.Commit()
  467. }
  468. // ReadBy sets issue to be read by given user.
  469. func (issue *Issue) ReadBy(userID int64) error {
  470. if err := UpdateIssueUserByRead(userID, issue.ID); err != nil {
  471. return err
  472. }
  473. return setNotificationStatusReadIfUnread(x, userID, issue.ID)
  474. }
  475. func updateIssueCols(e Engine, issue *Issue, cols ...string) error {
  476. if _, err := e.ID(issue.ID).Cols(cols...).Update(issue); err != nil {
  477. return err
  478. }
  479. return nil
  480. }
  481. func (issue *Issue) changeStatus(e *xorm.Session, doer *User, isClosed, isMergePull bool) (*Comment, error) {
  482. // Reload the issue
  483. currentIssue, err := getIssueByID(e, issue.ID)
  484. if err != nil {
  485. return nil, err
  486. }
  487. // Nothing should be performed if current status is same as target status
  488. if currentIssue.IsClosed == isClosed {
  489. if !issue.IsPull {
  490. return nil, ErrIssueWasClosed{
  491. ID: issue.ID,
  492. }
  493. }
  494. return nil, ErrPullWasClosed{
  495. ID: issue.ID,
  496. }
  497. }
  498. issue.IsClosed = isClosed
  499. return issue.doChangeStatus(e, doer, isMergePull)
  500. }
  501. func (issue *Issue) doChangeStatus(e *xorm.Session, doer *User, isMergePull bool) (*Comment, error) {
  502. // Check for open dependencies
  503. if issue.IsClosed && issue.Repo.isDependenciesEnabled(e) {
  504. // only check if dependencies are enabled and we're about to close an issue, otherwise reopening an issue would fail when there are unsatisfied dependencies
  505. noDeps, err := issueNoDependenciesLeft(e, issue)
  506. if err != nil {
  507. return nil, err
  508. }
  509. if !noDeps {
  510. return nil, ErrDependenciesLeft{issue.ID}
  511. }
  512. }
  513. if issue.IsClosed {
  514. issue.ClosedUnix = timeutil.TimeStampNow()
  515. } else {
  516. issue.ClosedUnix = 0
  517. }
  518. if err := updateIssueCols(e, issue, "is_closed", "closed_unix"); err != nil {
  519. return nil, err
  520. }
  521. // Update issue count of labels
  522. if err := issue.getLabels(e); err != nil {
  523. return nil, err
  524. }
  525. for idx := range issue.Labels {
  526. if err := updateLabelCols(e, issue.Labels[idx], "num_issues", "num_closed_issue"); err != nil {
  527. return nil, err
  528. }
  529. }
  530. // Update issue count of milestone
  531. if err := updateMilestoneClosedNum(e, issue.MilestoneID); err != nil {
  532. return nil, err
  533. }
  534. if err := issue.updateClosedNum(e); err != nil {
  535. return nil, err
  536. }
  537. // New action comment
  538. cmtType := CommentTypeClose
  539. if !issue.IsClosed {
  540. cmtType = CommentTypeReopen
  541. } else if isMergePull {
  542. cmtType = CommentTypeMergePull
  543. }
  544. return createComment(e, &CreateCommentOptions{
  545. Type: cmtType,
  546. Doer: doer,
  547. Repo: issue.Repo,
  548. Issue: issue,
  549. })
  550. }
  551. // ChangeStatus changes issue status to open or closed.
  552. func (issue *Issue) ChangeStatus(doer *User, isClosed bool) (*Comment, error) {
  553. sess := x.NewSession()
  554. defer sess.Close()
  555. if err := sess.Begin(); err != nil {
  556. return nil, err
  557. }
  558. if err := issue.loadRepo(sess); err != nil {
  559. return nil, err
  560. }
  561. if err := issue.loadPoster(sess); err != nil {
  562. return nil, err
  563. }
  564. comment, err := issue.changeStatus(sess, doer, isClosed, false)
  565. if err != nil {
  566. return nil, err
  567. }
  568. if err = sess.Commit(); err != nil {
  569. return nil, fmt.Errorf("Commit: %v", err)
  570. }
  571. return comment, nil
  572. }
  573. // ChangeTitle changes the title of this issue, as the given user.
  574. func (issue *Issue) ChangeTitle(doer *User, oldTitle string) (err error) {
  575. sess := x.NewSession()
  576. defer sess.Close()
  577. if err = sess.Begin(); err != nil {
  578. return err
  579. }
  580. if err = updateIssueCols(sess, issue, "name"); err != nil {
  581. return fmt.Errorf("updateIssueCols: %v", err)
  582. }
  583. if err = issue.loadRepo(sess); err != nil {
  584. return fmt.Errorf("loadRepo: %v", err)
  585. }
  586. var opts = &CreateCommentOptions{
  587. Type: CommentTypeChangeTitle,
  588. Doer: doer,
  589. Repo: issue.Repo,
  590. Issue: issue,
  591. OldTitle: oldTitle,
  592. NewTitle: issue.Title,
  593. }
  594. if _, err = createComment(sess, opts); err != nil {
  595. return fmt.Errorf("createComment: %v", err)
  596. }
  597. if err = issue.addCrossReferences(sess, doer, true); err != nil {
  598. return err
  599. }
  600. return sess.Commit()
  601. }
  602. // ChangeRef changes the branch of this issue, as the given user.
  603. func (issue *Issue) ChangeRef(doer *User, oldRef string) (err error) {
  604. sess := x.NewSession()
  605. defer sess.Close()
  606. if err = sess.Begin(); err != nil {
  607. return err
  608. }
  609. if err = updateIssueCols(sess, issue, "ref"); err != nil {
  610. return fmt.Errorf("updateIssueCols: %v", err)
  611. }
  612. return sess.Commit()
  613. }
  614. // AddDeletePRBranchComment adds delete branch comment for pull request issue
  615. func AddDeletePRBranchComment(doer *User, repo *Repository, issueID int64, branchName string) error {
  616. issue, err := getIssueByID(x, issueID)
  617. if err != nil {
  618. return err
  619. }
  620. sess := x.NewSession()
  621. defer sess.Close()
  622. if err := sess.Begin(); err != nil {
  623. return err
  624. }
  625. var opts = &CreateCommentOptions{
  626. Type: CommentTypeDeleteBranch,
  627. Doer: doer,
  628. Repo: repo,
  629. Issue: issue,
  630. CommitSHA: branchName,
  631. }
  632. if _, err = createComment(sess, opts); err != nil {
  633. return err
  634. }
  635. return sess.Commit()
  636. }
  637. // UpdateAttachments update attachments by UUIDs for the issue
  638. func (issue *Issue) UpdateAttachments(uuids []string) (err error) {
  639. sess := x.NewSession()
  640. defer sess.Close()
  641. if err = sess.Begin(); err != nil {
  642. return err
  643. }
  644. attachments, err := getAttachmentsByUUIDs(sess, uuids)
  645. if err != nil {
  646. return fmt.Errorf("getAttachmentsByUUIDs [uuids: %v]: %v", uuids, err)
  647. }
  648. for i := 0; i < len(attachments); i++ {
  649. attachments[i].IssueID = issue.ID
  650. if err := updateAttachment(sess, attachments[i]); err != nil {
  651. return fmt.Errorf("update attachment [id: %d]: %v", attachments[i].ID, err)
  652. }
  653. }
  654. return sess.Commit()
  655. }
  656. // ChangeContent changes issue content, as the given user.
  657. func (issue *Issue) ChangeContent(doer *User, content string) (err error) {
  658. issue.Content = content
  659. sess := x.NewSession()
  660. defer sess.Close()
  661. if err = sess.Begin(); err != nil {
  662. return err
  663. }
  664. if err = updateIssueCols(sess, issue, "content"); err != nil {
  665. return fmt.Errorf("UpdateIssueCols: %v", err)
  666. }
  667. if err = issue.addCrossReferences(sess, doer, true); err != nil {
  668. return err
  669. }
  670. return sess.Commit()
  671. }
  672. // GetTasks returns the amount of tasks in the issues content
  673. func (issue *Issue) GetTasks() int {
  674. return len(issueTasksPat.FindAllStringIndex(issue.Content, -1))
  675. }
  676. // GetTasksDone returns the amount of completed tasks in the issues content
  677. func (issue *Issue) GetTasksDone() int {
  678. return len(issueTasksDonePat.FindAllStringIndex(issue.Content, -1))
  679. }
  680. // GetLastEventTimestamp returns the last user visible event timestamp, either the creation of this issue or the close.
  681. func (issue *Issue) GetLastEventTimestamp() timeutil.TimeStamp {
  682. if issue.IsClosed {
  683. return issue.ClosedUnix
  684. }
  685. return issue.CreatedUnix
  686. }
  687. // GetLastEventLabel returns the localization label for the current issue.
  688. func (issue *Issue) GetLastEventLabel() string {
  689. if issue.IsClosed {
  690. if issue.IsPull && issue.PullRequest.HasMerged {
  691. return "repo.pulls.merged_by"
  692. }
  693. return "repo.issues.closed_by"
  694. }
  695. return "repo.issues.opened_by"
  696. }
  697. // GetLastComment return last comment for the current issue.
  698. func (issue *Issue) GetLastComment() (*Comment, error) {
  699. var c Comment
  700. exist, err := x.Where("type = ?", CommentTypeComment).
  701. And("issue_id = ?", issue.ID).Desc("id").Get(&c)
  702. if err != nil {
  703. return nil, err
  704. }
  705. if !exist {
  706. return nil, nil
  707. }
  708. return &c, nil
  709. }
  710. // GetLastEventLabelFake returns the localization label for the current issue without providing a link in the username.
  711. func (issue *Issue) GetLastEventLabelFake() string {
  712. if issue.IsClosed {
  713. if issue.IsPull && issue.PullRequest.HasMerged {
  714. return "repo.pulls.merged_by_fake"
  715. }
  716. return "repo.issues.closed_by_fake"
  717. }
  718. return "repo.issues.opened_by_fake"
  719. }
  720. // NewIssueOptions represents the options of a new issue.
  721. type NewIssueOptions struct {
  722. Repo *Repository
  723. Issue *Issue
  724. LabelIDs []int64
  725. Attachments []string // In UUID format.
  726. IsPull bool
  727. }
  728. func newIssue(e *xorm.Session, doer *User, opts NewIssueOptions) (err error) {
  729. opts.Issue.Title = strings.TrimSpace(opts.Issue.Title)
  730. if opts.Issue.MilestoneID > 0 {
  731. milestone, err := getMilestoneByRepoID(e, opts.Issue.RepoID, opts.Issue.MilestoneID)
  732. if err != nil && !IsErrMilestoneNotExist(err) {
  733. return fmt.Errorf("getMilestoneByID: %v", err)
  734. }
  735. // Assume milestone is invalid and drop silently.
  736. opts.Issue.MilestoneID = 0
  737. if milestone != nil {
  738. opts.Issue.MilestoneID = milestone.ID
  739. opts.Issue.Milestone = milestone
  740. }
  741. }
  742. // Milestone validation should happen before insert actual object.
  743. if _, err := e.SetExpr("`index`", "coalesce(MAX(`index`),0)+1").
  744. Where("repo_id=?", opts.Issue.RepoID).
  745. Insert(opts.Issue); err != nil {
  746. return ErrNewIssueInsert{err}
  747. }
  748. inserted, err := getIssueByID(e, opts.Issue.ID)
  749. if err != nil {
  750. return err
  751. }
  752. // Patch Index with the value calculated by the database
  753. opts.Issue.Index = inserted.Index
  754. if opts.Issue.MilestoneID > 0 {
  755. if _, err = e.Exec("UPDATE `milestone` SET num_issues=num_issues+1 WHERE id=?", opts.Issue.MilestoneID); err != nil {
  756. return err
  757. }
  758. var opts = &CreateCommentOptions{
  759. Type: CommentTypeMilestone,
  760. Doer: doer,
  761. Repo: opts.Repo,
  762. Issue: opts.Issue,
  763. OldMilestoneID: 0,
  764. MilestoneID: opts.Issue.MilestoneID,
  765. }
  766. if _, err = createComment(e, opts); err != nil {
  767. return err
  768. }
  769. }
  770. if opts.IsPull {
  771. _, err = e.Exec("UPDATE `repository` SET num_pulls = num_pulls + 1 WHERE id = ?", opts.Issue.RepoID)
  772. } else {
  773. _, err = e.Exec("UPDATE `repository` SET num_issues = num_issues + 1 WHERE id = ?", opts.Issue.RepoID)
  774. }
  775. if err != nil {
  776. return err
  777. }
  778. if len(opts.LabelIDs) > 0 {
  779. // During the session, SQLite3 driver cannot handle retrieve objects after update something.
  780. // So we have to get all needed labels first.
  781. labels := make([]*Label, 0, len(opts.LabelIDs))
  782. if err = e.In("id", opts.LabelIDs).Find(&labels); err != nil {
  783. return fmt.Errorf("find all labels [label_ids: %v]: %v", opts.LabelIDs, err)
  784. }
  785. if err = opts.Issue.loadPoster(e); err != nil {
  786. return err
  787. }
  788. for _, label := range labels {
  789. // Silently drop invalid labels.
  790. if label.RepoID != opts.Repo.ID && label.OrgID != opts.Repo.OwnerID {
  791. continue
  792. }
  793. if err = opts.Issue.addLabel(e, label, opts.Issue.Poster); err != nil {
  794. return fmt.Errorf("addLabel [id: %d]: %v", label.ID, err)
  795. }
  796. }
  797. }
  798. if err = newIssueUsers(e, opts.Repo, opts.Issue); err != nil {
  799. return err
  800. }
  801. if len(opts.Attachments) > 0 {
  802. attachments, err := getAttachmentsByUUIDs(e, opts.Attachments)
  803. if err != nil {
  804. return fmt.Errorf("getAttachmentsByUUIDs [uuids: %v]: %v", opts.Attachments, err)
  805. }
  806. for i := 0; i < len(attachments); i++ {
  807. attachments[i].IssueID = opts.Issue.ID
  808. if _, err = e.ID(attachments[i].ID).Update(attachments[i]); err != nil {
  809. return fmt.Errorf("update attachment [id: %d]: %v", attachments[i].ID, err)
  810. }
  811. }
  812. }
  813. if err = opts.Issue.loadAttributes(e); err != nil {
  814. return err
  815. }
  816. return opts.Issue.addCrossReferences(e, doer, false)
  817. }
  818. // NewIssue creates new issue with labels for repository.
  819. func NewIssue(repo *Repository, issue *Issue, labelIDs []int64, uuids []string) (err error) {
  820. // Retry several times in case INSERT fails due to duplicate key for (repo_id, index); see #7887
  821. i := 0
  822. for {
  823. if err = newIssueAttempt(repo, issue, labelIDs, uuids); err == nil {
  824. return nil
  825. }
  826. if !IsErrNewIssueInsert(err) {
  827. return err
  828. }
  829. if i++; i == issueMaxDupIndexAttempts {
  830. break
  831. }
  832. log.Error("NewIssue: error attempting to insert the new issue; will retry. Original error: %v", err)
  833. }
  834. return fmt.Errorf("NewIssue: too many errors attempting to insert the new issue. Last error was: %v", err)
  835. }
  836. func newIssueAttempt(repo *Repository, issue *Issue, labelIDs []int64, uuids []string) (err error) {
  837. sess := x.NewSession()
  838. defer sess.Close()
  839. if err = sess.Begin(); err != nil {
  840. return err
  841. }
  842. if err = newIssue(sess, issue.Poster, NewIssueOptions{
  843. Repo: repo,
  844. Issue: issue,
  845. LabelIDs: labelIDs,
  846. Attachments: uuids,
  847. }); err != nil {
  848. if IsErrUserDoesNotHaveAccessToRepo(err) || IsErrNewIssueInsert(err) {
  849. return err
  850. }
  851. return fmt.Errorf("newIssue: %v", err)
  852. }
  853. if err = sess.Commit(); err != nil {
  854. return fmt.Errorf("Commit: %v", err)
  855. }
  856. return nil
  857. }
  858. // GetIssueByIndex returns raw issue without loading attributes by index in a repository.
  859. func GetIssueByIndex(repoID, index int64) (*Issue, error) {
  860. issue := &Issue{
  861. RepoID: repoID,
  862. Index: index,
  863. }
  864. has, err := x.Get(issue)
  865. if err != nil {
  866. return nil, err
  867. } else if !has {
  868. return nil, ErrIssueNotExist{0, repoID, index}
  869. }
  870. return issue, nil
  871. }
  872. // GetIssueWithAttrsByIndex returns issue by index in a repository.
  873. func GetIssueWithAttrsByIndex(repoID, index int64) (*Issue, error) {
  874. issue, err := GetIssueByIndex(repoID, index)
  875. if err != nil {
  876. return nil, err
  877. }
  878. return issue, issue.LoadAttributes()
  879. }
  880. func getIssueByID(e Engine, id int64) (*Issue, error) {
  881. issue := new(Issue)
  882. has, err := e.ID(id).Get(issue)
  883. if err != nil {
  884. return nil, err
  885. } else if !has {
  886. return nil, ErrIssueNotExist{id, 0, 0}
  887. }
  888. return issue, nil
  889. }
  890. // GetIssueWithAttrsByID returns an issue with attributes by given ID.
  891. func GetIssueWithAttrsByID(id int64) (*Issue, error) {
  892. issue, err := getIssueByID(x, id)
  893. if err != nil {
  894. return nil, err
  895. }
  896. return issue, issue.loadAttributes(x)
  897. }
  898. // GetIssueByID returns an issue by given ID.
  899. func GetIssueByID(id int64) (*Issue, error) {
  900. return getIssueByID(x, id)
  901. }
  902. func getIssuesByIDs(e Engine, issueIDs []int64) ([]*Issue, error) {
  903. issues := make([]*Issue, 0, 10)
  904. return issues, e.In("id", issueIDs).Find(&issues)
  905. }
  906. func getIssueIDsByRepoID(e Engine, repoID int64) ([]int64, error) {
  907. var ids = make([]int64, 0, 10)
  908. err := e.Table("issue").Where("repo_id = ?", repoID).Find(&ids)
  909. return ids, err
  910. }
  911. // GetIssueIDsByRepoID returns all issue ids by repo id
  912. func GetIssueIDsByRepoID(repoID int64) ([]int64, error) {
  913. return getIssueIDsByRepoID(x, repoID)
  914. }
  915. // GetIssuesByIDs return issues with the given IDs.
  916. func GetIssuesByIDs(issueIDs []int64) ([]*Issue, error) {
  917. return getIssuesByIDs(x, issueIDs)
  918. }
  919. // IssuesOptions represents options of an issue.
  920. type IssuesOptions struct {
  921. ListOptions
  922. RepoIDs []int64 // include all repos if empty
  923. AssigneeID int64
  924. PosterID int64
  925. MentionedID int64
  926. MilestoneIDs []int64
  927. ProjectID int64
  928. ProjectBoardID int64
  929. IsClosed util.OptionalBool
  930. IsPull util.OptionalBool
  931. LabelIDs []int64
  932. IncludedLabelNames []string
  933. ExcludedLabelNames []string
  934. SortType string
  935. IssueIDs []int64
  936. // prioritize issues from this repo
  937. PriorityRepoID int64
  938. }
  939. // sortIssuesSession sort an issues-related session based on the provided
  940. // sortType string
  941. func sortIssuesSession(sess *xorm.Session, sortType string, priorityRepoID int64) {
  942. switch sortType {
  943. case "oldest":
  944. sess.Asc("issue.created_unix")
  945. case "recentupdate":
  946. sess.Desc("issue.updated_unix")
  947. case "leastupdate":
  948. sess.Asc("issue.updated_unix")
  949. case "mostcomment":
  950. sess.Desc("issue.num_comments")
  951. case "leastcomment":
  952. sess.Asc("issue.num_comments")
  953. case "priority":
  954. sess.Desc("issue.priority")
  955. case "nearduedate":
  956. // 253370764800 is 01/01/9999 @ 12:00am (UTC)
  957. sess.OrderBy("CASE WHEN issue.deadline_unix = 0 THEN 253370764800 ELSE issue.deadline_unix END ASC")
  958. case "farduedate":
  959. sess.Desc("issue.deadline_unix")
  960. case "priorityrepo":
  961. sess.OrderBy("CASE WHEN issue.repo_id = " + strconv.FormatInt(priorityRepoID, 10) + " THEN 1 ELSE 2 END, issue.created_unix DESC")
  962. default:
  963. sess.Desc("issue.created_unix")
  964. }
  965. }
  966. func (opts *IssuesOptions) setupSession(sess *xorm.Session) {
  967. if opts.Page >= 0 && opts.PageSize > 0 {
  968. var start int
  969. if opts.Page == 0 {
  970. start = 0
  971. } else {
  972. start = (opts.Page - 1) * opts.PageSize
  973. }
  974. sess.Limit(opts.PageSize, start)
  975. }
  976. if len(opts.IssueIDs) > 0 {
  977. sess.In("issue.id", opts.IssueIDs)
  978. }
  979. if len(opts.RepoIDs) > 0 {
  980. // In case repository IDs are provided but actually no repository has issue.
  981. sess.In("issue.repo_id", opts.RepoIDs)
  982. }
  983. switch opts.IsClosed {
  984. case util.OptionalBoolTrue:
  985. sess.And("issue.is_closed=?", true)
  986. case util.OptionalBoolFalse:
  987. sess.And("issue.is_closed=?", false)
  988. }
  989. if opts.AssigneeID > 0 {
  990. sess.Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  991. And("issue_assignees.assignee_id = ?", opts.AssigneeID)
  992. }
  993. if opts.PosterID > 0 {
  994. sess.And("issue.poster_id=?", opts.PosterID)
  995. }
  996. if opts.MentionedID > 0 {
  997. sess.Join("INNER", "issue_user", "issue.id = issue_user.issue_id").
  998. And("issue_user.is_mentioned = ?", true).
  999. And("issue_user.uid = ?", opts.MentionedID)
  1000. }
  1001. if len(opts.MilestoneIDs) > 0 {
  1002. sess.In("issue.milestone_id", opts.MilestoneIDs)
  1003. }
  1004. if opts.ProjectID > 0 {
  1005. sess.Join("INNER", "project_issue", "issue.id = project_issue.issue_id").
  1006. And("project_issue.project_id=?", opts.ProjectID)
  1007. }
  1008. if opts.ProjectBoardID != 0 {
  1009. if opts.ProjectBoardID > 0 {
  1010. sess.In("issue.id", builder.Select("issue_id").From("project_issue").Where(builder.Eq{"project_board_id": opts.ProjectBoardID}))
  1011. } else {
  1012. sess.In("issue.id", builder.Select("issue_id").From("project_issue").Where(builder.Eq{"project_board_id": 0}))
  1013. }
  1014. }
  1015. switch opts.IsPull {
  1016. case util.OptionalBoolTrue:
  1017. sess.And("issue.is_pull=?", true)
  1018. case util.OptionalBoolFalse:
  1019. sess.And("issue.is_pull=?", false)
  1020. }
  1021. if opts.LabelIDs != nil {
  1022. for i, labelID := range opts.LabelIDs {
  1023. if labelID > 0 {
  1024. sess.Join("INNER", fmt.Sprintf("issue_label il%d", i),
  1025. fmt.Sprintf("issue.id = il%[1]d.issue_id AND il%[1]d.label_id = %[2]d", i, labelID))
  1026. } else {
  1027. sess.Where("issue.id not in (select issue_id from issue_label where label_id = ?)", -labelID)
  1028. }
  1029. }
  1030. }
  1031. if len(opts.IncludedLabelNames) > 0 {
  1032. sess.In("issue.id", BuildLabelNamesIssueIDsCondition(opts.IncludedLabelNames))
  1033. }
  1034. if len(opts.ExcludedLabelNames) > 0 {
  1035. sess.And(builder.NotIn("issue.id", BuildLabelNamesIssueIDsCondition(opts.ExcludedLabelNames)))
  1036. }
  1037. }
  1038. // CountIssuesByRepo map from repoID to number of issues matching the options
  1039. func CountIssuesByRepo(opts *IssuesOptions) (map[int64]int64, error) {
  1040. sess := x.NewSession()
  1041. defer sess.Close()
  1042. opts.setupSession(sess)
  1043. countsSlice := make([]*struct {
  1044. RepoID int64
  1045. Count int64
  1046. }, 0, 10)
  1047. if err := sess.GroupBy("issue.repo_id").
  1048. Select("issue.repo_id AS repo_id, COUNT(*) AS count").
  1049. Table("issue").
  1050. Find(&countsSlice); err != nil {
  1051. return nil, err
  1052. }
  1053. countMap := make(map[int64]int64, len(countsSlice))
  1054. for _, c := range countsSlice {
  1055. countMap[c.RepoID] = c.Count
  1056. }
  1057. return countMap, nil
  1058. }
  1059. // GetRepoIDsForIssuesOptions find all repo ids for the given options
  1060. func GetRepoIDsForIssuesOptions(opts *IssuesOptions, user *User) ([]int64, error) {
  1061. repoIDs := make([]int64, 0, 5)
  1062. sess := x.NewSession()
  1063. defer sess.Close()
  1064. opts.setupSession(sess)
  1065. accessCond := accessibleRepositoryCondition(user)
  1066. if err := sess.Where(accessCond).
  1067. Join("INNER", "repository", "`issue`.repo_id = `repository`.id").
  1068. Distinct("issue.repo_id").
  1069. Table("issue").
  1070. Find(&repoIDs); err != nil {
  1071. return nil, err
  1072. }
  1073. return repoIDs, nil
  1074. }
  1075. // Issues returns a list of issues by given conditions.
  1076. func Issues(opts *IssuesOptions) ([]*Issue, error) {
  1077. sess := x.NewSession()
  1078. defer sess.Close()
  1079. opts.setupSession(sess)
  1080. sortIssuesSession(sess, opts.SortType, opts.PriorityRepoID)
  1081. issues := make([]*Issue, 0, setting.UI.IssuePagingNum)
  1082. if err := sess.Find(&issues); err != nil {
  1083. return nil, fmt.Errorf("Find: %v", err)
  1084. }
  1085. sess.Close()
  1086. if err := IssueList(issues).LoadAttributes(); err != nil {
  1087. return nil, fmt.Errorf("LoadAttributes: %v", err)
  1088. }
  1089. return issues, nil
  1090. }
  1091. // GetParticipantsIDsByIssueID returns the IDs of all users who participated in comments of an issue,
  1092. // but skips joining with `user` for performance reasons.
  1093. // User permissions must be verified elsewhere if required.
  1094. func GetParticipantsIDsByIssueID(issueID int64) ([]int64, error) {
  1095. userIDs := make([]int64, 0, 5)
  1096. return userIDs, x.Table("comment").
  1097. Cols("poster_id").
  1098. Where("issue_id = ?", issueID).
  1099. And("type in (?,?,?)", CommentTypeComment, CommentTypeCode, CommentTypeReview).
  1100. Distinct("poster_id").
  1101. Find(&userIDs)
  1102. }
  1103. // IsUserParticipantsOfIssue return true if user is participants of an issue
  1104. func IsUserParticipantsOfIssue(user *User, issue *Issue) bool {
  1105. userIDs, err := issue.getParticipantIDsByIssue(x)
  1106. if err != nil {
  1107. log.Error(err.Error())
  1108. return false
  1109. }
  1110. return util.IsInt64InSlice(user.ID, userIDs)
  1111. }
  1112. // UpdateIssueMentions updates issue-user relations for mentioned users.
  1113. func UpdateIssueMentions(ctx DBContext, issueID int64, mentions []*User) error {
  1114. if len(mentions) == 0 {
  1115. return nil
  1116. }
  1117. ids := make([]int64, len(mentions))
  1118. for i, u := range mentions {
  1119. ids[i] = u.ID
  1120. }
  1121. if err := UpdateIssueUsersByMentions(ctx, issueID, ids); err != nil {
  1122. return fmt.Errorf("UpdateIssueUsersByMentions: %v", err)
  1123. }
  1124. return nil
  1125. }
  1126. // IssueStats represents issue statistic information.
  1127. type IssueStats struct {
  1128. OpenCount, ClosedCount int64
  1129. YourRepositoriesCount int64
  1130. AssignCount int64
  1131. CreateCount int64
  1132. MentionCount int64
  1133. }
  1134. // Filter modes.
  1135. const (
  1136. FilterModeAll = iota
  1137. FilterModeAssign
  1138. FilterModeCreate
  1139. FilterModeMention
  1140. )
  1141. func parseCountResult(results []map[string][]byte) int64 {
  1142. if len(results) == 0 {
  1143. return 0
  1144. }
  1145. for _, result := range results[0] {
  1146. return com.StrTo(string(result)).MustInt64()
  1147. }
  1148. return 0
  1149. }
  1150. // IssueStatsOptions contains parameters accepted by GetIssueStats.
  1151. type IssueStatsOptions struct {
  1152. RepoID int64
  1153. Labels string
  1154. MilestoneID int64
  1155. AssigneeID int64
  1156. MentionedID int64
  1157. PosterID int64
  1158. IsPull util.OptionalBool
  1159. IssueIDs []int64
  1160. }
  1161. // GetIssueStats returns issue statistic information by given conditions.
  1162. func GetIssueStats(opts *IssueStatsOptions) (*IssueStats, error) {
  1163. if len(opts.IssueIDs) <= maxQueryParameters {
  1164. return getIssueStatsChunk(opts, opts.IssueIDs)
  1165. }
  1166. // If too long a list of IDs is provided, we get the statistics in
  1167. // smaller chunks and get accumulates. Note: this could potentially
  1168. // get us invalid results. The alternative is to insert the list of
  1169. // ids in a temporary table and join from them.
  1170. accum := &IssueStats{}
  1171. for i := 0; i < len(opts.IssueIDs); {
  1172. chunk := i + maxQueryParameters
  1173. if chunk > len(opts.IssueIDs) {
  1174. chunk = len(opts.IssueIDs)
  1175. }
  1176. stats, err := getIssueStatsChunk(opts, opts.IssueIDs[i:chunk])
  1177. if err != nil {
  1178. return nil, err
  1179. }
  1180. accum.OpenCount += stats.OpenCount
  1181. accum.ClosedCount += stats.ClosedCount
  1182. accum.YourRepositoriesCount += stats.YourRepositoriesCount
  1183. accum.AssignCount += stats.AssignCount
  1184. accum.CreateCount += stats.CreateCount
  1185. accum.OpenCount += stats.MentionCount
  1186. i = chunk
  1187. }
  1188. return accum, nil
  1189. }
  1190. func getIssueStatsChunk(opts *IssueStatsOptions, issueIDs []int64) (*IssueStats, error) {
  1191. stats := &IssueStats{}
  1192. countSession := func(opts *IssueStatsOptions) *xorm.Session {
  1193. sess := x.
  1194. Where("issue.repo_id = ?", opts.RepoID)
  1195. if len(opts.IssueIDs) > 0 {
  1196. sess.In("issue.id", opts.IssueIDs)
  1197. }
  1198. if len(opts.Labels) > 0 && opts.Labels != "0" {
  1199. labelIDs, err := base.StringsToInt64s(strings.Split(opts.Labels, ","))
  1200. if err != nil {
  1201. log.Warn("Malformed Labels argument: %s", opts.Labels)
  1202. } else {
  1203. for i, labelID := range labelIDs {
  1204. if labelID > 0 {
  1205. sess.Join("INNER", fmt.Sprintf("issue_label il%d", i),
  1206. fmt.Sprintf("issue.id = il%[1]d.issue_id AND il%[1]d.label_id = %[2]d", i, labelID))
  1207. } else {
  1208. sess.Where("issue.id NOT IN (SELECT issue_id FROM issue_label WHERE label_id = ?)", -labelID)
  1209. }
  1210. }
  1211. }
  1212. }
  1213. if opts.MilestoneID > 0 {
  1214. sess.And("issue.milestone_id = ?", opts.MilestoneID)
  1215. }
  1216. if opts.AssigneeID > 0 {
  1217. sess.Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  1218. And("issue_assignees.assignee_id = ?", opts.AssigneeID)
  1219. }
  1220. if opts.PosterID > 0 {
  1221. sess.And("issue.poster_id = ?", opts.PosterID)
  1222. }
  1223. if opts.MentionedID > 0 {
  1224. sess.Join("INNER", "issue_user", "issue.id = issue_user.issue_id").
  1225. And("issue_user.uid = ?", opts.MentionedID).
  1226. And("issue_user.is_mentioned = ?", true)
  1227. }
  1228. switch opts.IsPull {
  1229. case util.OptionalBoolTrue:
  1230. sess.And("issue.is_pull=?", true)
  1231. case util.OptionalBoolFalse:
  1232. sess.And("issue.is_pull=?", false)
  1233. }
  1234. return sess
  1235. }
  1236. var err error
  1237. stats.OpenCount, err = countSession(opts).
  1238. And("issue.is_closed = ?", false).
  1239. Count(new(Issue))
  1240. if err != nil {
  1241. return stats, err
  1242. }
  1243. stats.ClosedCount, err = countSession(opts).
  1244. And("issue.is_closed = ?", true).
  1245. Count(new(Issue))
  1246. return stats, err
  1247. }
  1248. // UserIssueStatsOptions contains parameters accepted by GetUserIssueStats.
  1249. type UserIssueStatsOptions struct {
  1250. UserID int64
  1251. RepoIDs []int64
  1252. UserRepoIDs []int64
  1253. FilterMode int
  1254. IsPull bool
  1255. IsClosed bool
  1256. IssueIDs []int64
  1257. }
  1258. // GetUserIssueStats returns issue statistic information for dashboard by given conditions.
  1259. func GetUserIssueStats(opts UserIssueStatsOptions) (*IssueStats, error) {
  1260. var err error
  1261. stats := &IssueStats{}
  1262. cond := builder.NewCond()
  1263. cond = cond.And(builder.Eq{"issue.is_pull": opts.IsPull})
  1264. if len(opts.RepoIDs) > 0 {
  1265. cond = cond.And(builder.In("issue.repo_id", opts.RepoIDs))
  1266. }
  1267. if len(opts.IssueIDs) > 0 {
  1268. cond = cond.And(builder.In("issue.id", opts.IssueIDs))
  1269. }
  1270. switch opts.FilterMode {
  1271. case FilterModeAll:
  1272. stats.OpenCount, err = x.Where(cond).And("issue.is_closed = ?", false).
  1273. And(builder.In("issue.repo_id", opts.UserRepoIDs)).
  1274. Count(new(Issue))
  1275. if err != nil {
  1276. return nil, err
  1277. }
  1278. stats.ClosedCount, err = x.Where(cond).And("issue.is_closed = ?", true).
  1279. And(builder.In("issue.repo_id", opts.UserRepoIDs)).
  1280. Count(new(Issue))
  1281. if err != nil {
  1282. return nil, err
  1283. }
  1284. case FilterModeAssign:
  1285. stats.OpenCount, err = x.Where(cond).And("issue.is_closed = ?", false).
  1286. Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  1287. And("issue_assignees.assignee_id = ?", opts.UserID).
  1288. Count(new(Issue))
  1289. if err != nil {
  1290. return nil, err
  1291. }
  1292. stats.ClosedCount, err = x.Where(cond).And("issue.is_closed = ?", true).
  1293. Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  1294. And("issue_assignees.assignee_id = ?", opts.UserID).
  1295. Count(new(Issue))
  1296. if err != nil {
  1297. return nil, err
  1298. }
  1299. case FilterModeCreate:
  1300. stats.OpenCount, err = x.Where(cond).And("issue.is_closed = ?", false).
  1301. And("issue.poster_id = ?", opts.UserID).
  1302. Count(new(Issue))
  1303. if err != nil {
  1304. return nil, err
  1305. }
  1306. stats.ClosedCount, err = x.Where(cond).And("issue.is_closed = ?", true).
  1307. And("issue.poster_id = ?", opts.UserID).
  1308. Count(new(Issue))
  1309. if err != nil {
  1310. return nil, err
  1311. }
  1312. case FilterModeMention:
  1313. stats.OpenCount, err = x.Where(cond).And("issue.is_closed = ?", false).
  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.ClosedCount, err = x.Where(cond).And("issue.is_closed = ?", true).
  1321. Join("INNER", "issue_user", "issue.id = issue_user.issue_id and issue_user.is_mentioned = ?", true).
  1322. And("issue_user.uid = ?", opts.UserID).
  1323. Count(new(Issue))
  1324. if err != nil {
  1325. return nil, err
  1326. }
  1327. }
  1328. cond = cond.And(builder.Eq{"issue.is_closed": opts.IsClosed})
  1329. stats.AssignCount, err = x.Where(cond).
  1330. Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  1331. And("issue_assignees.assignee_id = ?", opts.UserID).
  1332. Count(new(Issue))
  1333. if err != nil {
  1334. return nil, err
  1335. }
  1336. stats.CreateCount, err = x.Where(cond).
  1337. And("poster_id = ?", opts.UserID).
  1338. Count(new(Issue))
  1339. if err != nil {
  1340. return nil, err
  1341. }
  1342. stats.MentionCount, err = x.Where(cond).
  1343. Join("INNER", "issue_user", "issue.id = issue_user.issue_id and issue_user.is_mentioned = ?", true).
  1344. And("issue_user.uid = ?", opts.UserID).
  1345. Count(new(Issue))
  1346. if err != nil {
  1347. return nil, err
  1348. }
  1349. stats.YourRepositoriesCount, err = x.Where(cond).
  1350. And(builder.In("issue.repo_id", opts.UserRepoIDs)).
  1351. Count(new(Issue))
  1352. if err != nil {
  1353. return nil, err
  1354. }
  1355. return stats, nil
  1356. }
  1357. // GetRepoIssueStats returns number of open and closed repository issues by given filter mode.
  1358. func GetRepoIssueStats(repoID, uid int64, filterMode int, isPull bool) (numOpen int64, numClosed int64) {
  1359. countSession := func(isClosed, isPull bool, repoID int64) *xorm.Session {
  1360. sess := x.
  1361. Where("is_closed = ?", isClosed).
  1362. And("is_pull = ?", isPull).
  1363. And("repo_id = ?", repoID)
  1364. return sess
  1365. }
  1366. openCountSession := countSession(false, isPull, repoID)
  1367. closedCountSession := countSession(true, isPull, repoID)
  1368. switch filterMode {
  1369. case FilterModeAssign:
  1370. openCountSession.Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  1371. And("issue_assignees.assignee_id = ?", uid)
  1372. closedCountSession.Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  1373. And("issue_assignees.assignee_id = ?", uid)
  1374. case FilterModeCreate:
  1375. openCountSession.And("poster_id = ?", uid)
  1376. closedCountSession.And("poster_id = ?", uid)
  1377. }
  1378. openResult, _ := openCountSession.Count(new(Issue))
  1379. closedResult, _ := closedCountSession.Count(new(Issue))
  1380. return openResult, closedResult
  1381. }
  1382. // SearchIssueIDsByKeyword search issues on database
  1383. func SearchIssueIDsByKeyword(kw string, repoIDs []int64, limit, start int) (int64, []int64, error) {
  1384. var repoCond = builder.In("repo_id", repoIDs)
  1385. var subQuery = builder.Select("id").From("issue").Where(repoCond)
  1386. var cond = builder.And(
  1387. repoCond,
  1388. builder.Or(
  1389. builder.Like{"name", kw},
  1390. builder.Like{"content", kw},
  1391. builder.In("id", builder.Select("issue_id").
  1392. From("comment").
  1393. Where(builder.And(
  1394. builder.Eq{"type": CommentTypeComment},
  1395. builder.In("issue_id", subQuery),
  1396. builder.Like{"content", kw},
  1397. )),
  1398. ),
  1399. ),
  1400. )
  1401. var ids = make([]int64, 0, limit)
  1402. err := x.Distinct("id").Table("issue").Where(cond).Limit(limit, start).Find(&ids)
  1403. if err != nil {
  1404. return 0, nil, err
  1405. }
  1406. total, err := x.Distinct("id").Table("issue").Where(cond).Count()
  1407. if err != nil {
  1408. return 0, nil, err
  1409. }
  1410. return total, ids, nil
  1411. }
  1412. // UpdateIssueByAPI updates all allowed fields of given issue.
  1413. // If the issue status is changed a statusChangeComment is returned
  1414. // similarly if the title is changed the titleChanged bool is set to true
  1415. func UpdateIssueByAPI(issue *Issue, doer *User) (statusChangeComment *Comment, titleChanged bool, err error) {
  1416. sess := x.NewSession()
  1417. defer sess.Close()
  1418. if err := sess.Begin(); err != nil {
  1419. return nil, false, err
  1420. }
  1421. if err := issue.loadRepo(sess); err != nil {
  1422. return nil, false, fmt.Errorf("loadRepo: %v", err)
  1423. }
  1424. // Reload the issue
  1425. currentIssue, err := getIssueByID(sess, issue.ID)
  1426. if err != nil {
  1427. return nil, false, err
  1428. }
  1429. if _, err := sess.ID(issue.ID).Cols(
  1430. "name", "content", "milestone_id", "priority",
  1431. "deadline_unix", "updated_unix", "is_locked").
  1432. Update(issue); err != nil {
  1433. return nil, false, err
  1434. }
  1435. titleChanged = currentIssue.Title != issue.Title
  1436. if titleChanged {
  1437. var opts = &CreateCommentOptions{
  1438. Type: CommentTypeChangeTitle,
  1439. Doer: doer,
  1440. Repo: issue.Repo,
  1441. Issue: issue,
  1442. OldTitle: currentIssue.Title,
  1443. NewTitle: issue.Title,
  1444. }
  1445. _, err := createComment(sess, opts)
  1446. if err != nil {
  1447. return nil, false, fmt.Errorf("createComment: %v", err)
  1448. }
  1449. }
  1450. if currentIssue.IsClosed != issue.IsClosed {
  1451. statusChangeComment, err = issue.doChangeStatus(sess, doer, false)
  1452. if err != nil {
  1453. return nil, false, err
  1454. }
  1455. }
  1456. if err := issue.addCrossReferences(sess, doer, true); err != nil {
  1457. return nil, false, err
  1458. }
  1459. return statusChangeComment, titleChanged, sess.Commit()
  1460. }
  1461. // UpdateIssueDeadline updates an issue deadline and adds comments. Setting a deadline to 0 means deleting it.
  1462. func UpdateIssueDeadline(issue *Issue, deadlineUnix timeutil.TimeStamp, doer *User) (err error) {
  1463. // if the deadline hasn't changed do nothing
  1464. if issue.DeadlineUnix == deadlineUnix {
  1465. return nil
  1466. }
  1467. sess := x.NewSession()
  1468. defer sess.Close()
  1469. if err := sess.Begin(); err != nil {
  1470. return err
  1471. }
  1472. // Update the deadline
  1473. if err = updateIssueCols(sess, &Issue{ID: issue.ID, DeadlineUnix: deadlineUnix}, "deadline_unix"); err != nil {
  1474. return err
  1475. }
  1476. // Make the comment
  1477. if _, err = createDeadlineComment(sess, doer, issue, deadlineUnix); err != nil {
  1478. return fmt.Errorf("createRemovedDueDateComment: %v", err)
  1479. }
  1480. return sess.Commit()
  1481. }
  1482. // DependencyInfo represents high level information about an issue which is a dependency of another issue.
  1483. type DependencyInfo struct {
  1484. Issue `xorm:"extends"`
  1485. Repository `xorm:"extends"`
  1486. }
  1487. // getParticipantIDsByIssue returns all userIDs who are participated in comments of an issue and issue author
  1488. func (issue *Issue) getParticipantIDsByIssue(e Engine) ([]int64, error) {
  1489. if issue == nil {
  1490. return nil, nil
  1491. }
  1492. userIDs := make([]int64, 0, 5)
  1493. if err := e.Table("comment").Cols("poster_id").
  1494. Where("`comment`.issue_id = ?", issue.ID).
  1495. And("`comment`.type in (?,?,?)", CommentTypeComment, CommentTypeCode, CommentTypeReview).
  1496. And("`user`.is_active = ?", true).
  1497. And("`user`.prohibit_login = ?", false).
  1498. Join("INNER", "`user`", "`user`.id = `comment`.poster_id").
  1499. Distinct("poster_id").
  1500. Find(&userIDs); err != nil {
  1501. return nil, fmt.Errorf("get poster IDs: %v", err)
  1502. }
  1503. if !util.IsInt64InSlice(issue.PosterID, userIDs) {
  1504. return append(userIDs, issue.PosterID), nil
  1505. }
  1506. return userIDs, nil
  1507. }
  1508. // Get Blocked By Dependencies, aka all issues this issue is blocked by.
  1509. func (issue *Issue) getBlockedByDependencies(e Engine) (issueDeps []*DependencyInfo, err error) {
  1510. return issueDeps, e.
  1511. Table("issue").
  1512. Join("INNER", "repository", "repository.id = issue.repo_id").
  1513. Join("INNER", "issue_dependency", "issue_dependency.dependency_id = issue.id").
  1514. Where("issue_id = ?", issue.ID).
  1515. //sort by repo id then created date, with the issues of the same repo at the beginning of the list
  1516. OrderBy("CASE WHEN issue.repo_id = " + strconv.FormatInt(issue.RepoID, 10) + " THEN 0 ELSE issue.repo_id END, issue.created_unix DESC").
  1517. Find(&issueDeps)
  1518. }
  1519. // Get Blocking Dependencies, aka all issues this issue blocks.
  1520. func (issue *Issue) getBlockingDependencies(e Engine) (issueDeps []*DependencyInfo, err error) {
  1521. return issueDeps, e.
  1522. Table("issue").
  1523. Join("INNER", "repository", "repository.id = issue.repo_id").
  1524. Join("INNER", "issue_dependency", "issue_dependency.issue_id = issue.id").
  1525. Where("dependency_id = ?", issue.ID).
  1526. //sort by repo id then created date, with the issues of the same repo at the beginning of the list
  1527. OrderBy("CASE WHEN issue.repo_id = " + strconv.FormatInt(issue.RepoID, 10) + " THEN 0 ELSE issue.repo_id END, issue.created_unix DESC").
  1528. Find(&issueDeps)
  1529. }
  1530. // BlockedByDependencies finds all Dependencies an issue is blocked by
  1531. func (issue *Issue) BlockedByDependencies() ([]*DependencyInfo, error) {
  1532. return issue.getBlockedByDependencies(x)
  1533. }
  1534. // BlockingDependencies returns all blocking dependencies, aka all other issues a given issue blocks
  1535. func (issue *Issue) BlockingDependencies() ([]*DependencyInfo, error) {
  1536. return issue.getBlockingDependencies(x)
  1537. }
  1538. func (issue *Issue) updateClosedNum(e Engine) (err error) {
  1539. if issue.IsPull {
  1540. _, err = e.Exec("UPDATE `repository` SET num_closed_pulls=(SELECT count(*) FROM issue WHERE repo_id=? AND is_pull=? AND is_closed=?) WHERE id=?",
  1541. issue.RepoID,
  1542. true,
  1543. true,
  1544. issue.RepoID,
  1545. )
  1546. } else {
  1547. _, err = e.Exec("UPDATE `repository` SET num_closed_issues=(SELECT count(*) FROM issue WHERE repo_id=? AND is_pull=? AND is_closed=?) WHERE id=?",
  1548. issue.RepoID,
  1549. false,
  1550. true,
  1551. issue.RepoID,
  1552. )
  1553. }
  1554. return
  1555. }
  1556. // ResolveMentionsByVisibility returns the users mentioned in an issue, removing those that
  1557. // don't have access to reading it. Teams are expanded into their users, but organizations are ignored.
  1558. func (issue *Issue) ResolveMentionsByVisibility(ctx DBContext, doer *User, mentions []string) (users []*User, err error) {
  1559. if len(mentions) == 0 {
  1560. return
  1561. }
  1562. if err = issue.loadRepo(ctx.e); err != nil {
  1563. return
  1564. }
  1565. resolved := make(map[string]bool, 20)
  1566. names := make([]string, 0, 20)
  1567. resolved[doer.LowerName] = true
  1568. for _, name := range mentions {
  1569. name := strings.ToLower(name)
  1570. if _, ok := resolved[name]; ok {
  1571. continue
  1572. }
  1573. resolved[name] = false
  1574. names = append(names, name)
  1575. }
  1576. if err := issue.Repo.getOwner(ctx.e); err != nil {
  1577. return nil, err
  1578. }
  1579. if issue.Repo.Owner.IsOrganization() {
  1580. // Since there can be users with names that match the name of a team,
  1581. // if the team exists and can read the issue, the team takes precedence.
  1582. teams := make([]*Team, 0, len(names))
  1583. if err := ctx.e.
  1584. Join("INNER", "team_repo", "team_repo.team_id = team.id").
  1585. Where("team_repo.repo_id=?", issue.Repo.ID).
  1586. In("team.lower_name", names).
  1587. Find(&teams); err != nil {
  1588. return nil, fmt.Errorf("find mentioned teams: %v", err)
  1589. }
  1590. if len(teams) != 0 {
  1591. checked := make([]int64, 0, len(teams))
  1592. unittype := UnitTypeIssues
  1593. if issue.IsPull {
  1594. unittype = UnitTypePullRequests
  1595. }
  1596. for _, team := range teams {
  1597. if team.Authorize >= AccessModeOwner {
  1598. checked = append(checked, team.ID)
  1599. resolved[team.LowerName] = true
  1600. continue
  1601. }
  1602. has, err := ctx.e.Get(&TeamUnit{OrgID: issue.Repo.Owner.ID, TeamID: team.ID, Type: unittype})
  1603. if err != nil {
  1604. return nil, fmt.Errorf("get team units (%d): %v", team.ID, err)
  1605. }
  1606. if has {
  1607. checked = append(checked, team.ID)
  1608. resolved[team.LowerName] = true
  1609. }
  1610. }
  1611. if len(checked) != 0 {
  1612. teamusers := make([]*User, 0, 20)
  1613. if err := ctx.e.
  1614. Join("INNER", "team_user", "team_user.uid = `user`.id").
  1615. In("`team_user`.team_id", checked).
  1616. And("`user`.is_active = ?", true).
  1617. And("`user`.prohibit_login = ?", false).
  1618. Find(&teamusers); err != nil {
  1619. return nil, fmt.Errorf("get teams users: %v", err)
  1620. }
  1621. if len(teamusers) > 0 {
  1622. users = make([]*User, 0, len(teamusers))
  1623. for _, user := range teamusers {
  1624. if already, ok := resolved[user.LowerName]; !ok || !already {
  1625. users = append(users, user)
  1626. resolved[user.LowerName] = true
  1627. }
  1628. }
  1629. }
  1630. }
  1631. }
  1632. // Remove names already in the list to avoid querying the database if pending names remain
  1633. names = make([]string, 0, len(resolved))
  1634. for name, already := range resolved {
  1635. if !already {
  1636. names = append(names, name)
  1637. }
  1638. }
  1639. if len(names) == 0 {
  1640. return
  1641. }
  1642. }
  1643. unchecked := make([]*User, 0, len(names))
  1644. if err := ctx.e.
  1645. Where("`user`.is_active = ?", true).
  1646. And("`user`.prohibit_login = ?", false).
  1647. In("`user`.lower_name", names).
  1648. Find(&unchecked); err != nil {
  1649. return nil, fmt.Errorf("find mentioned users: %v", err)
  1650. }
  1651. for _, user := range unchecked {
  1652. if already := resolved[user.LowerName]; already || user.IsOrganization() {
  1653. continue
  1654. }
  1655. // Normal users must have read access to the referencing issue
  1656. perm, err := getUserRepoPermission(ctx.e, issue.Repo, user)
  1657. if err != nil {
  1658. return nil, fmt.Errorf("getUserRepoPermission [%d]: %v", user.ID, err)
  1659. }
  1660. if !perm.CanReadIssuesOrPulls(issue.IsPull) {
  1661. continue
  1662. }
  1663. users = append(users, user)
  1664. }
  1665. return
  1666. }
  1667. // UpdateIssuesMigrationsByType updates all migrated repositories' issues from gitServiceType to replace originalAuthorID to posterID
  1668. func UpdateIssuesMigrationsByType(gitServiceType structs.GitServiceType, originalAuthorID string, posterID int64) error {
  1669. _, err := x.Table("issue").
  1670. Where("repo_id IN (SELECT id FROM repository WHERE original_service_type = ?)", gitServiceType).
  1671. And("original_author_id = ?", originalAuthorID).
  1672. Update(map[string]interface{}{
  1673. "poster_id": posterID,
  1674. "original_author": "",
  1675. "original_author_id": 0,
  1676. })
  1677. return err
  1678. }
  1679. // UpdateReactionsMigrationsByType updates all migrated repositories' reactions from gitServiceType to replace originalAuthorID to posterID
  1680. func UpdateReactionsMigrationsByType(gitServiceType structs.GitServiceType, originalAuthorID string, userID int64) error {
  1681. _, err := x.Table("reaction").
  1682. Where("original_author_id = ?", originalAuthorID).
  1683. And(migratedIssueCond(gitServiceType)).
  1684. Update(map[string]interface{}{
  1685. "user_id": userID,
  1686. "original_author": "",
  1687. "original_author_id": 0,
  1688. })
  1689. return err
  1690. }
  1691. func deleteIssuesByRepoID(sess Engine, repoID int64) (attachmentPaths []string, err error) {
  1692. deleteCond := builder.Select("id").From("issue").Where(builder.Eq{"issue.repo_id": repoID})
  1693. // Delete comments and attachments
  1694. if _, err = sess.In("issue_id", deleteCond).
  1695. Delete(&Comment{}); err != nil {
  1696. return
  1697. }
  1698. // Dependencies for issues in this repository
  1699. if _, err = sess.In("issue_id", deleteCond).
  1700. Delete(&IssueDependency{}); err != nil {
  1701. return
  1702. }
  1703. // Delete dependencies for issues in other repositories
  1704. if _, err = sess.In("dependency_id", deleteCond).
  1705. Delete(&IssueDependency{}); err != nil {
  1706. return
  1707. }
  1708. if _, err = sess.In("issue_id", deleteCond).
  1709. Delete(&IssueUser{}); err != nil {
  1710. return
  1711. }
  1712. if _, err = sess.In("issue_id", deleteCond).
  1713. Delete(&Reaction{}); err != nil {
  1714. return
  1715. }
  1716. if _, err = sess.In("issue_id", deleteCond).
  1717. Delete(&IssueWatch{}); err != nil {
  1718. return
  1719. }
  1720. if _, err = sess.In("issue_id", deleteCond).
  1721. Delete(&Stopwatch{}); err != nil {
  1722. return
  1723. }
  1724. if _, err = sess.In("issue_id", deleteCond).
  1725. Delete(&TrackedTime{}); err != nil {
  1726. return
  1727. }
  1728. if _, err = sess.In("issue_id", deleteCond).
  1729. Delete(&ProjectIssue{}); err != nil {
  1730. return
  1731. }
  1732. if _, err = sess.In("dependent_issue_id", deleteCond).
  1733. Delete(&Comment{}); err != nil {
  1734. return
  1735. }
  1736. var attachments []*Attachment
  1737. if err = sess.In("issue_id", deleteCond).
  1738. Find(&attachments); err != nil {
  1739. return
  1740. }
  1741. for j := range attachments {
  1742. attachmentPaths = append(attachmentPaths, attachments[j].RelativePath())
  1743. }
  1744. if _, err = sess.In("issue_id", deleteCond).
  1745. Delete(&Attachment{}); err != nil {
  1746. return
  1747. }
  1748. if _, err = sess.Delete(&Issue{RepoID: repoID}); err != nil {
  1749. return
  1750. }
  1751. return
  1752. }