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

issue.go 57 kB

11 years ago
Allow cross-repository dependencies on issues (#7901) * in progress changes for #7405, added ability to add cross-repo dependencies * removed unused repolink var * fixed query that was breaking ci tests; fixed check in issue dependency add so that the id of the issue and dependency is checked rather than the indexes * reverted removal of string in local files becasue these are done via crowdin, not updated manually * removed 'Select("issue.*")' from getBlockedByDependencies and getBlockingDependencies based on comments in PR review * changed getBlockedByDependencies and getBlockingDependencies to use a more xorm-like query, also updated the sidebar as a result * simplified the getBlockingDependencies and getBlockedByDependencies methods; changed the sidebar to show the dependencies in a different format where you can see the name of the repository * made some changes to the issue view in the dependencies (issue name on top, repo full name on separate line). Change view of issue in the dependency search results (also showing the full repo name on separate line) * replace call to FindUserAccessibleRepoIDs with SearchRepositoryByName. The former was hardcoded to use isPrivate = false on the repo search, but this code needed it to be true. The SearchRepositoryByName method is used more in the code including on the user's dashboard * some more tweaks to the layout of the issues when showing dependencies and in the search box when you add new dependencies * added Name to the RepositoryMeta struct * updated swagger doc * fixed total count for link header on SearchIssues * fixed indentation * fixed aligment of remove icon on dependencies in issue sidebar * removed unnecessary nil check (unnecessary because issue.loadRepo is called prior to this block) * reverting .css change, somehow missed or forgot that less is used * updated less file and generated css; updated sidebar template with styles to line up delete and issue index * added ordering to the blocked by/depends on queries * fixed sorting in issue dependency search and the depends on/blocks views to show issues from the current repo first, then by created date descending; added a "all cross repository dependencies" setting to allow this feature to be turned off, if turned off, the issue dependency search will work the way it did before (restricted to the current repository) * re-applied my swagger changes after merge * fixed split string condition in issue search * changed ALLOW_CROSS_REPOSITORY_DEPENDENCIES description to sound more global than just the issue dependency search; returning 400 in the cross repo issue search api method if not enabled; fixed bug where the issue count did not respect the state parameter * when adding a dependency to an issue, added a check to make sure the issue and dependency are in the same repo if cross repo dependencies is not enabled * updated sortIssuesSession call in PullRequests, another commit moved this method from pull.go to pull_list.go so I had to re-apply my change here * fixed incorrect setting of user id parameter in search repos call
5 years ago
11 years ago
11 years ago
Issue due date (#3794) * Started adding deadline to ui * Implemented basic issue due date managing * Improved UI for due date managing * Added at least write access to the repo in order to modify issue due dates * Ui improvements * Added issue comments creation when adding/modifying/removing a due date * Show due date in issue list * Added api support for issue due dates * Fixed lint suggestions * Added deadline to sdk * Updated css * Added support for adding/modifiying deadlines for pull requests via api * Fixed comments not created when updating or removing a deadline * update sdk (will do properly once go-gitea/go-sdk#103 is merged) * enhanced updateIssueDeadline * Removed unnessecary Issue.DeadlineString * UI improvements * Small improvments to comment creation + ui & validation improvements * Check if an issue is overdue is now a seperate function * Updated go-sdk with govendor as it was merged * Simplified isOverdue method * removed unessecary deadline to 0 set * Update swagger definitions * Added missing return * Added an explanary comment * Improved updateIssueDeadline method so it'll only update `deadline_unix` * Small changes and improvements * no need to explicitly load the issue when updating a deadline, just use whats already there * small optimisations * Added check if a deadline was modified before updating it * Moved comment creating logic into its own function * Code cleanup for creating deadline comment * locale improvement * When modifying a deadline, the old deadline is saved with the comment * small improvments to xorm session handling when updating an issue deadline + style nitpicks * style nitpicks * Moved checking for if the user has write acces to middleware
7 years ago
Shows total tracked time in issue and milestone list (#3341) * Show total tracked time in issue and milestone list Show total tracked time at issue page Signed-off-by: Jonas Franz <info@jonasfranz.software> * Optimizing TotalTimes by using SumInt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fixing wrong total times for milestones caused by a missing JOIN Adding unit tests for total times Signed-off-by: Jonas Franz <info@jonasfranz.software> * Logging error instead of ignoring it Signed-off-by: Jonas Franz <info@jonasfranz.software> * Correcting spelling mistakes Signed-off-by: Jonas Franz <info@jonasfranz.software> * Change error message to a short version Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add error handling to TotalTimes Add variable for totalTimes Signed-off-by: Jonas Franz <info@jonasfranz.de> * Introduce TotalTrackedTimes as variable of issue Load TotalTrackedTimes by loading attributes of IssueList Load TotalTrackedTimes by loading attributes of single issue Add Sec2Time as helper to use it in templates Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fixed test + gofmt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Load TotalTrackedTimes via MilestoneList instead of single requests Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add documentation for MilestoneList Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add documentation for MilestoneList Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix test Signed-off-by: Jonas Franz <info@jonasfranz.software> * Change comment from SQL query to description Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix unit test by using int64 instead of int Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix unit test by using int64 instead of int Signed-off-by: Jonas Franz <info@jonasfranz.software> * Check if timetracker is enabled Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix test by enabling timetracking Signed-off-by: Jonas Franz <info@jonasfranz.de>
7 years ago
Shows total tracked time in issue and milestone list (#3341) * Show total tracked time in issue and milestone list Show total tracked time at issue page Signed-off-by: Jonas Franz <info@jonasfranz.software> * Optimizing TotalTimes by using SumInt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fixing wrong total times for milestones caused by a missing JOIN Adding unit tests for total times Signed-off-by: Jonas Franz <info@jonasfranz.software> * Logging error instead of ignoring it Signed-off-by: Jonas Franz <info@jonasfranz.software> * Correcting spelling mistakes Signed-off-by: Jonas Franz <info@jonasfranz.software> * Change error message to a short version Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add error handling to TotalTimes Add variable for totalTimes Signed-off-by: Jonas Franz <info@jonasfranz.de> * Introduce TotalTrackedTimes as variable of issue Load TotalTrackedTimes by loading attributes of IssueList Load TotalTrackedTimes by loading attributes of single issue Add Sec2Time as helper to use it in templates Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fixed test + gofmt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Load TotalTrackedTimes via MilestoneList instead of single requests Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add documentation for MilestoneList Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add documentation for MilestoneList Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix test Signed-off-by: Jonas Franz <info@jonasfranz.software> * Change comment from SQL query to description Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix unit test by using int64 instead of int Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix unit test by using int64 instead of int Signed-off-by: Jonas Franz <info@jonasfranz.software> * Check if timetracker is enabled Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix test by enabling timetracking Signed-off-by: Jonas Franz <info@jonasfranz.de>
7 years ago
Issue due date (#3794) * Started adding deadline to ui * Implemented basic issue due date managing * Improved UI for due date managing * Added at least write access to the repo in order to modify issue due dates * Ui improvements * Added issue comments creation when adding/modifying/removing a due date * Show due date in issue list * Added api support for issue due dates * Fixed lint suggestions * Added deadline to sdk * Updated css * Added support for adding/modifiying deadlines for pull requests via api * Fixed comments not created when updating or removing a deadline * update sdk (will do properly once go-gitea/go-sdk#103 is merged) * enhanced updateIssueDeadline * Removed unnessecary Issue.DeadlineString * UI improvements * Small improvments to comment creation + ui & validation improvements * Check if an issue is overdue is now a seperate function * Updated go-sdk with govendor as it was merged * Simplified isOverdue method * removed unessecary deadline to 0 set * Update swagger definitions * Added missing return * Added an explanary comment * Improved updateIssueDeadline method so it'll only update `deadline_unix` * Small changes and improvements * no need to explicitly load the issue when updating a deadline, just use whats already there * small optimisations * Added check if a deadline was modified before updating it * Moved comment creating logic into its own function * Code cleanup for creating deadline comment * locale improvement * When modifying a deadline, the old deadline is saved with the comment * small improvments to xorm session handling when updating an issue deadline + style nitpicks * style nitpicks * Moved checking for if the user has write acces to middleware
7 years ago
Issue due date (#3794) * Started adding deadline to ui * Implemented basic issue due date managing * Improved UI for due date managing * Added at least write access to the repo in order to modify issue due dates * Ui improvements * Added issue comments creation when adding/modifying/removing a due date * Show due date in issue list * Added api support for issue due dates * Fixed lint suggestions * Added deadline to sdk * Updated css * Added support for adding/modifiying deadlines for pull requests via api * Fixed comments not created when updating or removing a deadline * update sdk (will do properly once go-gitea/go-sdk#103 is merged) * enhanced updateIssueDeadline * Removed unnessecary Issue.DeadlineString * UI improvements * Small improvments to comment creation + ui & validation improvements * Check if an issue is overdue is now a seperate function * Updated go-sdk with govendor as it was merged * Simplified isOverdue method * removed unessecary deadline to 0 set * Update swagger definitions * Added missing return * Added an explanary comment * Improved updateIssueDeadline method so it'll only update `deadline_unix` * Small changes and improvements * no need to explicitly load the issue when updating a deadline, just use whats already there * small optimisations * Added check if a deadline was modified before updating it * Moved comment creating logic into its own function * Code cleanup for creating deadline comment * locale improvement * When modifying a deadline, the old deadline is saved with the comment * small improvments to xorm session handling when updating an issue deadline + style nitpicks * style nitpicks * Moved checking for if the user has write acces to middleware
7 years ago
Shows total tracked time in issue and milestone list (#3341) * Show total tracked time in issue and milestone list Show total tracked time at issue page Signed-off-by: Jonas Franz <info@jonasfranz.software> * Optimizing TotalTimes by using SumInt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fixing wrong total times for milestones caused by a missing JOIN Adding unit tests for total times Signed-off-by: Jonas Franz <info@jonasfranz.software> * Logging error instead of ignoring it Signed-off-by: Jonas Franz <info@jonasfranz.software> * Correcting spelling mistakes Signed-off-by: Jonas Franz <info@jonasfranz.software> * Change error message to a short version Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add error handling to TotalTimes Add variable for totalTimes Signed-off-by: Jonas Franz <info@jonasfranz.de> * Introduce TotalTrackedTimes as variable of issue Load TotalTrackedTimes by loading attributes of IssueList Load TotalTrackedTimes by loading attributes of single issue Add Sec2Time as helper to use it in templates Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fixed test + gofmt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Load TotalTrackedTimes via MilestoneList instead of single requests Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add documentation for MilestoneList Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add documentation for MilestoneList Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix test Signed-off-by: Jonas Franz <info@jonasfranz.software> * Change comment from SQL query to description Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix unit test by using int64 instead of int Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix unit test by using int64 instead of int Signed-off-by: Jonas Franz <info@jonasfranz.software> * Check if timetracker is enabled Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix test by enabling timetracking Signed-off-by: Jonas Franz <info@jonasfranz.de>
7 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
Shows total tracked time in issue and milestone list (#3341) * Show total tracked time in issue and milestone list Show total tracked time at issue page Signed-off-by: Jonas Franz <info@jonasfranz.software> * Optimizing TotalTimes by using SumInt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fixing wrong total times for milestones caused by a missing JOIN Adding unit tests for total times Signed-off-by: Jonas Franz <info@jonasfranz.software> * Logging error instead of ignoring it Signed-off-by: Jonas Franz <info@jonasfranz.software> * Correcting spelling mistakes Signed-off-by: Jonas Franz <info@jonasfranz.software> * Change error message to a short version Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add error handling to TotalTimes Add variable for totalTimes Signed-off-by: Jonas Franz <info@jonasfranz.de> * Introduce TotalTrackedTimes as variable of issue Load TotalTrackedTimes by loading attributes of IssueList Load TotalTrackedTimes by loading attributes of single issue Add Sec2Time as helper to use it in templates Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fixed test + gofmt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Load TotalTrackedTimes via MilestoneList instead of single requests Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add documentation for MilestoneList Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add documentation for MilestoneList Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix test Signed-off-by: Jonas Franz <info@jonasfranz.software> * Change comment from SQL query to description Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix unit test by using int64 instead of int Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix unit test by using int64 instead of int Signed-off-by: Jonas Franz <info@jonasfranz.software> * Check if timetracker is enabled Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix test by enabling timetracking Signed-off-by: Jonas Franz <info@jonasfranz.de>
7 years ago
Shows total tracked time in issue and milestone list (#3341) * Show total tracked time in issue and milestone list Show total tracked time at issue page Signed-off-by: Jonas Franz <info@jonasfranz.software> * Optimizing TotalTimes by using SumInt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fixing wrong total times for milestones caused by a missing JOIN Adding unit tests for total times Signed-off-by: Jonas Franz <info@jonasfranz.software> * Logging error instead of ignoring it Signed-off-by: Jonas Franz <info@jonasfranz.software> * Correcting spelling mistakes Signed-off-by: Jonas Franz <info@jonasfranz.software> * Change error message to a short version Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add error handling to TotalTimes Add variable for totalTimes Signed-off-by: Jonas Franz <info@jonasfranz.de> * Introduce TotalTrackedTimes as variable of issue Load TotalTrackedTimes by loading attributes of IssueList Load TotalTrackedTimes by loading attributes of single issue Add Sec2Time as helper to use it in templates Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fixed test + gofmt Signed-off-by: Jonas Franz <info@jonasfranz.software> * Load TotalTrackedTimes via MilestoneList instead of single requests Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add documentation for MilestoneList Signed-off-by: Jonas Franz <info@jonasfranz.software> * Add documentation for MilestoneList Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix test Signed-off-by: Jonas Franz <info@jonasfranz.software> * Change comment from SQL query to description Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix unit test by using int64 instead of int Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix unit test by using int64 instead of int Signed-off-by: Jonas Franz <info@jonasfranz.software> * Check if timetracker is enabled Signed-off-by: Jonas Franz <info@jonasfranz.software> * Fix test by enabling timetracking Signed-off-by: Jonas Franz <info@jonasfranz.de>
7 years ago
9 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
Add Organization Wide Labels (#10814) * Add organization wide labels Implement organization wide labels similar to organization wide webhooks. This lets you create individual labels for organizations that can be used for all repos under that organization (so being able to reuse the same label across multiple repos). This makes it possible for small organizations with many repos to use labels effectively. Fixes #7406 * Add migration * remove comments * fix tests * Update options/locale/locale_en-US.ini Removed unused translation string * show org labels in issue search label filter * Use more clear var name * rename migration after merge from master * comment typo * update migration again after rebase with master * check for orgID <=0 per guillep2k review * fmt * Apply suggestions from code review Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> * remove unused code * Make sure RepoID is 0 when searching orgID per code review * more changes/code review requests * More descriptive translation var per code review * func description/delete comment when issue label deleted instead of hiding it * remove comment * only use issues in that repo when calculating number of open issues for org label on repo label page * Add integration test for IssuesSearch API with labels * remove unused function * Update models/issue_label.go Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> * Use subquery in GetLabelIDsInReposByNames * Fix tests to use correct orgID * fix more tests * IssuesSearch api now uses new BuildLabelNamesIssueIDsCondition. Add a few more tests as well * update comment for clarity * Revert previous code change now that we can use the new BuildLabelNamesIssueIDsCondition * Don't sort repos by date in IssuesSearch API After much debugging I've found a strange issue where in some cases MySQL will return a different result than other enigines if a query is sorted by a null collumn. For example with our integration test data where we don't set updated_unix in repository fixtures: SELECT `id`, `owner_id`, `owner_name`, `lower_name`, `name`, `description`, `website`, `original_service_type`, `original_url`, `default_branch`, `num_watches`, `num_stars`, `num_forks`, `num_issues`, `num_closed_issues`, `num_pulls`, `num_closed_pulls`, `num_milestones`, `num_closed_milestones`, `is_private`, `is_empty`, `is_archived`, `is_mirror`, `status`, `is_fork`, `fork_id`, `is_template`, `template_id`, `size`, `is_fsck_enabled`, `close_issues_via_commit_in_any_branch`, `topics`, `avatar`, `created_unix`, `updated_unix` FROM `repository` ORDER BY updated_unix DESC LIMIT 15 OFFSET 45 Returns different results for MySQL than other engines. However, the similar query: SELECT `id`, `owner_id`, `owner_name`, `lower_name`, `name`, `description`, `website`, `original_service_type`, `original_url`, `default_branch`, `num_watches`, `num_stars`, `num_forks`, `num_issues`, `num_closed_issues`, `num_pulls`, `num_closed_pulls`, `num_milestones`, `num_closed_milestones`, `is_private`, `is_empty`, `is_archived`, `is_mirror`, `status`, `is_fork`, `fork_id`, `is_template`, `template_id`, `size`, `is_fsck_enabled`, `close_issues_via_commit_in_any_branch`, `topics`, `avatar`, `created_unix`, `updated_unix` FROM `repository` ORDER BY updated_unix DESC LIMIT 15 OFFSET 30 Returns the same results. This causes integration tests to fail on MySQL in certain cases but would never show up in a real installation. Since this API call always returns issues based on the optionally provided repo_priority_id or the issueID itself, there is no change to results by changing the repo sorting method used to get ids earlier in the function. * linter is back! * code review * remove now unused option * Fix newline at end of files * more unused code * update to master * check for matching ids before query * Update models/issue_label.go Co-Authored-By: 6543 <6543@obermui.de> * Update models/issue_label.go * update comments * Update routers/org/setting.go Co-authored-by: Lauris BH <lauris@nix.lv> Co-authored-by: guillep2k <18600385+guillep2k@users.noreply.github.com> Co-authored-by: 6543 <6543@obermui.de>
5 years ago
8 years ago
8 years ago
Add Organization Wide Labels (#10814) * Add organization wide labels Implement organization wide labels similar to organization wide webhooks. This lets you create individual labels for organizations that can be used for all repos under that organization (so being able to reuse the same label across multiple repos). This makes it possible for small organizations with many repos to use labels effectively. Fixes #7406 * Add migration * remove comments * fix tests * Update options/locale/locale_en-US.ini Removed unused translation string * show org labels in issue search label filter * Use more clear var name * rename migration after merge from master * comment typo * update migration again after rebase with master * check for orgID <=0 per guillep2k review * fmt * Apply suggestions from code review Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> * remove unused code * Make sure RepoID is 0 when searching orgID per code review * more changes/code review requests * More descriptive translation var per code review * func description/delete comment when issue label deleted instead of hiding it * remove comment * only use issues in that repo when calculating number of open issues for org label on repo label page * Add integration test for IssuesSearch API with labels * remove unused function * Update models/issue_label.go Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> * Use subquery in GetLabelIDsInReposByNames * Fix tests to use correct orgID * fix more tests * IssuesSearch api now uses new BuildLabelNamesIssueIDsCondition. Add a few more tests as well * update comment for clarity * Revert previous code change now that we can use the new BuildLabelNamesIssueIDsCondition * Don't sort repos by date in IssuesSearch API After much debugging I've found a strange issue where in some cases MySQL will return a different result than other enigines if a query is sorted by a null collumn. For example with our integration test data where we don't set updated_unix in repository fixtures: SELECT `id`, `owner_id`, `owner_name`, `lower_name`, `name`, `description`, `website`, `original_service_type`, `original_url`, `default_branch`, `num_watches`, `num_stars`, `num_forks`, `num_issues`, `num_closed_issues`, `num_pulls`, `num_closed_pulls`, `num_milestones`, `num_closed_milestones`, `is_private`, `is_empty`, `is_archived`, `is_mirror`, `status`, `is_fork`, `fork_id`, `is_template`, `template_id`, `size`, `is_fsck_enabled`, `close_issues_via_commit_in_any_branch`, `topics`, `avatar`, `created_unix`, `updated_unix` FROM `repository` ORDER BY updated_unix DESC LIMIT 15 OFFSET 45 Returns different results for MySQL than other engines. However, the similar query: SELECT `id`, `owner_id`, `owner_name`, `lower_name`, `name`, `description`, `website`, `original_service_type`, `original_url`, `default_branch`, `num_watches`, `num_stars`, `num_forks`, `num_issues`, `num_closed_issues`, `num_pulls`, `num_closed_pulls`, `num_milestones`, `num_closed_milestones`, `is_private`, `is_empty`, `is_archived`, `is_mirror`, `status`, `is_fork`, `fork_id`, `is_template`, `template_id`, `size`, `is_fsck_enabled`, `close_issues_via_commit_in_any_branch`, `topics`, `avatar`, `created_unix`, `updated_unix` FROM `repository` ORDER BY updated_unix DESC LIMIT 15 OFFSET 30 Returns the same results. This causes integration tests to fail on MySQL in certain cases but would never show up in a real installation. Since this API call always returns issues based on the optionally provided repo_priority_id or the issueID itself, there is no change to results by changing the repo sorting method used to get ids earlier in the function. * linter is back! * code review * remove now unused option * Fix newline at end of files * more unused code * update to master * check for matching ids before query * Update models/issue_label.go Co-Authored-By: 6543 <6543@obermui.de> * Update models/issue_label.go * update comments * Update routers/org/setting.go Co-authored-by: Lauris BH <lauris@nix.lv> Co-authored-by: guillep2k <18600385+guillep2k@users.noreply.github.com> Co-authored-by: 6543 <6543@obermui.de>
5 years ago
11 years ago
API add/generalize pagination (#9452) * paginate results * fixed deadlock * prevented breaking change * updated swagger * go fmt * fixed find topic * go mod tidy * go mod vendor with go1.13.5 * fixed repo find topics * fixed unit test * added Limit method to Engine struct; use engine variable when provided; fixed gitignore * use ItemsPerPage for default pagesize; fix GetWatchers, getOrgUsersByOrgID and GetStargazers; fix GetAllCommits headers; reverted some changed behaviors * set Page value on Home route * improved memory allocations * fixed response headers * removed logfiles * fixed import order * import order * improved swagger * added function to get models.ListOptions from context * removed pagesize diff on unit test * fixed imports * removed unnecessary struct field * fixed go fmt * scoped PR * code improvements * code improvements * go mod tidy * fixed import order * fixed commit statuses session * fixed files headers * fixed headers; added pagination for notifications * go mod tidy * go fmt * removed Private from user search options; added setting.UI.IssuePagingNum as default valeu on repo's issues list * Apply suggestions from code review Co-Authored-By: 6543 <6543@obermui.de> Co-Authored-By: zeripath <art27@cantab.net> * fixed build error * CI.restart() * fixed merge conflicts resolve * fixed conflicts resolve * improved FindTrackedTimesOptions.ToOptions() method * added backwards compatibility on ListReleases request; fixed issue tracked time ToSession * fixed build error; fixed swagger template * fixed swagger template * fixed ListReleases backwards compatibility * added page to user search route Co-authored-by: techknowlogick <matti@mdranta.net> Co-authored-by: 6543 <6543@obermui.de> Co-authored-by: zeripath <art27@cantab.net>
5 years ago
Allow cross-repository dependencies on issues (#7901) * in progress changes for #7405, added ability to add cross-repo dependencies * removed unused repolink var * fixed query that was breaking ci tests; fixed check in issue dependency add so that the id of the issue and dependency is checked rather than the indexes * reverted removal of string in local files becasue these are done via crowdin, not updated manually * removed 'Select("issue.*")' from getBlockedByDependencies and getBlockingDependencies based on comments in PR review * changed getBlockedByDependencies and getBlockingDependencies to use a more xorm-like query, also updated the sidebar as a result * simplified the getBlockingDependencies and getBlockedByDependencies methods; changed the sidebar to show the dependencies in a different format where you can see the name of the repository * made some changes to the issue view in the dependencies (issue name on top, repo full name on separate line). Change view of issue in the dependency search results (also showing the full repo name on separate line) * replace call to FindUserAccessibleRepoIDs with SearchRepositoryByName. The former was hardcoded to use isPrivate = false on the repo search, but this code needed it to be true. The SearchRepositoryByName method is used more in the code including on the user's dashboard * some more tweaks to the layout of the issues when showing dependencies and in the search box when you add new dependencies * added Name to the RepositoryMeta struct * updated swagger doc * fixed total count for link header on SearchIssues * fixed indentation * fixed aligment of remove icon on dependencies in issue sidebar * removed unnecessary nil check (unnecessary because issue.loadRepo is called prior to this block) * reverting .css change, somehow missed or forgot that less is used * updated less file and generated css; updated sidebar template with styles to line up delete and issue index * added ordering to the blocked by/depends on queries * fixed sorting in issue dependency search and the depends on/blocks views to show issues from the current repo first, then by created date descending; added a "all cross repository dependencies" setting to allow this feature to be turned off, if turned off, the issue dependency search will work the way it did before (restricted to the current repository) * re-applied my swagger changes after merge * fixed split string condition in issue search * changed ALLOW_CROSS_REPOSITORY_DEPENDENCIES description to sound more global than just the issue dependency search; returning 400 in the cross repo issue search api method if not enabled; fixed bug where the issue count did not respect the state parameter * when adding a dependency to an issue, added a check to make sure the issue and dependency are in the same repo if cross repo dependencies is not enabled * updated sortIssuesSession call in PullRequests, another commit moved this method from pull.go to pull_list.go so I had to re-apply my change here * fixed incorrect setting of user id parameter in search repos call
5 years ago
Allow cross-repository dependencies on issues (#7901) * in progress changes for #7405, added ability to add cross-repo dependencies * removed unused repolink var * fixed query that was breaking ci tests; fixed check in issue dependency add so that the id of the issue and dependency is checked rather than the indexes * reverted removal of string in local files becasue these are done via crowdin, not updated manually * removed 'Select("issue.*")' from getBlockedByDependencies and getBlockingDependencies based on comments in PR review * changed getBlockedByDependencies and getBlockingDependencies to use a more xorm-like query, also updated the sidebar as a result * simplified the getBlockingDependencies and getBlockedByDependencies methods; changed the sidebar to show the dependencies in a different format where you can see the name of the repository * made some changes to the issue view in the dependencies (issue name on top, repo full name on separate line). Change view of issue in the dependency search results (also showing the full repo name on separate line) * replace call to FindUserAccessibleRepoIDs with SearchRepositoryByName. The former was hardcoded to use isPrivate = false on the repo search, but this code needed it to be true. The SearchRepositoryByName method is used more in the code including on the user's dashboard * some more tweaks to the layout of the issues when showing dependencies and in the search box when you add new dependencies * added Name to the RepositoryMeta struct * updated swagger doc * fixed total count for link header on SearchIssues * fixed indentation * fixed aligment of remove icon on dependencies in issue sidebar * removed unnecessary nil check (unnecessary because issue.loadRepo is called prior to this block) * reverting .css change, somehow missed or forgot that less is used * updated less file and generated css; updated sidebar template with styles to line up delete and issue index * added ordering to the blocked by/depends on queries * fixed sorting in issue dependency search and the depends on/blocks views to show issues from the current repo first, then by created date descending; added a "all cross repository dependencies" setting to allow this feature to be turned off, if turned off, the issue dependency search will work the way it did before (restricted to the current repository) * re-applied my swagger changes after merge * fixed split string condition in issue search * changed ALLOW_CROSS_REPOSITORY_DEPENDENCIES description to sound more global than just the issue dependency search; returning 400 in the cross repo issue search api method if not enabled; fixed bug where the issue count did not respect the state parameter * when adding a dependency to an issue, added a check to make sure the issue and dependency are in the same repo if cross repo dependencies is not enabled * updated sortIssuesSession call in PullRequests, another commit moved this method from pull.go to pull_list.go so I had to re-apply my change here * fixed incorrect setting of user id parameter in search repos call
5 years ago
Allow cross-repository dependencies on issues (#7901) * in progress changes for #7405, added ability to add cross-repo dependencies * removed unused repolink var * fixed query that was breaking ci tests; fixed check in issue dependency add so that the id of the issue and dependency is checked rather than the indexes * reverted removal of string in local files becasue these are done via crowdin, not updated manually * removed 'Select("issue.*")' from getBlockedByDependencies and getBlockingDependencies based on comments in PR review * changed getBlockedByDependencies and getBlockingDependencies to use a more xorm-like query, also updated the sidebar as a result * simplified the getBlockingDependencies and getBlockedByDependencies methods; changed the sidebar to show the dependencies in a different format where you can see the name of the repository * made some changes to the issue view in the dependencies (issue name on top, repo full name on separate line). Change view of issue in the dependency search results (also showing the full repo name on separate line) * replace call to FindUserAccessibleRepoIDs with SearchRepositoryByName. The former was hardcoded to use isPrivate = false on the repo search, but this code needed it to be true. The SearchRepositoryByName method is used more in the code including on the user's dashboard * some more tweaks to the layout of the issues when showing dependencies and in the search box when you add new dependencies * added Name to the RepositoryMeta struct * updated swagger doc * fixed total count for link header on SearchIssues * fixed indentation * fixed aligment of remove icon on dependencies in issue sidebar * removed unnecessary nil check (unnecessary because issue.loadRepo is called prior to this block) * reverting .css change, somehow missed or forgot that less is used * updated less file and generated css; updated sidebar template with styles to line up delete and issue index * added ordering to the blocked by/depends on queries * fixed sorting in issue dependency search and the depends on/blocks views to show issues from the current repo first, then by created date descending; added a "all cross repository dependencies" setting to allow this feature to be turned off, if turned off, the issue dependency search will work the way it did before (restricted to the current repository) * re-applied my swagger changes after merge * fixed split string condition in issue search * changed ALLOW_CROSS_REPOSITORY_DEPENDENCIES description to sound more global than just the issue dependency search; returning 400 in the cross repo issue search api method if not enabled; fixed bug where the issue count did not respect the state parameter * when adding a dependency to an issue, added a check to make sure the issue and dependency are in the same repo if cross repo dependencies is not enabled * updated sortIssuesSession call in PullRequests, another commit moved this method from pull.go to pull_list.go so I had to re-apply my change here * fixed incorrect setting of user id parameter in search repos call
5 years ago
11 years ago
11 years ago
issue search on my related repositories (#9758) * adding search capability to user's issues dashboard * global issue search * placement of search bar on issues dashboard * fixed some bugs in the issue dashboard search * added unit test because IssueIDs option was added to UserIssueStatsOptions * some renaming of fields in the issue dashboard code to be more clear; also trying to fix issue of searching the right repos based on the filter * added unit test fro GetRepoIDsForIssuesOptions; fixed search lost on pagination; using shown issue status for open/close count; removed some debugging * fix issue with all count showing incorrectly * removed todo comment left in by mistake * typo pulling wrong count * fxied all count being off when selecting repositories * setting the opts.IsClosed after pulling repos to search, this is done so that the list of repo ids to serach for the keyword is not limited, we need to get all the issue ids for the shown issue stats * added "accessibleRepositoryCondition" check on the query to pull the repo ids to search for issues, this is an added protection to ensure we don't search repos the user does not have access to * added code so that in the issues search, we won't use an in clause of issues ids that goes over 1000 * fixed unit test * using 950 as the limit for issue search, removed unneeded group by in GetRepoIDsForIssuesOptions, showing search on pulls dashboard page too (not just issues) Co-authored-by: guillep2k <18600385+guillep2k@users.noreply.github.com>
5 years ago
Allow cross-repository dependencies on issues (#7901) * in progress changes for #7405, added ability to add cross-repo dependencies * removed unused repolink var * fixed query that was breaking ci tests; fixed check in issue dependency add so that the id of the issue and dependency is checked rather than the indexes * reverted removal of string in local files becasue these are done via crowdin, not updated manually * removed 'Select("issue.*")' from getBlockedByDependencies and getBlockingDependencies based on comments in PR review * changed getBlockedByDependencies and getBlockingDependencies to use a more xorm-like query, also updated the sidebar as a result * simplified the getBlockingDependencies and getBlockedByDependencies methods; changed the sidebar to show the dependencies in a different format where you can see the name of the repository * made some changes to the issue view in the dependencies (issue name on top, repo full name on separate line). Change view of issue in the dependency search results (also showing the full repo name on separate line) * replace call to FindUserAccessibleRepoIDs with SearchRepositoryByName. The former was hardcoded to use isPrivate = false on the repo search, but this code needed it to be true. The SearchRepositoryByName method is used more in the code including on the user's dashboard * some more tweaks to the layout of the issues when showing dependencies and in the search box when you add new dependencies * added Name to the RepositoryMeta struct * updated swagger doc * fixed total count for link header on SearchIssues * fixed indentation * fixed aligment of remove icon on dependencies in issue sidebar * removed unnecessary nil check (unnecessary because issue.loadRepo is called prior to this block) * reverting .css change, somehow missed or forgot that less is used * updated less file and generated css; updated sidebar template with styles to line up delete and issue index * added ordering to the blocked by/depends on queries * fixed sorting in issue dependency search and the depends on/blocks views to show issues from the current repo first, then by created date descending; added a "all cross repository dependencies" setting to allow this feature to be turned off, if turned off, the issue dependency search will work the way it did before (restricted to the current repository) * re-applied my swagger changes after merge * fixed split string condition in issue search * changed ALLOW_CROSS_REPOSITORY_DEPENDENCIES description to sound more global than just the issue dependency search; returning 400 in the cross repo issue search api method if not enabled; fixed bug where the issue count did not respect the state parameter * when adding a dependency to an issue, added a check to make sure the issue and dependency are in the same repo if cross repo dependencies is not enabled * updated sortIssuesSession call in PullRequests, another commit moved this method from pull.go to pull_list.go so I had to re-apply my change here * fixed incorrect setting of user id parameter in search repos call
5 years ago
11 years ago
[UI] IssuePage multi repo select (#8741) * Make repository list @ issues/PR page persist Will partially fix #6355 * Enable multiple selections in repo list @ issues/PR page Part of issue #6355 * Add RepoIDs to UserIssueStatsOptions to make "type" count correct when selecting one/multiple repos. * Replace variable "repo" with list "repos[]" and enable multiple selections of repositories from list by including/excluding RepoIDs in list. * * Remove redundant code * Add 'All' button Improves functionality of the page, so that backtracking is not necessary to reset the page * Remove redundant variable Completely replace 'RepoID' with 'RepoIDs' and remove redundant code * Add RepoIDs to label link * Revert part of code to previous version to troubleshoot build failure * Implement old and new pieces of code whilst adhering to multi select * Attempt to join the two versions Last commit passed tests but doesn't work in practice, this works in practice and hopefully passes the tests. * Update tests to desired state * Fix pagination implementation and tests * Pass repoIDs as `repos=[1,2,3...]` instead of several `repos[]=..` * Update tests file to reflect new functionality * Update template with new `repos` format * Implement new solution to show constant "total issues" count for "All" button * Correct behavior when passing zero to array * Comment out test url returning 404 This keeps returning 404 in the test despite working in practice, for the sake of running more tests I am commenting it out * Comment out another test url returning 404 Last attempt, if more tests crash I will uncomment the urls and request assistance. * Reenable tests and test fix * Re-enable tests * Make selecting "In your repositories" reset selection as passing IDs of repos belonging to other profiles causes breakage * Remove unnecessary (with multi-selection enable) code * Drop repo from repo map and total count if permission denied * Remove extra parenthesis * make template work again * find bug! * forgot the '#' at bugfixing * delete unused RepoID * compile regex only one time * make fmt * local variable = capital letter lower * check if repos query pattern is correct * pagination remove last , - make regex work again * use Replace instead of ReplaceAll; del delete * fix test * how did this test binary got in?!? dont forgot the "-p" at git add * ! * dont replace -> cut fisrt & last string Co-Authored-By: zeripath <art27@cantab.net> * jet another regex dont mind as long as it has the same result and is performatn ... Co-Authored-By: zeripath <art27@cantab.net> * dont use nonexisting repo for test * exclude /issues?type=created_by from test * add table to querys use same syntax in each query (table.colum) * add new issue for test * dont make a workaround or something else this need a refactor itself and is out of scope for this PR * fix misspell * CI.redo() * englisch txt update Co-Authored-By: zeripath <art27@cantab.net> * add sugestions * Tweak & Fix * CI.restart()
5 years ago
issue search on my related repositories (#9758) * adding search capability to user's issues dashboard * global issue search * placement of search bar on issues dashboard * fixed some bugs in the issue dashboard search * added unit test because IssueIDs option was added to UserIssueStatsOptions * some renaming of fields in the issue dashboard code to be more clear; also trying to fix issue of searching the right repos based on the filter * added unit test fro GetRepoIDsForIssuesOptions; fixed search lost on pagination; using shown issue status for open/close count; removed some debugging * fix issue with all count showing incorrectly * removed todo comment left in by mistake * typo pulling wrong count * fxied all count being off when selecting repositories * setting the opts.IsClosed after pulling repos to search, this is done so that the list of repo ids to serach for the keyword is not limited, we need to get all the issue ids for the shown issue stats * added "accessibleRepositoryCondition" check on the query to pull the repo ids to search for issues, this is an added protection to ensure we don't search repos the user does not have access to * added code so that in the issues search, we won't use an in clause of issues ids that goes over 1000 * fixed unit test * using 950 as the limit for issue search, removed unneeded group by in GetRepoIDsForIssuesOptions, showing search on pulls dashboard page too (not just issues) Co-authored-by: guillep2k <18600385+guillep2k@users.noreply.github.com>
5 years ago
[UI] IssuePage multi repo select (#8741) * Make repository list @ issues/PR page persist Will partially fix #6355 * Enable multiple selections in repo list @ issues/PR page Part of issue #6355 * Add RepoIDs to UserIssueStatsOptions to make "type" count correct when selecting one/multiple repos. * Replace variable "repo" with list "repos[]" and enable multiple selections of repositories from list by including/excluding RepoIDs in list. * * Remove redundant code * Add 'All' button Improves functionality of the page, so that backtracking is not necessary to reset the page * Remove redundant variable Completely replace 'RepoID' with 'RepoIDs' and remove redundant code * Add RepoIDs to label link * Revert part of code to previous version to troubleshoot build failure * Implement old and new pieces of code whilst adhering to multi select * Attempt to join the two versions Last commit passed tests but doesn't work in practice, this works in practice and hopefully passes the tests. * Update tests to desired state * Fix pagination implementation and tests * Pass repoIDs as `repos=[1,2,3...]` instead of several `repos[]=..` * Update tests file to reflect new functionality * Update template with new `repos` format * Implement new solution to show constant "total issues" count for "All" button * Correct behavior when passing zero to array * Comment out test url returning 404 This keeps returning 404 in the test despite working in practice, for the sake of running more tests I am commenting it out * Comment out another test url returning 404 Last attempt, if more tests crash I will uncomment the urls and request assistance. * Reenable tests and test fix * Re-enable tests * Make selecting "In your repositories" reset selection as passing IDs of repos belonging to other profiles causes breakage * Remove unnecessary (with multi-selection enable) code * Drop repo from repo map and total count if permission denied * Remove extra parenthesis * make template work again * find bug! * forgot the '#' at bugfixing * delete unused RepoID * compile regex only one time * make fmt * local variable = capital letter lower * check if repos query pattern is correct * pagination remove last , - make regex work again * use Replace instead of ReplaceAll; del delete * fix test * how did this test binary got in?!? dont forgot the "-p" at git add * ! * dont replace -> cut fisrt & last string Co-Authored-By: zeripath <art27@cantab.net> * jet another regex dont mind as long as it has the same result and is performatn ... Co-Authored-By: zeripath <art27@cantab.net> * dont use nonexisting repo for test * exclude /issues?type=created_by from test * add table to querys use same syntax in each query (table.colum) * add new issue for test * dont make a workaround or something else this need a refactor itself and is out of scope for this PR * fix misspell * CI.redo() * englisch txt update Co-Authored-By: zeripath <art27@cantab.net> * add sugestions * Tweak & Fix * CI.restart()
5 years ago
issue search on my related repositories (#9758) * adding search capability to user's issues dashboard * global issue search * placement of search bar on issues dashboard * fixed some bugs in the issue dashboard search * added unit test because IssueIDs option was added to UserIssueStatsOptions * some renaming of fields in the issue dashboard code to be more clear; also trying to fix issue of searching the right repos based on the filter * added unit test fro GetRepoIDsForIssuesOptions; fixed search lost on pagination; using shown issue status for open/close count; removed some debugging * fix issue with all count showing incorrectly * removed todo comment left in by mistake * typo pulling wrong count * fxied all count being off when selecting repositories * setting the opts.IsClosed after pulling repos to search, this is done so that the list of repo ids to serach for the keyword is not limited, we need to get all the issue ids for the shown issue stats * added "accessibleRepositoryCondition" check on the query to pull the repo ids to search for issues, this is an added protection to ensure we don't search repos the user does not have access to * added code so that in the issues search, we won't use an in clause of issues ids that goes over 1000 * fixed unit test * using 950 as the limit for issue search, removed unneeded group by in GetRepoIDsForIssuesOptions, showing search on pulls dashboard page too (not just issues) Co-authored-by: guillep2k <18600385+guillep2k@users.noreply.github.com>
5 years ago
[UI] IssuePage multi repo select (#8741) * Make repository list @ issues/PR page persist Will partially fix #6355 * Enable multiple selections in repo list @ issues/PR page Part of issue #6355 * Add RepoIDs to UserIssueStatsOptions to make "type" count correct when selecting one/multiple repos. * Replace variable "repo" with list "repos[]" and enable multiple selections of repositories from list by including/excluding RepoIDs in list. * * Remove redundant code * Add 'All' button Improves functionality of the page, so that backtracking is not necessary to reset the page * Remove redundant variable Completely replace 'RepoID' with 'RepoIDs' and remove redundant code * Add RepoIDs to label link * Revert part of code to previous version to troubleshoot build failure * Implement old and new pieces of code whilst adhering to multi select * Attempt to join the two versions Last commit passed tests but doesn't work in practice, this works in practice and hopefully passes the tests. * Update tests to desired state * Fix pagination implementation and tests * Pass repoIDs as `repos=[1,2,3...]` instead of several `repos[]=..` * Update tests file to reflect new functionality * Update template with new `repos` format * Implement new solution to show constant "total issues" count for "All" button * Correct behavior when passing zero to array * Comment out test url returning 404 This keeps returning 404 in the test despite working in practice, for the sake of running more tests I am commenting it out * Comment out another test url returning 404 Last attempt, if more tests crash I will uncomment the urls and request assistance. * Reenable tests and test fix * Re-enable tests * Make selecting "In your repositories" reset selection as passing IDs of repos belonging to other profiles causes breakage * Remove unnecessary (with multi-selection enable) code * Drop repo from repo map and total count if permission denied * Remove extra parenthesis * make template work again * find bug! * forgot the '#' at bugfixing * delete unused RepoID * compile regex only one time * make fmt * local variable = capital letter lower * check if repos query pattern is correct * pagination remove last , - make regex work again * use Replace instead of ReplaceAll; del delete * fix test * how did this test binary got in?!? dont forgot the "-p" at git add * ! * dont replace -> cut fisrt & last string Co-Authored-By: zeripath <art27@cantab.net> * jet another regex dont mind as long as it has the same result and is performatn ... Co-Authored-By: zeripath <art27@cantab.net> * dont use nonexisting repo for test * exclude /issues?type=created_by from test * add table to querys use same syntax in each query (table.colum) * add new issue for test * dont make a workaround or something else this need a refactor itself and is out of scope for this PR * fix misspell * CI.redo() * englisch txt update Co-Authored-By: zeripath <art27@cantab.net> * add sugestions * Tweak & Fix * CI.restart()
5 years ago
[UI] IssuePage multi repo select (#8741) * Make repository list @ issues/PR page persist Will partially fix #6355 * Enable multiple selections in repo list @ issues/PR page Part of issue #6355 * Add RepoIDs to UserIssueStatsOptions to make "type" count correct when selecting one/multiple repos. * Replace variable "repo" with list "repos[]" and enable multiple selections of repositories from list by including/excluding RepoIDs in list. * * Remove redundant code * Add 'All' button Improves functionality of the page, so that backtracking is not necessary to reset the page * Remove redundant variable Completely replace 'RepoID' with 'RepoIDs' and remove redundant code * Add RepoIDs to label link * Revert part of code to previous version to troubleshoot build failure * Implement old and new pieces of code whilst adhering to multi select * Attempt to join the two versions Last commit passed tests but doesn't work in practice, this works in practice and hopefully passes the tests. * Update tests to desired state * Fix pagination implementation and tests * Pass repoIDs as `repos=[1,2,3...]` instead of several `repos[]=..` * Update tests file to reflect new functionality * Update template with new `repos` format * Implement new solution to show constant "total issues" count for "All" button * Correct behavior when passing zero to array * Comment out test url returning 404 This keeps returning 404 in the test despite working in practice, for the sake of running more tests I am commenting it out * Comment out another test url returning 404 Last attempt, if more tests crash I will uncomment the urls and request assistance. * Reenable tests and test fix * Re-enable tests * Make selecting "In your repositories" reset selection as passing IDs of repos belonging to other profiles causes breakage * Remove unnecessary (with multi-selection enable) code * Drop repo from repo map and total count if permission denied * Remove extra parenthesis * make template work again * find bug! * forgot the '#' at bugfixing * delete unused RepoID * compile regex only one time * make fmt * local variable = capital letter lower * check if repos query pattern is correct * pagination remove last , - make regex work again * use Replace instead of ReplaceAll; del delete * fix test * how did this test binary got in?!? dont forgot the "-p" at git add * ! * dont replace -> cut fisrt & last string Co-Authored-By: zeripath <art27@cantab.net> * jet another regex dont mind as long as it has the same result and is performatn ... Co-Authored-By: zeripath <art27@cantab.net> * dont use nonexisting repo for test * exclude /issues?type=created_by from test * add table to querys use same syntax in each query (table.colum) * add new issue for test * dont make a workaround or something else this need a refactor itself and is out of scope for this PR * fix misspell * CI.redo() * englisch txt update Co-Authored-By: zeripath <art27@cantab.net> * add sugestions * Tweak & Fix * CI.restart()
5 years ago
[UI] IssuePage multi repo select (#8741) * Make repository list @ issues/PR page persist Will partially fix #6355 * Enable multiple selections in repo list @ issues/PR page Part of issue #6355 * Add RepoIDs to UserIssueStatsOptions to make "type" count correct when selecting one/multiple repos. * Replace variable "repo" with list "repos[]" and enable multiple selections of repositories from list by including/excluding RepoIDs in list. * * Remove redundant code * Add 'All' button Improves functionality of the page, so that backtracking is not necessary to reset the page * Remove redundant variable Completely replace 'RepoID' with 'RepoIDs' and remove redundant code * Add RepoIDs to label link * Revert part of code to previous version to troubleshoot build failure * Implement old and new pieces of code whilst adhering to multi select * Attempt to join the two versions Last commit passed tests but doesn't work in practice, this works in practice and hopefully passes the tests. * Update tests to desired state * Fix pagination implementation and tests * Pass repoIDs as `repos=[1,2,3...]` instead of several `repos[]=..` * Update tests file to reflect new functionality * Update template with new `repos` format * Implement new solution to show constant "total issues" count for "All" button * Correct behavior when passing zero to array * Comment out test url returning 404 This keeps returning 404 in the test despite working in practice, for the sake of running more tests I am commenting it out * Comment out another test url returning 404 Last attempt, if more tests crash I will uncomment the urls and request assistance. * Reenable tests and test fix * Re-enable tests * Make selecting "In your repositories" reset selection as passing IDs of repos belonging to other profiles causes breakage * Remove unnecessary (with multi-selection enable) code * Drop repo from repo map and total count if permission denied * Remove extra parenthesis * make template work again * find bug! * forgot the '#' at bugfixing * delete unused RepoID * compile regex only one time * make fmt * local variable = capital letter lower * check if repos query pattern is correct * pagination remove last , - make regex work again * use Replace instead of ReplaceAll; del delete * fix test * how did this test binary got in?!? dont forgot the "-p" at git add * ! * dont replace -> cut fisrt & last string Co-Authored-By: zeripath <art27@cantab.net> * jet another regex dont mind as long as it has the same result and is performatn ... Co-Authored-By: zeripath <art27@cantab.net> * dont use nonexisting repo for test * exclude /issues?type=created_by from test * add table to querys use same syntax in each query (table.colum) * add new issue for test * dont make a workaround or something else this need a refactor itself and is out of scope for this PR * fix misspell * CI.redo() * englisch txt update Co-Authored-By: zeripath <art27@cantab.net> * add sugestions * Tweak & Fix * CI.restart()
5 years ago
[UI] IssuePage multi repo select (#8741) * Make repository list @ issues/PR page persist Will partially fix #6355 * Enable multiple selections in repo list @ issues/PR page Part of issue #6355 * Add RepoIDs to UserIssueStatsOptions to make "type" count correct when selecting one/multiple repos. * Replace variable "repo" with list "repos[]" and enable multiple selections of repositories from list by including/excluding RepoIDs in list. * * Remove redundant code * Add 'All' button Improves functionality of the page, so that backtracking is not necessary to reset the page * Remove redundant variable Completely replace 'RepoID' with 'RepoIDs' and remove redundant code * Add RepoIDs to label link * Revert part of code to previous version to troubleshoot build failure * Implement old and new pieces of code whilst adhering to multi select * Attempt to join the two versions Last commit passed tests but doesn't work in practice, this works in practice and hopefully passes the tests. * Update tests to desired state * Fix pagination implementation and tests * Pass repoIDs as `repos=[1,2,3...]` instead of several `repos[]=..` * Update tests file to reflect new functionality * Update template with new `repos` format * Implement new solution to show constant "total issues" count for "All" button * Correct behavior when passing zero to array * Comment out test url returning 404 This keeps returning 404 in the test despite working in practice, for the sake of running more tests I am commenting it out * Comment out another test url returning 404 Last attempt, if more tests crash I will uncomment the urls and request assistance. * Reenable tests and test fix * Re-enable tests * Make selecting "In your repositories" reset selection as passing IDs of repos belonging to other profiles causes breakage * Remove unnecessary (with multi-selection enable) code * Drop repo from repo map and total count if permission denied * Remove extra parenthesis * make template work again * find bug! * forgot the '#' at bugfixing * delete unused RepoID * compile regex only one time * make fmt * local variable = capital letter lower * check if repos query pattern is correct * pagination remove last , - make regex work again * use Replace instead of ReplaceAll; del delete * fix test * how did this test binary got in?!? dont forgot the "-p" at git add * ! * dont replace -> cut fisrt & last string Co-Authored-By: zeripath <art27@cantab.net> * jet another regex dont mind as long as it has the same result and is performatn ... Co-Authored-By: zeripath <art27@cantab.net> * dont use nonexisting repo for test * exclude /issues?type=created_by from test * add table to querys use same syntax in each query (table.colum) * add new issue for test * dont make a workaround or something else this need a refactor itself and is out of scope for this PR * fix misspell * CI.redo() * englisch txt update Co-Authored-By: zeripath <art27@cantab.net> * add sugestions * Tweak & Fix * CI.restart()
5 years ago
Allow cross-repository dependencies on issues (#7901) * in progress changes for #7405, added ability to add cross-repo dependencies * removed unused repolink var * fixed query that was breaking ci tests; fixed check in issue dependency add so that the id of the issue and dependency is checked rather than the indexes * reverted removal of string in local files becasue these are done via crowdin, not updated manually * removed 'Select("issue.*")' from getBlockedByDependencies and getBlockingDependencies based on comments in PR review * changed getBlockedByDependencies and getBlockingDependencies to use a more xorm-like query, also updated the sidebar as a result * simplified the getBlockingDependencies and getBlockedByDependencies methods; changed the sidebar to show the dependencies in a different format where you can see the name of the repository * made some changes to the issue view in the dependencies (issue name on top, repo full name on separate line). Change view of issue in the dependency search results (also showing the full repo name on separate line) * replace call to FindUserAccessibleRepoIDs with SearchRepositoryByName. The former was hardcoded to use isPrivate = false on the repo search, but this code needed it to be true. The SearchRepositoryByName method is used more in the code including on the user's dashboard * some more tweaks to the layout of the issues when showing dependencies and in the search box when you add new dependencies * added Name to the RepositoryMeta struct * updated swagger doc * fixed total count for link header on SearchIssues * fixed indentation * fixed aligment of remove icon on dependencies in issue sidebar * removed unnecessary nil check (unnecessary because issue.loadRepo is called prior to this block) * reverting .css change, somehow missed or forgot that less is used * updated less file and generated css; updated sidebar template with styles to line up delete and issue index * added ordering to the blocked by/depends on queries * fixed sorting in issue dependency search and the depends on/blocks views to show issues from the current repo first, then by created date descending; added a "all cross repository dependencies" setting to allow this feature to be turned off, if turned off, the issue dependency search will work the way it did before (restricted to the current repository) * re-applied my swagger changes after merge * fixed split string condition in issue search * changed ALLOW_CROSS_REPOSITORY_DEPENDENCIES description to sound more global than just the issue dependency search; returning 400 in the cross repo issue search api method if not enabled; fixed bug where the issue count did not respect the state parameter * when adding a dependency to an issue, added a check to make sure the issue and dependency are in the same repo if cross repo dependencies is not enabled * updated sortIssuesSession call in PullRequests, another commit moved this method from pull.go to pull_list.go so I had to re-apply my change here * fixed incorrect setting of user id parameter in search repos call
5 years ago
Issue due date (#3794) * Started adding deadline to ui * Implemented basic issue due date managing * Improved UI for due date managing * Added at least write access to the repo in order to modify issue due dates * Ui improvements * Added issue comments creation when adding/modifying/removing a due date * Show due date in issue list * Added api support for issue due dates * Fixed lint suggestions * Added deadline to sdk * Updated css * Added support for adding/modifiying deadlines for pull requests via api * Fixed comments not created when updating or removing a deadline * update sdk (will do properly once go-gitea/go-sdk#103 is merged) * enhanced updateIssueDeadline * Removed unnessecary Issue.DeadlineString * UI improvements * Small improvments to comment creation + ui & validation improvements * Check if an issue is overdue is now a seperate function * Updated go-sdk with govendor as it was merged * Simplified isOverdue method * removed unessecary deadline to 0 set * Update swagger definitions * Added missing return * Added an explanary comment * Improved updateIssueDeadline method so it'll only update `deadline_unix` * Small changes and improvements * no need to explicitly load the issue when updating a deadline, just use whats already there * small optimisations * Added check if a deadline was modified before updating it * Moved comment creating logic into its own function * Code cleanup for creating deadline comment * locale improvement * When modifying a deadline, the old deadline is saved with the comment * small improvments to xorm session handling when updating an issue deadline + style nitpicks * style nitpicks * Moved checking for if the user has write acces to middleware
7 years ago
Issue due date (#3794) * Started adding deadline to ui * Implemented basic issue due date managing * Improved UI for due date managing * Added at least write access to the repo in order to modify issue due dates * Ui improvements * Added issue comments creation when adding/modifying/removing a due date * Show due date in issue list * Added api support for issue due dates * Fixed lint suggestions * Added deadline to sdk * Updated css * Added support for adding/modifiying deadlines for pull requests via api * Fixed comments not created when updating or removing a deadline * update sdk (will do properly once go-gitea/go-sdk#103 is merged) * enhanced updateIssueDeadline * Removed unnessecary Issue.DeadlineString * UI improvements * Small improvments to comment creation + ui & validation improvements * Check if an issue is overdue is now a seperate function * Updated go-sdk with govendor as it was merged * Simplified isOverdue method * removed unessecary deadline to 0 set * Update swagger definitions * Added missing return * Added an explanary comment * Improved updateIssueDeadline method so it'll only update `deadline_unix` * Small changes and improvements * no need to explicitly load the issue when updating a deadline, just use whats already there * small optimisations * Added check if a deadline was modified before updating it * Moved comment creating logic into its own function * Code cleanup for creating deadline comment * locale improvement * When modifying a deadline, the old deadline is saved with the comment * small improvments to xorm session handling when updating an issue deadline + style nitpicks * style nitpicks * Moved checking for if the user has write acces to middleware
7 years ago
Allow cross-repository dependencies on issues (#7901) * in progress changes for #7405, added ability to add cross-repo dependencies * removed unused repolink var * fixed query that was breaking ci tests; fixed check in issue dependency add so that the id of the issue and dependency is checked rather than the indexes * reverted removal of string in local files becasue these are done via crowdin, not updated manually * removed 'Select("issue.*")' from getBlockedByDependencies and getBlockingDependencies based on comments in PR review * changed getBlockedByDependencies and getBlockingDependencies to use a more xorm-like query, also updated the sidebar as a result * simplified the getBlockingDependencies and getBlockedByDependencies methods; changed the sidebar to show the dependencies in a different format where you can see the name of the repository * made some changes to the issue view in the dependencies (issue name on top, repo full name on separate line). Change view of issue in the dependency search results (also showing the full repo name on separate line) * replace call to FindUserAccessibleRepoIDs with SearchRepositoryByName. The former was hardcoded to use isPrivate = false on the repo search, but this code needed it to be true. The SearchRepositoryByName method is used more in the code including on the user's dashboard * some more tweaks to the layout of the issues when showing dependencies and in the search box when you add new dependencies * added Name to the RepositoryMeta struct * updated swagger doc * fixed total count for link header on SearchIssues * fixed indentation * fixed aligment of remove icon on dependencies in issue sidebar * removed unnecessary nil check (unnecessary because issue.loadRepo is called prior to this block) * reverting .css change, somehow missed or forgot that less is used * updated less file and generated css; updated sidebar template with styles to line up delete and issue index * added ordering to the blocked by/depends on queries * fixed sorting in issue dependency search and the depends on/blocks views to show issues from the current repo first, then by created date descending; added a "all cross repository dependencies" setting to allow this feature to be turned off, if turned off, the issue dependency search will work the way it did before (restricted to the current repository) * re-applied my swagger changes after merge * fixed split string condition in issue search * changed ALLOW_CROSS_REPOSITORY_DEPENDENCIES description to sound more global than just the issue dependency search; returning 400 in the cross repo issue search api method if not enabled; fixed bug where the issue count did not respect the state parameter * when adding a dependency to an issue, added a check to make sure the issue and dependency are in the same repo if cross repo dependencies is not enabled * updated sortIssuesSession call in PullRequests, another commit moved this method from pull.go to pull_list.go so I had to re-apply my change here * fixed incorrect setting of user id parameter in search repos call
5 years ago
Allow cross-repository dependencies on issues (#7901) * in progress changes for #7405, added ability to add cross-repo dependencies * removed unused repolink var * fixed query that was breaking ci tests; fixed check in issue dependency add so that the id of the issue and dependency is checked rather than the indexes * reverted removal of string in local files becasue these are done via crowdin, not updated manually * removed 'Select("issue.*")' from getBlockedByDependencies and getBlockingDependencies based on comments in PR review * changed getBlockedByDependencies and getBlockingDependencies to use a more xorm-like query, also updated the sidebar as a result * simplified the getBlockingDependencies and getBlockedByDependencies methods; changed the sidebar to show the dependencies in a different format where you can see the name of the repository * made some changes to the issue view in the dependencies (issue name on top, repo full name on separate line). Change view of issue in the dependency search results (also showing the full repo name on separate line) * replace call to FindUserAccessibleRepoIDs with SearchRepositoryByName. The former was hardcoded to use isPrivate = false on the repo search, but this code needed it to be true. The SearchRepositoryByName method is used more in the code including on the user's dashboard * some more tweaks to the layout of the issues when showing dependencies and in the search box when you add new dependencies * added Name to the RepositoryMeta struct * updated swagger doc * fixed total count for link header on SearchIssues * fixed indentation * fixed aligment of remove icon on dependencies in issue sidebar * removed unnecessary nil check (unnecessary because issue.loadRepo is called prior to this block) * reverting .css change, somehow missed or forgot that less is used * updated less file and generated css; updated sidebar template with styles to line up delete and issue index * added ordering to the blocked by/depends on queries * fixed sorting in issue dependency search and the depends on/blocks views to show issues from the current repo first, then by created date descending; added a "all cross repository dependencies" setting to allow this feature to be turned off, if turned off, the issue dependency search will work the way it did before (restricted to the current repository) * re-applied my swagger changes after merge * fixed split string condition in issue search * changed ALLOW_CROSS_REPOSITORY_DEPENDENCIES description to sound more global than just the issue dependency search; returning 400 in the cross repo issue search api method if not enabled; fixed bug where the issue count did not respect the state parameter * when adding a dependency to an issue, added a check to make sure the issue and dependency are in the same repo if cross repo dependencies is not enabled * updated sortIssuesSession call in PullRequests, another commit moved this method from pull.go to pull_list.go so I had to re-apply my change here * fixed incorrect setting of user id parameter in search repos call
5 years ago
Allow cross-repository dependencies on issues (#7901) * in progress changes for #7405, added ability to add cross-repo dependencies * removed unused repolink var * fixed query that was breaking ci tests; fixed check in issue dependency add so that the id of the issue and dependency is checked rather than the indexes * reverted removal of string in local files becasue these are done via crowdin, not updated manually * removed 'Select("issue.*")' from getBlockedByDependencies and getBlockingDependencies based on comments in PR review * changed getBlockedByDependencies and getBlockingDependencies to use a more xorm-like query, also updated the sidebar as a result * simplified the getBlockingDependencies and getBlockedByDependencies methods; changed the sidebar to show the dependencies in a different format where you can see the name of the repository * made some changes to the issue view in the dependencies (issue name on top, repo full name on separate line). Change view of issue in the dependency search results (also showing the full repo name on separate line) * replace call to FindUserAccessibleRepoIDs with SearchRepositoryByName. The former was hardcoded to use isPrivate = false on the repo search, but this code needed it to be true. The SearchRepositoryByName method is used more in the code including on the user's dashboard * some more tweaks to the layout of the issues when showing dependencies and in the search box when you add new dependencies * added Name to the RepositoryMeta struct * updated swagger doc * fixed total count for link header on SearchIssues * fixed indentation * fixed aligment of remove icon on dependencies in issue sidebar * removed unnecessary nil check (unnecessary because issue.loadRepo is called prior to this block) * reverting .css change, somehow missed or forgot that less is used * updated less file and generated css; updated sidebar template with styles to line up delete and issue index * added ordering to the blocked by/depends on queries * fixed sorting in issue dependency search and the depends on/blocks views to show issues from the current repo first, then by created date descending; added a "all cross repository dependencies" setting to allow this feature to be turned off, if turned off, the issue dependency search will work the way it did before (restricted to the current repository) * re-applied my swagger changes after merge * fixed split string condition in issue search * changed ALLOW_CROSS_REPOSITORY_DEPENDENCIES description to sound more global than just the issue dependency search; returning 400 in the cross repo issue search api method if not enabled; fixed bug where the issue count did not respect the state parameter * when adding a dependency to an issue, added a check to make sure the issue and dependency are in the same repo if cross repo dependencies is not enabled * updated sortIssuesSession call in PullRequests, another commit moved this method from pull.go to pull_list.go so I had to re-apply my change here * fixed incorrect setting of user id parameter in search repos call
5 years ago
Allow cross-repository dependencies on issues (#7901) * in progress changes for #7405, added ability to add cross-repo dependencies * removed unused repolink var * fixed query that was breaking ci tests; fixed check in issue dependency add so that the id of the issue and dependency is checked rather than the indexes * reverted removal of string in local files becasue these are done via crowdin, not updated manually * removed 'Select("issue.*")' from getBlockedByDependencies and getBlockingDependencies based on comments in PR review * changed getBlockedByDependencies and getBlockingDependencies to use a more xorm-like query, also updated the sidebar as a result * simplified the getBlockingDependencies and getBlockedByDependencies methods; changed the sidebar to show the dependencies in a different format where you can see the name of the repository * made some changes to the issue view in the dependencies (issue name on top, repo full name on separate line). Change view of issue in the dependency search results (also showing the full repo name on separate line) * replace call to FindUserAccessibleRepoIDs with SearchRepositoryByName. The former was hardcoded to use isPrivate = false on the repo search, but this code needed it to be true. The SearchRepositoryByName method is used more in the code including on the user's dashboard * some more tweaks to the layout of the issues when showing dependencies and in the search box when you add new dependencies * added Name to the RepositoryMeta struct * updated swagger doc * fixed total count for link header on SearchIssues * fixed indentation * fixed aligment of remove icon on dependencies in issue sidebar * removed unnecessary nil check (unnecessary because issue.loadRepo is called prior to this block) * reverting .css change, somehow missed or forgot that less is used * updated less file and generated css; updated sidebar template with styles to line up delete and issue index * added ordering to the blocked by/depends on queries * fixed sorting in issue dependency search and the depends on/blocks views to show issues from the current repo first, then by created date descending; added a "all cross repository dependencies" setting to allow this feature to be turned off, if turned off, the issue dependency search will work the way it did before (restricted to the current repository) * re-applied my swagger changes after merge * fixed split string condition in issue search * changed ALLOW_CROSS_REPOSITORY_DEPENDENCIES description to sound more global than just the issue dependency search; returning 400 in the cross repo issue search api method if not enabled; fixed bug where the issue count did not respect the state parameter * when adding a dependency to an issue, added a check to make sure the issue and dependency are in the same repo if cross repo dependencies is not enabled * updated sortIssuesSession call in PullRequests, another commit moved this method from pull.go to pull_list.go so I had to re-apply my change here * fixed incorrect setting of user id parameter in search repos call
5 years ago
Allow cross-repository dependencies on issues (#7901) * in progress changes for #7405, added ability to add cross-repo dependencies * removed unused repolink var * fixed query that was breaking ci tests; fixed check in issue dependency add so that the id of the issue and dependency is checked rather than the indexes * reverted removal of string in local files becasue these are done via crowdin, not updated manually * removed 'Select("issue.*")' from getBlockedByDependencies and getBlockingDependencies based on comments in PR review * changed getBlockedByDependencies and getBlockingDependencies to use a more xorm-like query, also updated the sidebar as a result * simplified the getBlockingDependencies and getBlockedByDependencies methods; changed the sidebar to show the dependencies in a different format where you can see the name of the repository * made some changes to the issue view in the dependencies (issue name on top, repo full name on separate line). Change view of issue in the dependency search results (also showing the full repo name on separate line) * replace call to FindUserAccessibleRepoIDs with SearchRepositoryByName. The former was hardcoded to use isPrivate = false on the repo search, but this code needed it to be true. The SearchRepositoryByName method is used more in the code including on the user's dashboard * some more tweaks to the layout of the issues when showing dependencies and in the search box when you add new dependencies * added Name to the RepositoryMeta struct * updated swagger doc * fixed total count for link header on SearchIssues * fixed indentation * fixed aligment of remove icon on dependencies in issue sidebar * removed unnecessary nil check (unnecessary because issue.loadRepo is called prior to this block) * reverting .css change, somehow missed or forgot that less is used * updated less file and generated css; updated sidebar template with styles to line up delete and issue index * added ordering to the blocked by/depends on queries * fixed sorting in issue dependency search and the depends on/blocks views to show issues from the current repo first, then by created date descending; added a "all cross repository dependencies" setting to allow this feature to be turned off, if turned off, the issue dependency search will work the way it did before (restricted to the current repository) * re-applied my swagger changes after merge * fixed split string condition in issue search * changed ALLOW_CROSS_REPOSITORY_DEPENDENCIES description to sound more global than just the issue dependency search; returning 400 in the cross repo issue search api method if not enabled; fixed bug where the issue count did not respect the state parameter * when adding a dependency to an issue, added a check to make sure the issue and dependency are in the same repo if cross repo dependencies is not enabled * updated sortIssuesSession call in PullRequests, another commit moved this method from pull.go to pull_list.go so I had to re-apply my change here * fixed incorrect setting of user id parameter in search repos call
5 years ago
Allow cross-repository dependencies on issues (#7901) * in progress changes for #7405, added ability to add cross-repo dependencies * removed unused repolink var * fixed query that was breaking ci tests; fixed check in issue dependency add so that the id of the issue and dependency is checked rather than the indexes * reverted removal of string in local files becasue these are done via crowdin, not updated manually * removed 'Select("issue.*")' from getBlockedByDependencies and getBlockingDependencies based on comments in PR review * changed getBlockedByDependencies and getBlockingDependencies to use a more xorm-like query, also updated the sidebar as a result * simplified the getBlockingDependencies and getBlockedByDependencies methods; changed the sidebar to show the dependencies in a different format where you can see the name of the repository * made some changes to the issue view in the dependencies (issue name on top, repo full name on separate line). Change view of issue in the dependency search results (also showing the full repo name on separate line) * replace call to FindUserAccessibleRepoIDs with SearchRepositoryByName. The former was hardcoded to use isPrivate = false on the repo search, but this code needed it to be true. The SearchRepositoryByName method is used more in the code including on the user's dashboard * some more tweaks to the layout of the issues when showing dependencies and in the search box when you add new dependencies * added Name to the RepositoryMeta struct * updated swagger doc * fixed total count for link header on SearchIssues * fixed indentation * fixed aligment of remove icon on dependencies in issue sidebar * removed unnecessary nil check (unnecessary because issue.loadRepo is called prior to this block) * reverting .css change, somehow missed or forgot that less is used * updated less file and generated css; updated sidebar template with styles to line up delete and issue index * added ordering to the blocked by/depends on queries * fixed sorting in issue dependency search and the depends on/blocks views to show issues from the current repo first, then by created date descending; added a "all cross repository dependencies" setting to allow this feature to be turned off, if turned off, the issue dependency search will work the way it did before (restricted to the current repository) * re-applied my swagger changes after merge * fixed split string condition in issue search * changed ALLOW_CROSS_REPOSITORY_DEPENDENCIES description to sound more global than just the issue dependency search; returning 400 in the cross repo issue search api method if not enabled; fixed bug where the issue count did not respect the state parameter * when adding a dependency to an issue, added a check to make sure the issue and dependency are in the same repo if cross repo dependencies is not enabled * updated sortIssuesSession call in PullRequests, another commit moved this method from pull.go to pull_list.go so I had to re-apply my change here * fixed incorrect setting of user id parameter in search repos call
5 years ago
Allow cross-repository dependencies on issues (#7901) * in progress changes for #7405, added ability to add cross-repo dependencies * removed unused repolink var * fixed query that was breaking ci tests; fixed check in issue dependency add so that the id of the issue and dependency is checked rather than the indexes * reverted removal of string in local files becasue these are done via crowdin, not updated manually * removed 'Select("issue.*")' from getBlockedByDependencies and getBlockingDependencies based on comments in PR review * changed getBlockedByDependencies and getBlockingDependencies to use a more xorm-like query, also updated the sidebar as a result * simplified the getBlockingDependencies and getBlockedByDependencies methods; changed the sidebar to show the dependencies in a different format where you can see the name of the repository * made some changes to the issue view in the dependencies (issue name on top, repo full name on separate line). Change view of issue in the dependency search results (also showing the full repo name on separate line) * replace call to FindUserAccessibleRepoIDs with SearchRepositoryByName. The former was hardcoded to use isPrivate = false on the repo search, but this code needed it to be true. The SearchRepositoryByName method is used more in the code including on the user's dashboard * some more tweaks to the layout of the issues when showing dependencies and in the search box when you add new dependencies * added Name to the RepositoryMeta struct * updated swagger doc * fixed total count for link header on SearchIssues * fixed indentation * fixed aligment of remove icon on dependencies in issue sidebar * removed unnecessary nil check (unnecessary because issue.loadRepo is called prior to this block) * reverting .css change, somehow missed or forgot that less is used * updated less file and generated css; updated sidebar template with styles to line up delete and issue index * added ordering to the blocked by/depends on queries * fixed sorting in issue dependency search and the depends on/blocks views to show issues from the current repo first, then by created date descending; added a "all cross repository dependencies" setting to allow this feature to be turned off, if turned off, the issue dependency search will work the way it did before (restricted to the current repository) * re-applied my swagger changes after merge * fixed split string condition in issue search * changed ALLOW_CROSS_REPOSITORY_DEPENDENCIES description to sound more global than just the issue dependency search; returning 400 in the cross repo issue search api method if not enabled; fixed bug where the issue count did not respect the state parameter * when adding a dependency to an issue, added a check to make sure the issue and dependency are in the same repo if cross repo dependencies is not enabled * updated sortIssuesSession call in PullRequests, another commit moved this method from pull.go to pull_list.go so I had to re-apply my change here * fixed incorrect setting of user id parameter in search repos call
5 years ago
Allow cross-repository dependencies on issues (#7901) * in progress changes for #7405, added ability to add cross-repo dependencies * removed unused repolink var * fixed query that was breaking ci tests; fixed check in issue dependency add so that the id of the issue and dependency is checked rather than the indexes * reverted removal of string in local files becasue these are done via crowdin, not updated manually * removed 'Select("issue.*")' from getBlockedByDependencies and getBlockingDependencies based on comments in PR review * changed getBlockedByDependencies and getBlockingDependencies to use a more xorm-like query, also updated the sidebar as a result * simplified the getBlockingDependencies and getBlockedByDependencies methods; changed the sidebar to show the dependencies in a different format where you can see the name of the repository * made some changes to the issue view in the dependencies (issue name on top, repo full name on separate line). Change view of issue in the dependency search results (also showing the full repo name on separate line) * replace call to FindUserAccessibleRepoIDs with SearchRepositoryByName. The former was hardcoded to use isPrivate = false on the repo search, but this code needed it to be true. The SearchRepositoryByName method is used more in the code including on the user's dashboard * some more tweaks to the layout of the issues when showing dependencies and in the search box when you add new dependencies * added Name to the RepositoryMeta struct * updated swagger doc * fixed total count for link header on SearchIssues * fixed indentation * fixed aligment of remove icon on dependencies in issue sidebar * removed unnecessary nil check (unnecessary because issue.loadRepo is called prior to this block) * reverting .css change, somehow missed or forgot that less is used * updated less file and generated css; updated sidebar template with styles to line up delete and issue index * added ordering to the blocked by/depends on queries * fixed sorting in issue dependency search and the depends on/blocks views to show issues from the current repo first, then by created date descending; added a "all cross repository dependencies" setting to allow this feature to be turned off, if turned off, the issue dependency search will work the way it did before (restricted to the current repository) * re-applied my swagger changes after merge * fixed split string condition in issue search * changed ALLOW_CROSS_REPOSITORY_DEPENDENCIES description to sound more global than just the issue dependency search; returning 400 in the cross repo issue search api method if not enabled; fixed bug where the issue count did not respect the state parameter * when adding a dependency to an issue, added a check to make sure the issue and dependency are in the same repo if cross repo dependencies is not enabled * updated sortIssuesSession call in PullRequests, another commit moved this method from pull.go to pull_list.go so I had to re-apply my change here * fixed incorrect setting of user id parameter in search repos call
5 years ago
Allow cross-repository dependencies on issues (#7901) * in progress changes for #7405, added ability to add cross-repo dependencies * removed unused repolink var * fixed query that was breaking ci tests; fixed check in issue dependency add so that the id of the issue and dependency is checked rather than the indexes * reverted removal of string in local files becasue these are done via crowdin, not updated manually * removed 'Select("issue.*")' from getBlockedByDependencies and getBlockingDependencies based on comments in PR review * changed getBlockedByDependencies and getBlockingDependencies to use a more xorm-like query, also updated the sidebar as a result * simplified the getBlockingDependencies and getBlockedByDependencies methods; changed the sidebar to show the dependencies in a different format where you can see the name of the repository * made some changes to the issue view in the dependencies (issue name on top, repo full name on separate line). Change view of issue in the dependency search results (also showing the full repo name on separate line) * replace call to FindUserAccessibleRepoIDs with SearchRepositoryByName. The former was hardcoded to use isPrivate = false on the repo search, but this code needed it to be true. The SearchRepositoryByName method is used more in the code including on the user's dashboard * some more tweaks to the layout of the issues when showing dependencies and in the search box when you add new dependencies * added Name to the RepositoryMeta struct * updated swagger doc * fixed total count for link header on SearchIssues * fixed indentation * fixed aligment of remove icon on dependencies in issue sidebar * removed unnecessary nil check (unnecessary because issue.loadRepo is called prior to this block) * reverting .css change, somehow missed or forgot that less is used * updated less file and generated css; updated sidebar template with styles to line up delete and issue index * added ordering to the blocked by/depends on queries * fixed sorting in issue dependency search and the depends on/blocks views to show issues from the current repo first, then by created date descending; added a "all cross repository dependencies" setting to allow this feature to be turned off, if turned off, the issue dependency search will work the way it did before (restricted to the current repository) * re-applied my swagger changes after merge * fixed split string condition in issue search * changed ALLOW_CROSS_REPOSITORY_DEPENDENCIES description to sound more global than just the issue dependency search; returning 400 in the cross repo issue search api method if not enabled; fixed bug where the issue count did not respect the state parameter * when adding a dependency to an issue, added a check to make sure the issue and dependency are in the same repo if cross repo dependencies is not enabled * updated sortIssuesSession call in PullRequests, another commit moved this method from pull.go to pull_list.go so I had to re-apply my change here * fixed incorrect setting of user id parameter in search repos call
5 years ago
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>
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>
4 years ago
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060
  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. issue.Labels = nil
  469. if err = issue.loadLabels(sess); err != nil {
  470. return err
  471. }
  472. return sess.Commit()
  473. }
  474. // ReadBy sets issue to be read by given user.
  475. func (issue *Issue) ReadBy(userID int64) error {
  476. if err := UpdateIssueUserByRead(userID, issue.ID); err != nil {
  477. return err
  478. }
  479. return setNotificationStatusReadIfUnread(x, userID, issue.ID)
  480. }
  481. func updateIssueCols(e Engine, issue *Issue, cols ...string) error {
  482. if _, err := e.ID(issue.ID).Cols(cols...).Update(issue); err != nil {
  483. return err
  484. }
  485. return nil
  486. }
  487. func (issue *Issue) changeStatus(e *xorm.Session, doer *User, isClosed, isMergePull bool) (*Comment, error) {
  488. // Reload the issue
  489. currentIssue, err := getIssueByID(e, issue.ID)
  490. if err != nil {
  491. return nil, err
  492. }
  493. // Nothing should be performed if current status is same as target status
  494. if currentIssue.IsClosed == isClosed {
  495. if !issue.IsPull {
  496. return nil, ErrIssueWasClosed{
  497. ID: issue.ID,
  498. }
  499. }
  500. return nil, ErrPullWasClosed{
  501. ID: issue.ID,
  502. }
  503. }
  504. issue.IsClosed = isClosed
  505. return issue.doChangeStatus(e, doer, isMergePull)
  506. }
  507. func (issue *Issue) doChangeStatus(e *xorm.Session, doer *User, isMergePull bool) (*Comment, error) {
  508. // Check for open dependencies
  509. if issue.IsClosed && issue.Repo.isDependenciesEnabled(e) {
  510. // 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
  511. noDeps, err := issueNoDependenciesLeft(e, issue)
  512. if err != nil {
  513. return nil, err
  514. }
  515. if !noDeps {
  516. return nil, ErrDependenciesLeft{issue.ID}
  517. }
  518. }
  519. if issue.IsClosed {
  520. issue.ClosedUnix = timeutil.TimeStampNow()
  521. } else {
  522. issue.ClosedUnix = 0
  523. }
  524. if err := updateIssueCols(e, issue, "is_closed", "closed_unix"); err != nil {
  525. return nil, err
  526. }
  527. // Update issue count of labels
  528. if err := issue.getLabels(e); err != nil {
  529. return nil, err
  530. }
  531. for idx := range issue.Labels {
  532. if err := updateLabelCols(e, issue.Labels[idx], "num_issues", "num_closed_issue"); err != nil {
  533. return nil, err
  534. }
  535. }
  536. // Update issue count of milestone
  537. if err := updateMilestoneClosedNum(e, issue.MilestoneID); err != nil {
  538. return nil, err
  539. }
  540. if err := issue.updateClosedNum(e); err != nil {
  541. return nil, err
  542. }
  543. // New action comment
  544. cmtType := CommentTypeClose
  545. if !issue.IsClosed {
  546. cmtType = CommentTypeReopen
  547. } else if isMergePull {
  548. cmtType = CommentTypeMergePull
  549. }
  550. return createComment(e, &CreateCommentOptions{
  551. Type: cmtType,
  552. Doer: doer,
  553. Repo: issue.Repo,
  554. Issue: issue,
  555. })
  556. }
  557. // ChangeStatus changes issue status to open or closed.
  558. func (issue *Issue) ChangeStatus(doer *User, isClosed bool) (*Comment, error) {
  559. sess := x.NewSession()
  560. defer sess.Close()
  561. if err := sess.Begin(); err != nil {
  562. return nil, err
  563. }
  564. if err := issue.loadRepo(sess); err != nil {
  565. return nil, err
  566. }
  567. if err := issue.loadPoster(sess); err != nil {
  568. return nil, err
  569. }
  570. comment, err := issue.changeStatus(sess, doer, isClosed, false)
  571. if err != nil {
  572. return nil, err
  573. }
  574. if err = sess.Commit(); err != nil {
  575. return nil, fmt.Errorf("Commit: %v", err)
  576. }
  577. return comment, nil
  578. }
  579. // ChangeTitle changes the title of this issue, as the given user.
  580. func (issue *Issue) ChangeTitle(doer *User, oldTitle string) (err error) {
  581. sess := x.NewSession()
  582. defer sess.Close()
  583. if err = sess.Begin(); err != nil {
  584. return err
  585. }
  586. if err = updateIssueCols(sess, issue, "name"); err != nil {
  587. return fmt.Errorf("updateIssueCols: %v", err)
  588. }
  589. if err = issue.loadRepo(sess); err != nil {
  590. return fmt.Errorf("loadRepo: %v", err)
  591. }
  592. var opts = &CreateCommentOptions{
  593. Type: CommentTypeChangeTitle,
  594. Doer: doer,
  595. Repo: issue.Repo,
  596. Issue: issue,
  597. OldTitle: oldTitle,
  598. NewTitle: issue.Title,
  599. }
  600. if _, err = createComment(sess, opts); err != nil {
  601. return fmt.Errorf("createComment: %v", err)
  602. }
  603. if err = issue.addCrossReferences(sess, doer, true); err != nil {
  604. return err
  605. }
  606. return sess.Commit()
  607. }
  608. // ChangeRef changes the branch of this issue, as the given user.
  609. func (issue *Issue) ChangeRef(doer *User, oldRef string) (err error) {
  610. sess := x.NewSession()
  611. defer sess.Close()
  612. if err = sess.Begin(); err != nil {
  613. return err
  614. }
  615. if err = updateIssueCols(sess, issue, "ref"); err != nil {
  616. return fmt.Errorf("updateIssueCols: %v", err)
  617. }
  618. return sess.Commit()
  619. }
  620. // AddDeletePRBranchComment adds delete branch comment for pull request issue
  621. func AddDeletePRBranchComment(doer *User, repo *Repository, issueID int64, branchName string) error {
  622. issue, err := getIssueByID(x, issueID)
  623. if err != nil {
  624. return err
  625. }
  626. sess := x.NewSession()
  627. defer sess.Close()
  628. if err := sess.Begin(); err != nil {
  629. return err
  630. }
  631. var opts = &CreateCommentOptions{
  632. Type: CommentTypeDeleteBranch,
  633. Doer: doer,
  634. Repo: repo,
  635. Issue: issue,
  636. CommitSHA: branchName,
  637. }
  638. if _, err = createComment(sess, opts); err != nil {
  639. return err
  640. }
  641. return sess.Commit()
  642. }
  643. // UpdateAttachments update attachments by UUIDs for the issue
  644. func (issue *Issue) UpdateAttachments(uuids []string) (err error) {
  645. sess := x.NewSession()
  646. defer sess.Close()
  647. if err = sess.Begin(); err != nil {
  648. return err
  649. }
  650. attachments, err := getAttachmentsByUUIDs(sess, uuids)
  651. if err != nil {
  652. return fmt.Errorf("getAttachmentsByUUIDs [uuids: %v]: %v", uuids, err)
  653. }
  654. for i := 0; i < len(attachments); i++ {
  655. attachments[i].IssueID = issue.ID
  656. if err := updateAttachment(sess, attachments[i]); err != nil {
  657. return fmt.Errorf("update attachment [id: %d]: %v", attachments[i].ID, err)
  658. }
  659. }
  660. return sess.Commit()
  661. }
  662. // ChangeContent changes issue content, as the given user.
  663. func (issue *Issue) ChangeContent(doer *User, content string) (err error) {
  664. issue.Content = content
  665. sess := x.NewSession()
  666. defer sess.Close()
  667. if err = sess.Begin(); err != nil {
  668. return err
  669. }
  670. if err = updateIssueCols(sess, issue, "content"); err != nil {
  671. return fmt.Errorf("UpdateIssueCols: %v", err)
  672. }
  673. if err = issue.addCrossReferences(sess, doer, true); err != nil {
  674. return err
  675. }
  676. return sess.Commit()
  677. }
  678. // GetTasks returns the amount of tasks in the issues content
  679. func (issue *Issue) GetTasks() int {
  680. return len(issueTasksPat.FindAllStringIndex(issue.Content, -1))
  681. }
  682. // GetTasksDone returns the amount of completed tasks in the issues content
  683. func (issue *Issue) GetTasksDone() int {
  684. return len(issueTasksDonePat.FindAllStringIndex(issue.Content, -1))
  685. }
  686. // GetLastEventTimestamp returns the last user visible event timestamp, either the creation of this issue or the close.
  687. func (issue *Issue) GetLastEventTimestamp() timeutil.TimeStamp {
  688. if issue.IsClosed {
  689. return issue.ClosedUnix
  690. }
  691. return issue.CreatedUnix
  692. }
  693. // GetLastEventLabel returns the localization label for the current issue.
  694. func (issue *Issue) GetLastEventLabel() string {
  695. if issue.IsClosed {
  696. if issue.IsPull && issue.PullRequest.HasMerged {
  697. return "repo.pulls.merged_by"
  698. }
  699. return "repo.issues.closed_by"
  700. }
  701. return "repo.issues.opened_by"
  702. }
  703. // GetLastComment return last comment for the current issue.
  704. func (issue *Issue) GetLastComment() (*Comment, error) {
  705. var c Comment
  706. exist, err := x.Where("type = ?", CommentTypeComment).
  707. And("issue_id = ?", issue.ID).Desc("id").Get(&c)
  708. if err != nil {
  709. return nil, err
  710. }
  711. if !exist {
  712. return nil, nil
  713. }
  714. return &c, nil
  715. }
  716. // GetLastEventLabelFake returns the localization label for the current issue without providing a link in the username.
  717. func (issue *Issue) GetLastEventLabelFake() string {
  718. if issue.IsClosed {
  719. if issue.IsPull && issue.PullRequest.HasMerged {
  720. return "repo.pulls.merged_by_fake"
  721. }
  722. return "repo.issues.closed_by_fake"
  723. }
  724. return "repo.issues.opened_by_fake"
  725. }
  726. // NewIssueOptions represents the options of a new issue.
  727. type NewIssueOptions struct {
  728. Repo *Repository
  729. Issue *Issue
  730. LabelIDs []int64
  731. Attachments []string // In UUID format.
  732. IsPull bool
  733. }
  734. func newIssue(e *xorm.Session, doer *User, opts NewIssueOptions) (err error) {
  735. opts.Issue.Title = strings.TrimSpace(opts.Issue.Title)
  736. if opts.Issue.MilestoneID > 0 {
  737. milestone, err := getMilestoneByRepoID(e, opts.Issue.RepoID, opts.Issue.MilestoneID)
  738. if err != nil && !IsErrMilestoneNotExist(err) {
  739. return fmt.Errorf("getMilestoneByID: %v", err)
  740. }
  741. // Assume milestone is invalid and drop silently.
  742. opts.Issue.MilestoneID = 0
  743. if milestone != nil {
  744. opts.Issue.MilestoneID = milestone.ID
  745. opts.Issue.Milestone = milestone
  746. }
  747. }
  748. // Milestone validation should happen before insert actual object.
  749. if _, err := e.SetExpr("`index`", "coalesce(MAX(`index`),0)+1").
  750. Where("repo_id=?", opts.Issue.RepoID).
  751. Insert(opts.Issue); err != nil {
  752. return ErrNewIssueInsert{err}
  753. }
  754. inserted, err := getIssueByID(e, opts.Issue.ID)
  755. if err != nil {
  756. return err
  757. }
  758. // Patch Index with the value calculated by the database
  759. opts.Issue.Index = inserted.Index
  760. if opts.Issue.MilestoneID > 0 {
  761. if _, err = e.Exec("UPDATE `milestone` SET num_issues=num_issues+1 WHERE id=?", opts.Issue.MilestoneID); err != nil {
  762. return err
  763. }
  764. var opts = &CreateCommentOptions{
  765. Type: CommentTypeMilestone,
  766. Doer: doer,
  767. Repo: opts.Repo,
  768. Issue: opts.Issue,
  769. OldMilestoneID: 0,
  770. MilestoneID: opts.Issue.MilestoneID,
  771. }
  772. if _, err = createComment(e, opts); err != nil {
  773. return err
  774. }
  775. }
  776. if opts.IsPull {
  777. _, err = e.Exec("UPDATE `repository` SET num_pulls = num_pulls + 1 WHERE id = ?", opts.Issue.RepoID)
  778. } else {
  779. _, err = e.Exec("UPDATE `repository` SET num_issues = num_issues + 1 WHERE id = ?", opts.Issue.RepoID)
  780. }
  781. if err != nil {
  782. return err
  783. }
  784. if len(opts.LabelIDs) > 0 {
  785. // During the session, SQLite3 driver cannot handle retrieve objects after update something.
  786. // So we have to get all needed labels first.
  787. labels := make([]*Label, 0, len(opts.LabelIDs))
  788. if err = e.In("id", opts.LabelIDs).Find(&labels); err != nil {
  789. return fmt.Errorf("find all labels [label_ids: %v]: %v", opts.LabelIDs, err)
  790. }
  791. if err = opts.Issue.loadPoster(e); err != nil {
  792. return err
  793. }
  794. for _, label := range labels {
  795. // Silently drop invalid labels.
  796. if label.RepoID != opts.Repo.ID && label.OrgID != opts.Repo.OwnerID {
  797. continue
  798. }
  799. if err = opts.Issue.addLabel(e, label, opts.Issue.Poster); err != nil {
  800. return fmt.Errorf("addLabel [id: %d]: %v", label.ID, err)
  801. }
  802. }
  803. }
  804. if err = newIssueUsers(e, opts.Repo, opts.Issue); err != nil {
  805. return err
  806. }
  807. if len(opts.Attachments) > 0 {
  808. attachments, err := getAttachmentsByUUIDs(e, opts.Attachments)
  809. if err != nil {
  810. return fmt.Errorf("getAttachmentsByUUIDs [uuids: %v]: %v", opts.Attachments, err)
  811. }
  812. for i := 0; i < len(attachments); i++ {
  813. attachments[i].IssueID = opts.Issue.ID
  814. if _, err = e.ID(attachments[i].ID).Update(attachments[i]); err != nil {
  815. return fmt.Errorf("update attachment [id: %d]: %v", attachments[i].ID, err)
  816. }
  817. }
  818. }
  819. if err = opts.Issue.loadAttributes(e); err != nil {
  820. return err
  821. }
  822. return opts.Issue.addCrossReferences(e, doer, false)
  823. }
  824. // NewIssue creates new issue with labels for repository.
  825. func NewIssue(repo *Repository, issue *Issue, labelIDs []int64, uuids []string) (err error) {
  826. // Retry several times in case INSERT fails due to duplicate key for (repo_id, index); see #7887
  827. i := 0
  828. for {
  829. if err = newIssueAttempt(repo, issue, labelIDs, uuids); err == nil {
  830. return nil
  831. }
  832. if !IsErrNewIssueInsert(err) {
  833. return err
  834. }
  835. if i++; i == issueMaxDupIndexAttempts {
  836. break
  837. }
  838. log.Error("NewIssue: error attempting to insert the new issue; will retry. Original error: %v", err)
  839. }
  840. return fmt.Errorf("NewIssue: too many errors attempting to insert the new issue. Last error was: %v", err)
  841. }
  842. func newIssueAttempt(repo *Repository, issue *Issue, labelIDs []int64, uuids []string) (err error) {
  843. sess := x.NewSession()
  844. defer sess.Close()
  845. if err = sess.Begin(); err != nil {
  846. return err
  847. }
  848. if err = newIssue(sess, issue.Poster, NewIssueOptions{
  849. Repo: repo,
  850. Issue: issue,
  851. LabelIDs: labelIDs,
  852. Attachments: uuids,
  853. }); err != nil {
  854. if IsErrUserDoesNotHaveAccessToRepo(err) || IsErrNewIssueInsert(err) {
  855. return err
  856. }
  857. return fmt.Errorf("newIssue: %v", err)
  858. }
  859. if err = sess.Commit(); err != nil {
  860. return fmt.Errorf("Commit: %v", err)
  861. }
  862. return nil
  863. }
  864. // GetIssueByIndex returns raw issue without loading attributes by index in a repository.
  865. func GetIssueByIndex(repoID, index int64) (*Issue, error) {
  866. issue := &Issue{
  867. RepoID: repoID,
  868. Index: index,
  869. }
  870. has, err := x.Get(issue)
  871. if err != nil {
  872. return nil, err
  873. } else if !has {
  874. return nil, ErrIssueNotExist{0, repoID, index}
  875. }
  876. return issue, nil
  877. }
  878. // GetIssueWithAttrsByIndex returns issue by index in a repository.
  879. func GetIssueWithAttrsByIndex(repoID, index int64) (*Issue, error) {
  880. issue, err := GetIssueByIndex(repoID, index)
  881. if err != nil {
  882. return nil, err
  883. }
  884. return issue, issue.LoadAttributes()
  885. }
  886. func getIssueByID(e Engine, id int64) (*Issue, error) {
  887. issue := new(Issue)
  888. has, err := e.ID(id).Get(issue)
  889. if err != nil {
  890. return nil, err
  891. } else if !has {
  892. return nil, ErrIssueNotExist{id, 0, 0}
  893. }
  894. return issue, nil
  895. }
  896. // GetIssueWithAttrsByID returns an issue with attributes by given ID.
  897. func GetIssueWithAttrsByID(id int64) (*Issue, error) {
  898. issue, err := getIssueByID(x, id)
  899. if err != nil {
  900. return nil, err
  901. }
  902. return issue, issue.loadAttributes(x)
  903. }
  904. // GetIssueByID returns an issue by given ID.
  905. func GetIssueByID(id int64) (*Issue, error) {
  906. return getIssueByID(x, id)
  907. }
  908. func getIssuesByIDs(e Engine, issueIDs []int64) ([]*Issue, error) {
  909. issues := make([]*Issue, 0, 10)
  910. return issues, e.In("id", issueIDs).Find(&issues)
  911. }
  912. func getIssueIDsByRepoID(e Engine, repoID int64) ([]int64, error) {
  913. var ids = make([]int64, 0, 10)
  914. err := e.Table("issue").Where("repo_id = ?", repoID).Find(&ids)
  915. return ids, err
  916. }
  917. // GetIssueIDsByRepoID returns all issue ids by repo id
  918. func GetIssueIDsByRepoID(repoID int64) ([]int64, error) {
  919. return getIssueIDsByRepoID(x, repoID)
  920. }
  921. // GetIssuesByIDs return issues with the given IDs.
  922. func GetIssuesByIDs(issueIDs []int64) ([]*Issue, error) {
  923. return getIssuesByIDs(x, issueIDs)
  924. }
  925. // IssuesOptions represents options of an issue.
  926. type IssuesOptions struct {
  927. ListOptions
  928. RepoIDs []int64 // include all repos if empty
  929. AssigneeID int64
  930. PosterID int64
  931. MentionedID int64
  932. MilestoneIDs []int64
  933. ProjectID int64
  934. ProjectBoardID int64
  935. IsClosed util.OptionalBool
  936. IsPull util.OptionalBool
  937. LabelIDs []int64
  938. IncludedLabelNames []string
  939. ExcludedLabelNames []string
  940. SortType string
  941. IssueIDs []int64
  942. UpdatedAfterUnix int64
  943. UpdatedBeforeUnix int64
  944. // prioritize issues from this repo
  945. PriorityRepoID int64
  946. }
  947. // sortIssuesSession sort an issues-related session based on the provided
  948. // sortType string
  949. func sortIssuesSession(sess *xorm.Session, sortType string, priorityRepoID int64) {
  950. switch sortType {
  951. case "oldest":
  952. sess.Asc("issue.created_unix")
  953. case "recentupdate":
  954. sess.Desc("issue.updated_unix")
  955. case "leastupdate":
  956. sess.Asc("issue.updated_unix")
  957. case "mostcomment":
  958. sess.Desc("issue.num_comments")
  959. case "leastcomment":
  960. sess.Asc("issue.num_comments")
  961. case "priority":
  962. sess.Desc("issue.priority")
  963. case "nearduedate":
  964. // 253370764800 is 01/01/9999 @ 12:00am (UTC)
  965. sess.OrderBy("CASE WHEN issue.deadline_unix = 0 THEN 253370764800 ELSE issue.deadline_unix END ASC")
  966. case "farduedate":
  967. sess.Desc("issue.deadline_unix")
  968. case "priorityrepo":
  969. sess.OrderBy("CASE WHEN issue.repo_id = " + strconv.FormatInt(priorityRepoID, 10) + " THEN 1 ELSE 2 END, issue.created_unix DESC")
  970. default:
  971. sess.Desc("issue.created_unix")
  972. }
  973. }
  974. func (opts *IssuesOptions) setupSession(sess *xorm.Session) {
  975. if opts.Page >= 0 && opts.PageSize > 0 {
  976. var start int
  977. if opts.Page == 0 {
  978. start = 0
  979. } else {
  980. start = (opts.Page - 1) * opts.PageSize
  981. }
  982. sess.Limit(opts.PageSize, start)
  983. }
  984. if len(opts.IssueIDs) > 0 {
  985. sess.In("issue.id", opts.IssueIDs)
  986. }
  987. if len(opts.RepoIDs) > 0 {
  988. // In case repository IDs are provided but actually no repository has issue.
  989. sess.In("issue.repo_id", opts.RepoIDs)
  990. }
  991. switch opts.IsClosed {
  992. case util.OptionalBoolTrue:
  993. sess.And("issue.is_closed=?", true)
  994. case util.OptionalBoolFalse:
  995. sess.And("issue.is_closed=?", false)
  996. }
  997. if opts.AssigneeID > 0 {
  998. sess.Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  999. And("issue_assignees.assignee_id = ?", opts.AssigneeID)
  1000. }
  1001. if opts.PosterID > 0 {
  1002. sess.And("issue.poster_id=?", opts.PosterID)
  1003. }
  1004. if opts.MentionedID > 0 {
  1005. sess.Join("INNER", "issue_user", "issue.id = issue_user.issue_id").
  1006. And("issue_user.is_mentioned = ?", true).
  1007. And("issue_user.uid = ?", opts.MentionedID)
  1008. }
  1009. if len(opts.MilestoneIDs) > 0 {
  1010. sess.In("issue.milestone_id", opts.MilestoneIDs)
  1011. }
  1012. if opts.UpdatedAfterUnix != 0 {
  1013. sess.And(builder.Gte{"issue.updated_unix": opts.UpdatedAfterUnix})
  1014. }
  1015. if opts.UpdatedBeforeUnix != 0 {
  1016. sess.And(builder.Lte{"issue.updated_unix": opts.UpdatedBeforeUnix})
  1017. }
  1018. if opts.ProjectID > 0 {
  1019. sess.Join("INNER", "project_issue", "issue.id = project_issue.issue_id").
  1020. And("project_issue.project_id=?", opts.ProjectID)
  1021. }
  1022. if opts.ProjectBoardID != 0 {
  1023. if opts.ProjectBoardID > 0 {
  1024. sess.In("issue.id", builder.Select("issue_id").From("project_issue").Where(builder.Eq{"project_board_id": opts.ProjectBoardID}))
  1025. } else {
  1026. sess.In("issue.id", builder.Select("issue_id").From("project_issue").Where(builder.Eq{"project_board_id": 0}))
  1027. }
  1028. }
  1029. switch opts.IsPull {
  1030. case util.OptionalBoolTrue:
  1031. sess.And("issue.is_pull=?", true)
  1032. case util.OptionalBoolFalse:
  1033. sess.And("issue.is_pull=?", false)
  1034. }
  1035. if opts.LabelIDs != nil {
  1036. for i, labelID := range opts.LabelIDs {
  1037. if labelID > 0 {
  1038. sess.Join("INNER", fmt.Sprintf("issue_label il%d", i),
  1039. fmt.Sprintf("issue.id = il%[1]d.issue_id AND il%[1]d.label_id = %[2]d", i, labelID))
  1040. } else {
  1041. sess.Where("issue.id not in (select issue_id from issue_label where label_id = ?)", -labelID)
  1042. }
  1043. }
  1044. }
  1045. if len(opts.IncludedLabelNames) > 0 {
  1046. sess.In("issue.id", BuildLabelNamesIssueIDsCondition(opts.IncludedLabelNames))
  1047. }
  1048. if len(opts.ExcludedLabelNames) > 0 {
  1049. sess.And(builder.NotIn("issue.id", BuildLabelNamesIssueIDsCondition(opts.ExcludedLabelNames)))
  1050. }
  1051. }
  1052. // CountIssuesByRepo map from repoID to number of issues matching the options
  1053. func CountIssuesByRepo(opts *IssuesOptions) (map[int64]int64, error) {
  1054. sess := x.NewSession()
  1055. defer sess.Close()
  1056. opts.setupSession(sess)
  1057. countsSlice := make([]*struct {
  1058. RepoID int64
  1059. Count int64
  1060. }, 0, 10)
  1061. if err := sess.GroupBy("issue.repo_id").
  1062. Select("issue.repo_id AS repo_id, COUNT(*) AS count").
  1063. Table("issue").
  1064. Find(&countsSlice); err != nil {
  1065. return nil, err
  1066. }
  1067. countMap := make(map[int64]int64, len(countsSlice))
  1068. for _, c := range countsSlice {
  1069. countMap[c.RepoID] = c.Count
  1070. }
  1071. return countMap, nil
  1072. }
  1073. // GetRepoIDsForIssuesOptions find all repo ids for the given options
  1074. func GetRepoIDsForIssuesOptions(opts *IssuesOptions, user *User) ([]int64, error) {
  1075. repoIDs := make([]int64, 0, 5)
  1076. sess := x.NewSession()
  1077. defer sess.Close()
  1078. opts.setupSession(sess)
  1079. accessCond := accessibleRepositoryCondition(user)
  1080. if err := sess.Where(accessCond).
  1081. Join("INNER", "repository", "`issue`.repo_id = `repository`.id").
  1082. Distinct("issue.repo_id").
  1083. Table("issue").
  1084. Find(&repoIDs); err != nil {
  1085. return nil, err
  1086. }
  1087. return repoIDs, nil
  1088. }
  1089. // Issues returns a list of issues by given conditions.
  1090. func Issues(opts *IssuesOptions) ([]*Issue, error) {
  1091. sess := x.NewSession()
  1092. defer sess.Close()
  1093. opts.setupSession(sess)
  1094. sortIssuesSession(sess, opts.SortType, opts.PriorityRepoID)
  1095. issues := make([]*Issue, 0, opts.ListOptions.PageSize)
  1096. if err := sess.Find(&issues); err != nil {
  1097. return nil, fmt.Errorf("Find: %v", err)
  1098. }
  1099. sess.Close()
  1100. if err := IssueList(issues).LoadAttributes(); err != nil {
  1101. return nil, fmt.Errorf("LoadAttributes: %v", err)
  1102. }
  1103. return issues, nil
  1104. }
  1105. // CountIssues number return of issues by given conditions.
  1106. func CountIssues(opts *IssuesOptions) (int64, error) {
  1107. sess := x.NewSession()
  1108. defer sess.Close()
  1109. countsSlice := make([]*struct {
  1110. RepoID int64
  1111. Count int64
  1112. }, 0, 1)
  1113. sess.Select("COUNT(issue.id) AS count").Table("issue")
  1114. opts.setupSession(sess)
  1115. if err := sess.Find(&countsSlice); err != nil {
  1116. return 0, fmt.Errorf("Find: %v", err)
  1117. }
  1118. if len(countsSlice) < 1 {
  1119. return 0, fmt.Errorf("there is less than one result sql record")
  1120. }
  1121. return countsSlice[0].Count, nil
  1122. }
  1123. // GetParticipantsIDsByIssueID returns the IDs of all users who participated in comments of an issue,
  1124. // but skips joining with `user` for performance reasons.
  1125. // User permissions must be verified elsewhere if required.
  1126. func GetParticipantsIDsByIssueID(issueID int64) ([]int64, error) {
  1127. userIDs := make([]int64, 0, 5)
  1128. return userIDs, x.Table("comment").
  1129. Cols("poster_id").
  1130. Where("issue_id = ?", issueID).
  1131. And("type in (?,?,?)", CommentTypeComment, CommentTypeCode, CommentTypeReview).
  1132. Distinct("poster_id").
  1133. Find(&userIDs)
  1134. }
  1135. // IsUserParticipantsOfIssue return true if user is participants of an issue
  1136. func IsUserParticipantsOfIssue(user *User, issue *Issue) bool {
  1137. userIDs, err := issue.getParticipantIDsByIssue(x)
  1138. if err != nil {
  1139. log.Error(err.Error())
  1140. return false
  1141. }
  1142. return util.IsInt64InSlice(user.ID, userIDs)
  1143. }
  1144. // UpdateIssueMentions updates issue-user relations for mentioned users.
  1145. func UpdateIssueMentions(ctx DBContext, issueID int64, mentions []*User) error {
  1146. if len(mentions) == 0 {
  1147. return nil
  1148. }
  1149. ids := make([]int64, len(mentions))
  1150. for i, u := range mentions {
  1151. ids[i] = u.ID
  1152. }
  1153. if err := UpdateIssueUsersByMentions(ctx, issueID, ids); err != nil {
  1154. return fmt.Errorf("UpdateIssueUsersByMentions: %v", err)
  1155. }
  1156. return nil
  1157. }
  1158. // IssueStats represents issue statistic information.
  1159. type IssueStats struct {
  1160. OpenCount, ClosedCount int64
  1161. YourRepositoriesCount int64
  1162. AssignCount int64
  1163. CreateCount int64
  1164. MentionCount int64
  1165. }
  1166. // Filter modes.
  1167. const (
  1168. FilterModeAll = iota
  1169. FilterModeAssign
  1170. FilterModeCreate
  1171. FilterModeMention
  1172. )
  1173. func parseCountResult(results []map[string][]byte) int64 {
  1174. if len(results) == 0 {
  1175. return 0
  1176. }
  1177. for _, result := range results[0] {
  1178. return com.StrTo(string(result)).MustInt64()
  1179. }
  1180. return 0
  1181. }
  1182. // IssueStatsOptions contains parameters accepted by GetIssueStats.
  1183. type IssueStatsOptions struct {
  1184. RepoID int64
  1185. Labels string
  1186. MilestoneID int64
  1187. AssigneeID int64
  1188. MentionedID int64
  1189. PosterID int64
  1190. IsPull util.OptionalBool
  1191. IssueIDs []int64
  1192. }
  1193. // GetIssueStats returns issue statistic information by given conditions.
  1194. func GetIssueStats(opts *IssueStatsOptions) (*IssueStats, error) {
  1195. if len(opts.IssueIDs) <= maxQueryParameters {
  1196. return getIssueStatsChunk(opts, opts.IssueIDs)
  1197. }
  1198. // If too long a list of IDs is provided, we get the statistics in
  1199. // smaller chunks and get accumulates. Note: this could potentially
  1200. // get us invalid results. The alternative is to insert the list of
  1201. // ids in a temporary table and join from them.
  1202. accum := &IssueStats{}
  1203. for i := 0; i < len(opts.IssueIDs); {
  1204. chunk := i + maxQueryParameters
  1205. if chunk > len(opts.IssueIDs) {
  1206. chunk = len(opts.IssueIDs)
  1207. }
  1208. stats, err := getIssueStatsChunk(opts, opts.IssueIDs[i:chunk])
  1209. if err != nil {
  1210. return nil, err
  1211. }
  1212. accum.OpenCount += stats.OpenCount
  1213. accum.ClosedCount += stats.ClosedCount
  1214. accum.YourRepositoriesCount += stats.YourRepositoriesCount
  1215. accum.AssignCount += stats.AssignCount
  1216. accum.CreateCount += stats.CreateCount
  1217. accum.OpenCount += stats.MentionCount
  1218. i = chunk
  1219. }
  1220. return accum, nil
  1221. }
  1222. func getIssueStatsChunk(opts *IssueStatsOptions, issueIDs []int64) (*IssueStats, error) {
  1223. stats := &IssueStats{}
  1224. countSession := func(opts *IssueStatsOptions) *xorm.Session {
  1225. sess := x.
  1226. Where("issue.repo_id = ?", opts.RepoID)
  1227. if len(opts.IssueIDs) > 0 {
  1228. sess.In("issue.id", opts.IssueIDs)
  1229. }
  1230. if len(opts.Labels) > 0 && opts.Labels != "0" {
  1231. labelIDs, err := base.StringsToInt64s(strings.Split(opts.Labels, ","))
  1232. if err != nil {
  1233. log.Warn("Malformed Labels argument: %s", opts.Labels)
  1234. } else {
  1235. for i, labelID := range labelIDs {
  1236. if labelID > 0 {
  1237. sess.Join("INNER", fmt.Sprintf("issue_label il%d", i),
  1238. fmt.Sprintf("issue.id = il%[1]d.issue_id AND il%[1]d.label_id = %[2]d", i, labelID))
  1239. } else {
  1240. sess.Where("issue.id NOT IN (SELECT issue_id FROM issue_label WHERE label_id = ?)", -labelID)
  1241. }
  1242. }
  1243. }
  1244. }
  1245. if opts.MilestoneID > 0 {
  1246. sess.And("issue.milestone_id = ?", opts.MilestoneID)
  1247. }
  1248. if opts.AssigneeID > 0 {
  1249. sess.Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  1250. And("issue_assignees.assignee_id = ?", opts.AssigneeID)
  1251. }
  1252. if opts.PosterID > 0 {
  1253. sess.And("issue.poster_id = ?", opts.PosterID)
  1254. }
  1255. if opts.MentionedID > 0 {
  1256. sess.Join("INNER", "issue_user", "issue.id = issue_user.issue_id").
  1257. And("issue_user.uid = ?", opts.MentionedID).
  1258. And("issue_user.is_mentioned = ?", true)
  1259. }
  1260. switch opts.IsPull {
  1261. case util.OptionalBoolTrue:
  1262. sess.And("issue.is_pull=?", true)
  1263. case util.OptionalBoolFalse:
  1264. sess.And("issue.is_pull=?", false)
  1265. }
  1266. return sess
  1267. }
  1268. var err error
  1269. stats.OpenCount, err = countSession(opts).
  1270. And("issue.is_closed = ?", false).
  1271. Count(new(Issue))
  1272. if err != nil {
  1273. return stats, err
  1274. }
  1275. stats.ClosedCount, err = countSession(opts).
  1276. And("issue.is_closed = ?", true).
  1277. Count(new(Issue))
  1278. return stats, err
  1279. }
  1280. // UserIssueStatsOptions contains parameters accepted by GetUserIssueStats.
  1281. type UserIssueStatsOptions struct {
  1282. UserID int64
  1283. RepoIDs []int64
  1284. UserRepoIDs []int64
  1285. FilterMode int
  1286. IsPull bool
  1287. IsClosed bool
  1288. IssueIDs []int64
  1289. }
  1290. // GetUserIssueStats returns issue statistic information for dashboard by given conditions.
  1291. func GetUserIssueStats(opts UserIssueStatsOptions) (*IssueStats, error) {
  1292. var err error
  1293. stats := &IssueStats{}
  1294. cond := builder.NewCond()
  1295. cond = cond.And(builder.Eq{"issue.is_pull": opts.IsPull})
  1296. if len(opts.RepoIDs) > 0 {
  1297. cond = cond.And(builder.In("issue.repo_id", opts.RepoIDs))
  1298. }
  1299. if len(opts.IssueIDs) > 0 {
  1300. cond = cond.And(builder.In("issue.id", opts.IssueIDs))
  1301. }
  1302. switch opts.FilterMode {
  1303. case FilterModeAll:
  1304. stats.OpenCount, err = x.Where(cond).And("issue.is_closed = ?", false).
  1305. And(builder.In("issue.repo_id", opts.UserRepoIDs)).
  1306. Count(new(Issue))
  1307. if err != nil {
  1308. return nil, err
  1309. }
  1310. stats.ClosedCount, err = x.Where(cond).And("issue.is_closed = ?", true).
  1311. And(builder.In("issue.repo_id", opts.UserRepoIDs)).
  1312. Count(new(Issue))
  1313. if err != nil {
  1314. return nil, err
  1315. }
  1316. case FilterModeAssign:
  1317. stats.OpenCount, err = x.Where(cond).And("issue.is_closed = ?", false).
  1318. Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  1319. And("issue_assignees.assignee_id = ?", opts.UserID).
  1320. Count(new(Issue))
  1321. if err != nil {
  1322. return nil, err
  1323. }
  1324. stats.ClosedCount, err = x.Where(cond).And("issue.is_closed = ?", true).
  1325. Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  1326. And("issue_assignees.assignee_id = ?", opts.UserID).
  1327. Count(new(Issue))
  1328. if err != nil {
  1329. return nil, err
  1330. }
  1331. case FilterModeCreate:
  1332. stats.OpenCount, err = x.Where(cond).And("issue.is_closed = ?", false).
  1333. And("issue.poster_id = ?", opts.UserID).
  1334. Count(new(Issue))
  1335. if err != nil {
  1336. return nil, err
  1337. }
  1338. stats.ClosedCount, err = x.Where(cond).And("issue.is_closed = ?", true).
  1339. And("issue.poster_id = ?", opts.UserID).
  1340. Count(new(Issue))
  1341. if err != nil {
  1342. return nil, err
  1343. }
  1344. case FilterModeMention:
  1345. stats.OpenCount, err = x.Where(cond).And("issue.is_closed = ?", false).
  1346. Join("INNER", "issue_user", "issue.id = issue_user.issue_id and issue_user.is_mentioned = ?", true).
  1347. And("issue_user.uid = ?", opts.UserID).
  1348. Count(new(Issue))
  1349. if err != nil {
  1350. return nil, err
  1351. }
  1352. stats.ClosedCount, err = x.Where(cond).And("issue.is_closed = ?", true).
  1353. Join("INNER", "issue_user", "issue.id = issue_user.issue_id and issue_user.is_mentioned = ?", true).
  1354. And("issue_user.uid = ?", opts.UserID).
  1355. Count(new(Issue))
  1356. if err != nil {
  1357. return nil, err
  1358. }
  1359. }
  1360. cond = cond.And(builder.Eq{"issue.is_closed": opts.IsClosed})
  1361. stats.AssignCount, err = x.Where(cond).
  1362. Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  1363. And("issue_assignees.assignee_id = ?", opts.UserID).
  1364. Count(new(Issue))
  1365. if err != nil {
  1366. return nil, err
  1367. }
  1368. stats.CreateCount, err = x.Where(cond).
  1369. And("poster_id = ?", opts.UserID).
  1370. Count(new(Issue))
  1371. if err != nil {
  1372. return nil, err
  1373. }
  1374. stats.MentionCount, err = x.Where(cond).
  1375. Join("INNER", "issue_user", "issue.id = issue_user.issue_id and issue_user.is_mentioned = ?", true).
  1376. And("issue_user.uid = ?", opts.UserID).
  1377. Count(new(Issue))
  1378. if err != nil {
  1379. return nil, err
  1380. }
  1381. stats.YourRepositoriesCount, err = x.Where(cond).
  1382. And(builder.In("issue.repo_id", opts.UserRepoIDs)).
  1383. Count(new(Issue))
  1384. if err != nil {
  1385. return nil, err
  1386. }
  1387. return stats, nil
  1388. }
  1389. // GetRepoIssueStats returns number of open and closed repository issues by given filter mode.
  1390. func GetRepoIssueStats(repoID, uid int64, filterMode int, isPull bool) (numOpen int64, numClosed int64) {
  1391. countSession := func(isClosed, isPull bool, repoID int64) *xorm.Session {
  1392. sess := x.
  1393. Where("is_closed = ?", isClosed).
  1394. And("is_pull = ?", isPull).
  1395. And("repo_id = ?", repoID)
  1396. return sess
  1397. }
  1398. openCountSession := countSession(false, isPull, repoID)
  1399. closedCountSession := countSession(true, isPull, repoID)
  1400. switch filterMode {
  1401. case FilterModeAssign:
  1402. openCountSession.Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  1403. And("issue_assignees.assignee_id = ?", uid)
  1404. closedCountSession.Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  1405. And("issue_assignees.assignee_id = ?", uid)
  1406. case FilterModeCreate:
  1407. openCountSession.And("poster_id = ?", uid)
  1408. closedCountSession.And("poster_id = ?", uid)
  1409. }
  1410. openResult, _ := openCountSession.Count(new(Issue))
  1411. closedResult, _ := closedCountSession.Count(new(Issue))
  1412. return openResult, closedResult
  1413. }
  1414. // SearchIssueIDsByKeyword search issues on database
  1415. func SearchIssueIDsByKeyword(kw string, repoIDs []int64, limit, start int) (int64, []int64, error) {
  1416. var repoCond = builder.In("repo_id", repoIDs)
  1417. var subQuery = builder.Select("id").From("issue").Where(repoCond)
  1418. var cond = builder.And(
  1419. repoCond,
  1420. builder.Or(
  1421. builder.Like{"name", kw},
  1422. builder.Like{"content", kw},
  1423. builder.In("id", builder.Select("issue_id").
  1424. From("comment").
  1425. Where(builder.And(
  1426. builder.Eq{"type": CommentTypeComment},
  1427. builder.In("issue_id", subQuery),
  1428. builder.Like{"content", kw},
  1429. )),
  1430. ),
  1431. ),
  1432. )
  1433. var ids = make([]int64, 0, limit)
  1434. err := x.Distinct("id").Table("issue").Where(cond).Limit(limit, start).Find(&ids)
  1435. if err != nil {
  1436. return 0, nil, err
  1437. }
  1438. total, err := x.Distinct("id").Table("issue").Where(cond).Count()
  1439. if err != nil {
  1440. return 0, nil, err
  1441. }
  1442. return total, ids, nil
  1443. }
  1444. // UpdateIssueByAPI updates all allowed fields of given issue.
  1445. // If the issue status is changed a statusChangeComment is returned
  1446. // similarly if the title is changed the titleChanged bool is set to true
  1447. func UpdateIssueByAPI(issue *Issue, doer *User) (statusChangeComment *Comment, titleChanged bool, err error) {
  1448. sess := x.NewSession()
  1449. defer sess.Close()
  1450. if err := sess.Begin(); err != nil {
  1451. return nil, false, err
  1452. }
  1453. if err := issue.loadRepo(sess); err != nil {
  1454. return nil, false, fmt.Errorf("loadRepo: %v", err)
  1455. }
  1456. // Reload the issue
  1457. currentIssue, err := getIssueByID(sess, issue.ID)
  1458. if err != nil {
  1459. return nil, false, err
  1460. }
  1461. if _, err := sess.ID(issue.ID).Cols(
  1462. "name", "content", "milestone_id", "priority",
  1463. "deadline_unix", "updated_unix", "is_locked").
  1464. Update(issue); err != nil {
  1465. return nil, false, err
  1466. }
  1467. titleChanged = currentIssue.Title != issue.Title
  1468. if titleChanged {
  1469. var opts = &CreateCommentOptions{
  1470. Type: CommentTypeChangeTitle,
  1471. Doer: doer,
  1472. Repo: issue.Repo,
  1473. Issue: issue,
  1474. OldTitle: currentIssue.Title,
  1475. NewTitle: issue.Title,
  1476. }
  1477. _, err := createComment(sess, opts)
  1478. if err != nil {
  1479. return nil, false, fmt.Errorf("createComment: %v", err)
  1480. }
  1481. }
  1482. if currentIssue.IsClosed != issue.IsClosed {
  1483. statusChangeComment, err = issue.doChangeStatus(sess, doer, false)
  1484. if err != nil {
  1485. return nil, false, err
  1486. }
  1487. }
  1488. if err := issue.addCrossReferences(sess, doer, true); err != nil {
  1489. return nil, false, err
  1490. }
  1491. return statusChangeComment, titleChanged, sess.Commit()
  1492. }
  1493. // UpdateIssueDeadline updates an issue deadline and adds comments. Setting a deadline to 0 means deleting it.
  1494. func UpdateIssueDeadline(issue *Issue, deadlineUnix timeutil.TimeStamp, doer *User) (err error) {
  1495. // if the deadline hasn't changed do nothing
  1496. if issue.DeadlineUnix == deadlineUnix {
  1497. return nil
  1498. }
  1499. sess := x.NewSession()
  1500. defer sess.Close()
  1501. if err := sess.Begin(); err != nil {
  1502. return err
  1503. }
  1504. // Update the deadline
  1505. if err = updateIssueCols(sess, &Issue{ID: issue.ID, DeadlineUnix: deadlineUnix}, "deadline_unix"); err != nil {
  1506. return err
  1507. }
  1508. // Make the comment
  1509. if _, err = createDeadlineComment(sess, doer, issue, deadlineUnix); err != nil {
  1510. return fmt.Errorf("createRemovedDueDateComment: %v", err)
  1511. }
  1512. return sess.Commit()
  1513. }
  1514. // DependencyInfo represents high level information about an issue which is a dependency of another issue.
  1515. type DependencyInfo struct {
  1516. Issue `xorm:"extends"`
  1517. Repository `xorm:"extends"`
  1518. }
  1519. // getParticipantIDsByIssue returns all userIDs who are participated in comments of an issue and issue author
  1520. func (issue *Issue) getParticipantIDsByIssue(e Engine) ([]int64, error) {
  1521. if issue == nil {
  1522. return nil, nil
  1523. }
  1524. userIDs := make([]int64, 0, 5)
  1525. if err := e.Table("comment").Cols("poster_id").
  1526. Where("`comment`.issue_id = ?", issue.ID).
  1527. And("`comment`.type in (?,?,?)", CommentTypeComment, CommentTypeCode, CommentTypeReview).
  1528. And("`user`.is_active = ?", true).
  1529. And("`user`.prohibit_login = ?", false).
  1530. Join("INNER", "`user`", "`user`.id = `comment`.poster_id").
  1531. Distinct("poster_id").
  1532. Find(&userIDs); err != nil {
  1533. return nil, fmt.Errorf("get poster IDs: %v", err)
  1534. }
  1535. if !util.IsInt64InSlice(issue.PosterID, userIDs) {
  1536. return append(userIDs, issue.PosterID), nil
  1537. }
  1538. return userIDs, nil
  1539. }
  1540. // Get Blocked By Dependencies, aka all issues this issue is blocked by.
  1541. func (issue *Issue) getBlockedByDependencies(e Engine) (issueDeps []*DependencyInfo, err error) {
  1542. return issueDeps, e.
  1543. Table("issue").
  1544. Join("INNER", "repository", "repository.id = issue.repo_id").
  1545. Join("INNER", "issue_dependency", "issue_dependency.dependency_id = issue.id").
  1546. Where("issue_id = ?", issue.ID).
  1547. //sort by repo id then created date, with the issues of the same repo at the beginning of the list
  1548. OrderBy("CASE WHEN issue.repo_id = " + strconv.FormatInt(issue.RepoID, 10) + " THEN 0 ELSE issue.repo_id END, issue.created_unix DESC").
  1549. Find(&issueDeps)
  1550. }
  1551. // Get Blocking Dependencies, aka all issues this issue blocks.
  1552. func (issue *Issue) getBlockingDependencies(e Engine) (issueDeps []*DependencyInfo, err error) {
  1553. return issueDeps, e.
  1554. Table("issue").
  1555. Join("INNER", "repository", "repository.id = issue.repo_id").
  1556. Join("INNER", "issue_dependency", "issue_dependency.issue_id = issue.id").
  1557. Where("dependency_id = ?", issue.ID).
  1558. //sort by repo id then created date, with the issues of the same repo at the beginning of the list
  1559. OrderBy("CASE WHEN issue.repo_id = " + strconv.FormatInt(issue.RepoID, 10) + " THEN 0 ELSE issue.repo_id END, issue.created_unix DESC").
  1560. Find(&issueDeps)
  1561. }
  1562. // BlockedByDependencies finds all Dependencies an issue is blocked by
  1563. func (issue *Issue) BlockedByDependencies() ([]*DependencyInfo, error) {
  1564. return issue.getBlockedByDependencies(x)
  1565. }
  1566. // BlockingDependencies returns all blocking dependencies, aka all other issues a given issue blocks
  1567. func (issue *Issue) BlockingDependencies() ([]*DependencyInfo, error) {
  1568. return issue.getBlockingDependencies(x)
  1569. }
  1570. func (issue *Issue) updateClosedNum(e Engine) (err error) {
  1571. if issue.IsPull {
  1572. _, err = e.Exec("UPDATE `repository` SET num_closed_pulls=(SELECT count(*) FROM issue WHERE repo_id=? AND is_pull=? AND is_closed=?) WHERE id=?",
  1573. issue.RepoID,
  1574. true,
  1575. true,
  1576. issue.RepoID,
  1577. )
  1578. } else {
  1579. _, err = e.Exec("UPDATE `repository` SET num_closed_issues=(SELECT count(*) FROM issue WHERE repo_id=? AND is_pull=? AND is_closed=?) WHERE id=?",
  1580. issue.RepoID,
  1581. false,
  1582. true,
  1583. issue.RepoID,
  1584. )
  1585. }
  1586. return
  1587. }
  1588. // ResolveMentionsByVisibility returns the users mentioned in an issue, removing those that
  1589. // don't have access to reading it. Teams are expanded into their users, but organizations are ignored.
  1590. func (issue *Issue) ResolveMentionsByVisibility(ctx DBContext, doer *User, mentions []string) (users []*User, err error) {
  1591. if len(mentions) == 0 {
  1592. return
  1593. }
  1594. if err = issue.loadRepo(ctx.e); err != nil {
  1595. return
  1596. }
  1597. resolved := make(map[string]bool, 20)
  1598. names := make([]string, 0, 20)
  1599. resolved[doer.LowerName] = true
  1600. for _, name := range mentions {
  1601. name := strings.ToLower(name)
  1602. if _, ok := resolved[name]; ok {
  1603. continue
  1604. }
  1605. resolved[name] = false
  1606. names = append(names, name)
  1607. }
  1608. if err := issue.Repo.getOwner(ctx.e); err != nil {
  1609. return nil, err
  1610. }
  1611. if issue.Repo.Owner.IsOrganization() {
  1612. // Since there can be users with names that match the name of a team,
  1613. // if the team exists and can read the issue, the team takes precedence.
  1614. teams := make([]*Team, 0, len(names))
  1615. if err := ctx.e.
  1616. Join("INNER", "team_repo", "team_repo.team_id = team.id").
  1617. Where("team_repo.repo_id=?", issue.Repo.ID).
  1618. In("team.lower_name", names).
  1619. Find(&teams); err != nil {
  1620. return nil, fmt.Errorf("find mentioned teams: %v", err)
  1621. }
  1622. if len(teams) != 0 {
  1623. checked := make([]int64, 0, len(teams))
  1624. unittype := UnitTypeIssues
  1625. if issue.IsPull {
  1626. unittype = UnitTypePullRequests
  1627. }
  1628. for _, team := range teams {
  1629. if team.Authorize >= AccessModeOwner {
  1630. checked = append(checked, team.ID)
  1631. resolved[team.LowerName] = true
  1632. continue
  1633. }
  1634. has, err := ctx.e.Get(&TeamUnit{OrgID: issue.Repo.Owner.ID, TeamID: team.ID, Type: unittype})
  1635. if err != nil {
  1636. return nil, fmt.Errorf("get team units (%d): %v", team.ID, err)
  1637. }
  1638. if has {
  1639. checked = append(checked, team.ID)
  1640. resolved[team.LowerName] = true
  1641. }
  1642. }
  1643. if len(checked) != 0 {
  1644. teamusers := make([]*User, 0, 20)
  1645. if err := ctx.e.
  1646. Join("INNER", "team_user", "team_user.uid = `user`.id").
  1647. In("`team_user`.team_id", checked).
  1648. And("`user`.is_active = ?", true).
  1649. And("`user`.prohibit_login = ?", false).
  1650. Find(&teamusers); err != nil {
  1651. return nil, fmt.Errorf("get teams users: %v", err)
  1652. }
  1653. if len(teamusers) > 0 {
  1654. users = make([]*User, 0, len(teamusers))
  1655. for _, user := range teamusers {
  1656. if already, ok := resolved[user.LowerName]; !ok || !already {
  1657. users = append(users, user)
  1658. resolved[user.LowerName] = true
  1659. }
  1660. }
  1661. }
  1662. }
  1663. }
  1664. // Remove names already in the list to avoid querying the database if pending names remain
  1665. names = make([]string, 0, len(resolved))
  1666. for name, already := range resolved {
  1667. if !already {
  1668. names = append(names, name)
  1669. }
  1670. }
  1671. if len(names) == 0 {
  1672. return
  1673. }
  1674. }
  1675. unchecked := make([]*User, 0, len(names))
  1676. if err := ctx.e.
  1677. Where("`user`.is_active = ?", true).
  1678. And("`user`.prohibit_login = ?", false).
  1679. In("`user`.lower_name", names).
  1680. Find(&unchecked); err != nil {
  1681. return nil, fmt.Errorf("find mentioned users: %v", err)
  1682. }
  1683. for _, user := range unchecked {
  1684. if already := resolved[user.LowerName]; already || user.IsOrganization() {
  1685. continue
  1686. }
  1687. // Normal users must have read access to the referencing issue
  1688. perm, err := getUserRepoPermission(ctx.e, issue.Repo, user)
  1689. if err != nil {
  1690. return nil, fmt.Errorf("getUserRepoPermission [%d]: %v", user.ID, err)
  1691. }
  1692. if !perm.CanReadIssuesOrPulls(issue.IsPull) {
  1693. continue
  1694. }
  1695. users = append(users, user)
  1696. }
  1697. return
  1698. }
  1699. // UpdateIssuesMigrationsByType updates all migrated repositories' issues from gitServiceType to replace originalAuthorID to posterID
  1700. func UpdateIssuesMigrationsByType(gitServiceType structs.GitServiceType, originalAuthorID string, posterID int64) error {
  1701. _, err := x.Table("issue").
  1702. Where("repo_id IN (SELECT id FROM repository WHERE original_service_type = ?)", gitServiceType).
  1703. And("original_author_id = ?", originalAuthorID).
  1704. Update(map[string]interface{}{
  1705. "poster_id": posterID,
  1706. "original_author": "",
  1707. "original_author_id": 0,
  1708. })
  1709. return err
  1710. }
  1711. // UpdateReactionsMigrationsByType updates all migrated repositories' reactions from gitServiceType to replace originalAuthorID to posterID
  1712. func UpdateReactionsMigrationsByType(gitServiceType structs.GitServiceType, originalAuthorID string, userID int64) error {
  1713. _, err := x.Table("reaction").
  1714. Where("original_author_id = ?", originalAuthorID).
  1715. And(migratedIssueCond(gitServiceType)).
  1716. Update(map[string]interface{}{
  1717. "user_id": userID,
  1718. "original_author": "",
  1719. "original_author_id": 0,
  1720. })
  1721. return err
  1722. }
  1723. func deleteIssuesByRepoID(sess Engine, repoID int64) (attachmentPaths []string, err error) {
  1724. deleteCond := builder.Select("id").From("issue").Where(builder.Eq{"issue.repo_id": repoID})
  1725. // Delete comments and attachments
  1726. if _, err = sess.In("issue_id", deleteCond).
  1727. Delete(&Comment{}); err != nil {
  1728. return
  1729. }
  1730. // Dependencies for issues in this repository
  1731. if _, err = sess.In("issue_id", deleteCond).
  1732. Delete(&IssueDependency{}); err != nil {
  1733. return
  1734. }
  1735. // Delete dependencies for issues in other repositories
  1736. if _, err = sess.In("dependency_id", deleteCond).
  1737. Delete(&IssueDependency{}); err != nil {
  1738. return
  1739. }
  1740. if _, err = sess.In("issue_id", deleteCond).
  1741. Delete(&IssueUser{}); err != nil {
  1742. return
  1743. }
  1744. if _, err = sess.In("issue_id", deleteCond).
  1745. Delete(&Reaction{}); err != nil {
  1746. return
  1747. }
  1748. if _, err = sess.In("issue_id", deleteCond).
  1749. Delete(&IssueWatch{}); err != nil {
  1750. return
  1751. }
  1752. if _, err = sess.In("issue_id", deleteCond).
  1753. Delete(&Stopwatch{}); err != nil {
  1754. return
  1755. }
  1756. if _, err = sess.In("issue_id", deleteCond).
  1757. Delete(&TrackedTime{}); err != nil {
  1758. return
  1759. }
  1760. if _, err = sess.In("issue_id", deleteCond).
  1761. Delete(&ProjectIssue{}); err != nil {
  1762. return
  1763. }
  1764. if _, err = sess.In("dependent_issue_id", deleteCond).
  1765. Delete(&Comment{}); err != nil {
  1766. return
  1767. }
  1768. var attachments []*Attachment
  1769. if err = sess.In("issue_id", deleteCond).
  1770. Find(&attachments); err != nil {
  1771. return
  1772. }
  1773. for j := range attachments {
  1774. attachmentPaths = append(attachmentPaths, attachments[j].RelativePath())
  1775. }
  1776. if _, err = sess.In("issue_id", deleteCond).
  1777. Delete(&Attachment{}); err != nil {
  1778. return
  1779. }
  1780. if _, err = sess.Delete(&Issue{RepoID: repoID}); err != nil {
  1781. return
  1782. }
  1783. return
  1784. }