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.

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